#include <stdio.h>


#include "defines.h"
#include "configuration.h"


void ReadVariables(FILE *fileptr,
		   void AssignFunction(char *VariableName, char *value));
int GetWord(FILE *fileptr, char *Word, char EndOfWord, int MaxSize);
int IgnoreCommentsAndSpaces(FILE *fileptr, char *c);
void TerminateVariable(char *variable);
int GoToEndOfLine(FILE *fileptr);


void ReadVariables(FILE *fileptr,
		   void AssignFunction(char *VariableName, char *value))
{
  char VariableName[MAX_NAME_LENGTH], Value[MAX_NAME_LENGTH];

  while(GetWord(fileptr, VariableName, '=', MAX_NAME_LENGTH)) {
    if (!GetWord(fileptr, Value, '\n', MAX_NAME_LENGTH)) {
      return;
    }
    AssignFunction(VariableName, Value);
  }
  return;
}


int GetWord(FILE *fileptr, char *Word, char EndOfWord, int MaxSize)
{
  char *c;
  int i=1;

  c=Word;

  if (IgnoreCommentsAndSpaces(fileptr, c)) {
    return(0);
  }
  c++;

  while((*c=fgetc(fileptr)) != EndOfWord) {
    i++;
    if (*c==EOF || i>MaxSize) {
      return(0);
    }
    c++;
  }
  TerminateVariable(Word);

  return(1);
}


int IgnoreCommentsAndSpaces(FILE *fileptr, char *c)
{
  while((*c=fgetc(fileptr))!=EOF) {
    // Check For Comment
    if (*c=='/' || *c=='#' || *c==';') {
      if (GoToEndOfLine(fileptr)) {
	return(1);
      }
    // Ignore White Spaces
    } else if (*c != ' ' && *c != '\n' && *c != '\t') {
      return(0);
    }
  }
  return(1);
}


void TerminateVariable(char *variable)
{
  while(*variable!='=' && *variable!=' ' && *variable!='\t' && *variable!='\n'
	&& *variable!='/' && *variable!='#' && *variable!=';') {
    variable++;
  }
  *variable='\0';
}


int GoToEndOfLine(FILE *fileptr)
{
  char c;

  while((c=fgetc(fileptr))!=EOF) {
    if (c=='\n') {
      return(0);
    }
  }

  return(1);
}
