#include <stdio.h>
#include "util.h"
#include "gmap.h"
#include "strings.h"

UINT   string_length(s) STRING s; {
       return strlen(s);
       }

STRING string_copy(s) STRING s; {
       UINT n = string_length(s);
       STRING t = (STRING) malloc (n + 1);
       UINT i;
       for (i = 0; i <= n; i ++) t[i] = s[i];
       return t;
       }

UINT   string_hash(s) STRING s; {
       UINT i = 0;
       while (*s != 0) {
           i += (*s++ & 0x3f);
	   i = (i << 5) + (i >> 27);
           }
       return i;
       }

UINT   string_equal(s,t) STRING s,t; {
       return strcmp(s,t) == 0;
       }

UINT   string_compare(s,t) STRING s,t; {
       return strcmp(s,t);
       }

STRING string_read_line(fd)
     FILE * fd; 
{
  char buffer[256];
  int i = 0;
  int rc = getc(fd);
  while (rc != EOF && rc != '\n') {
    buffer[i] = rc;
    i++;
    rc = getc(fd);
  }
  buffer[i] = 0;

  if (i == 0 && rc == EOF) return 0;
  else return string_copy(buffer);
}

STRING string_read_fmt(fd, fmt)
     FILE * fd; char * fmt;
{
  char buffer[256];
  int rc = fscanf(fd, fmt, buffer);

  return rc == 1 ? string_copy(buffer) : 0;
}

STRING string_write_fmt(fd, fmt, s)
     FILE * fd; char * fmt;
     STRING s;
{
  fprintf(fd, fmt, s);
}

int    string_free(s) STRING s; { FREE(s);}

GMAP new_string_map() {
  return g_new_map(string_hash, string_free, string_copy, string_equal);
}
