

#include "magic.h"
#include <ctype.h>


static String magic_comment = NULLSTRING;

int magicGetChar(FILE *fp)
{
  register int ic;

  if (fp == NULL)
    return EOF;
  
  if (magic_comment == NULLSTRING) {
    magic_comment = strNew(100);
    
    if (magic_comment == NULLSTRING)
      return EOF;
  }

  ic = getc(fp);

  if (ic == EOF) return (ic);
  
  if ((char) ic == '#')	{
    do {
      ic = getc(fp);
      if (ic == EOF) return EOF;

      strAddChar(magic_comment, (char) ic);
    } while ((char) ic != '\n');
  }

  return ic;
}


int magicGetInt(FILE *fp, int *xp)
{
  register int x;
  register int ic;

  while (isspace(((char) (ic = magicGetChar(fp)))))
    ;

  if (!isdigit(ic)) {
    return -1;
  }

  for (x = 0; ic != EOF  &&  isdigit((char) ic); ic = magicGetChar(fp))
    x = x*10 + (char) ic - '0';

  if (ic != EOF  &&  xp != NULL)
    *xp = x;
  
  return ((ic == EOF) ? -1 : 0);
}


int magicGetString(FILE *fp, String *sp)
{
  int ic;
  
  if (sp == (String *) NULL  ||  fp == (FILE *) NULL) {
    return -1;
  }

  if (*sp == (String) NULL) {
    *sp = strNew(10);
  }

  if (*sp == (String) NULL) {
    return -1;
  }
  
  while (isspace(((char) (ic = magicGetChar(fp)))))
    ;

  for (strClear(*sp); ic != EOF  &&  !isspace((char) ic); ic = magicGetChar(fp))
    strAddChar(*sp, (char) ic);

  return (ic == EOF) ? -1 : 0;  
}


int magicGetFloat(FILE *fp, float *xp)
{
  static String string = (String) NULL;

  if (magicGetString(fp, &string)) {
    return -1;
  }
 
  if (sscanf(strGet(string), "%f", xp) != 1) {
    return -1;
  }

  return 0; 
}


int magicStart()
{
  if (magic_comment == NULLSTRING) {
    magic_comment = strNew(100);
    
    if (magic_comment == NULLSTRING)
      return -1;
  }

  strClear(magic_comment);
  return 0;
}


String magicComment()
{
  return strNewCopy(magic_comment);
}
