#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define DMID 14
#include "debug.h"

#include "rstring.h"

#include "vsnprintf.h"
#include "lprintf.h"

#define rsfree(x)		{if (x) {free(x); x = NULL;}}
#define RSTRING_BUFFER	4096

void _rstring_resize(RString *s, int bytes)
{
	if (bytes < s->bytes) return ;
	s->data = realloc(s->data,bytes+1);
	s->bytes = bytes+1;
}

RString *rstring_new(int bfsz)
{
	RString *s = calloc(1,sizeof(RString));
	return s;
}
RString *rstring_new2(int bfsz)
{
    RString *s = calloc(1,sizeof(RString));
    _rstring_resize(s, bfsz);
    return s;
}

void rstring_free(RString **s)
{
	rsfree((*s)->data);
	rsfree(*s);
}

int rstring_set(RString *s, char *format, ...)
{
	char tmp[RSTRING_BUFFER];
	va_list args;
	int length;

	va_start(args,format);
	length = vsnprintf(tmp,RSTRING_BUFFER,format,args);
	va_end(args);

	if (length == RSTRING_BUFFER || length == -1)
		tmp[length = RSTRING_BUFFER-1] = 0;

	rstring_ncpy(s,tmp,length);

	return length;
}

int rstring_printf(RString *s, char *format, ...)
{
	char tmp[RSTRING_BUFFER];
	va_list args;
	int length;

	va_start(args,format);
	length = vsnprintf(tmp,RSTRING_BUFFER,format,args);
	va_end(args);

	if (length == RSTRING_BUFFER || length == -1)
		tmp[length = RSTRING_BUFFER-1] = 0;

	rstring_ncat(s,tmp,length);

	return length;
}

int rstring_copy(RString *s, char *bf)
{
	int bytes;

	for(bytes = 0; bf[bytes]; bytes++);
	return rstring_ncpy(s,bf,bytes);
}

int rstring_ncpy(RString *s, char *bf, int n)
{
	_rstring_resize(s,n);
	strncpy(s->data,bf,n);
	s->length = n;
	s->data[s->length] = 0;
	return s->length;
}

int rstring_cat(RString *s, char *bf)
{
	int bytes;

	for(bytes = 0; bf[bytes]; bytes++);
	return rstring_ncat(s,bf,bytes);
}

int rstring_ncat(RString *s, char *bf, int n)
{
	_rstring_resize(s,s->length+n);
	strncpy(&s->data[s->length],bf,n);
	s->length += n;
	s->data[s->length] = 0;
	return s->length;
}

int rstring_to_char(RString *s, char *bf, int bfsz)
{
	int length;

	length = s->length;
	if (length > bfsz-1) length = bfsz-1;

	strncpy(bf,s->data,length);
	bf[length] = 0;

	return length;
}

#define BFSZ 1000
void rstring_consume(RString *s, int n)
{
    char *src, *dst;
    int count=0;
    

    if(n<=0) return;
    
    dst = s->data;
  //  lprintf(tmp1, BFSZ,"%ld %ld", s->data, dst);  seem to be unused...
    if (n>s->length) n=s->length;
    src = s->data+n;
    for (; *src!=0 && src<s->data+s->length; dst++,src++) {
        *dst = *src;
        count++;
    }
    *dst = 0;
    
    //lprintf(tmp2, BFSZ,"%ld %ld", s->data, dst);
    s->length = (int)strlen(s->data);
}

