#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <stdio.h>
#include <string.h>
#include "buffer.h"


Buffer *CreateBuffer(char *name, int initial, int increment, int limit) {
	Buffer *b;
	
	if (strlen(name)>8)
		XtError("CreateBuffer name too long.");
	b=(Buffer*) XtMalloc(sizeof(Buffer));
	b->buf = XtMalloc(initial);
	b->buf[0] = '\0';
	strcpy(b->name, name);
	b->buf_size = initial;
	b->increment = increment;
	b->limit = limit;
	b->str_size = 0;
	return b;
	}

void FreeBuffer(Buffer *b) {
	XtFree(b->buf);
	XtFree((char*) b);
	}

void ClearBuffer(Buffer *b) {
	b->buf[0]='\0';
	b->str_size=0;
	}

int EmptyBuffer(Buffer *b) {
	return (b->str_size==0);
	}

int BufferSize(Buffer *b) {
	return b->str_size;
	}

void AddToBufferN(Buffer *b, char *str, int n) {
	char buf[80];

	if (b->str_size + n >= b->buf_size -1) {
		if (b->buf_size + b->increment > b->limit) {
			sprintf(buf, "%s: buffer overflow", b->name);
			XtError(buf);
			}
		while (b->str_size + n >= b->buf_size -1)
			b->buf_size += b->increment;
		b->buf=XtRealloc(b->buf, b->buf_size);
		/* printf("%s: %d\n", b->name, b->buf_size); */
		}

	strncpy(b->buf + b->str_size, str, n);
	b->str_size += n;
	b->buf[b->str_size] = '\0';
	}

void AddToBuffer(Buffer *b, char *str) {
	AddToBufferN(b, str, strlen(str));
	}
