/* vstring.c
   implement variable length strings */

   /* these routines were inspired by those in STRstring.* from the
      gopher Unix client, version 0.9.  The main reason for changing
      them at all is that the chosen data type name in the original
      routines, String, conflicts with the X Window System data
      type of the same name, but different type. */

#include <stdio.h>
#include "vstring.h"
#if !defined(NeXt) && !defined(sequent)
#include <malloc.h>
#endif
#if defined(sequent)
char	*malloc();
char	*realloc();
#endif


/* vStringSet
   set the value of a variable length string, length and data */

void vStringSet(vs, value)
vString *vs;
char	*value;
{
	int	need;

	if (value == NULL) return;

	if (*value == '\0') 
		need = 1;
	else
		need = strlen(value) + 1;
	
	fprintf (stderr, "previous len: %d  ", vs->len);
	if (vs->data == NULL) {
		if (need < 128) need = 128;
		fprintf (stderr, "null string -> %d bytes\n", need);
		if ((vs->data = malloc (need * sizeof(char *))) == NULL) {
			fprintf (stderr,
				"Cannot allocate more memory for a string.");
			exit(1);
		}
		strcpy (vs->data, value);
		vs->len = need;
	} else {
		fprintf (stderr, "%d bytes -> %d bytes\n", vs->len, need);
		if (vs->len >= need)
			strcpy(vs->data, value);
		else {
			fprintf (stderr, "(realloc)\n");
			vs->data = realloc(vs->data, need);

			strcpy(vs->data, value);
			vs->len = need;
		}
	}
}


/* Some of these routines are not used in this release */
#ifdef NOT_YET 


/* vStringDestroy
   destroy a variable length string, content and structure */

void 
vStringDestroy(vs)
vString *vs;
{
	if (vs->data != NULL)
		free(vs->data);
	
	free(vs);
}


/* vStringNew
   Allocate a new variable length string structure, initialized to NULL */

vString *
vStringNew()
{
	vString	*vs;

	if ((vs = (vString *) malloc (sizeof(struct vStringStruct))) == NULL) {
		fprintf (stderr, "Cannot allocate more memory for a string.");
		exit(1);
	}

	vStringInit(vs);

	return (vs);
}

#endif /* NOT_YET */
