/* this would be a cross-platform configuration file module thingy */

#include <stdio.h>
#include <string.h>

int read_config_var(char *, char *, char []);
int write_config_var(char *, char *, char []);

int read_config_var(char *values_file, char *keyword, char value[])
{
  static char str[100];
  int len;
  FILE *file;

  if(keyword == NULL) return(-1);

  len = strlen(keyword);

  if(len > 97) return(-2);

  if(values_file)
  {
    file = fopen(values_file, "r");
    if(file == NULL) return(-1);
  }

  else
    return(-2);

  if(fseek(file, 0, SEEK_SET))
  {
    fclose(file);
    return(-1);
  }

  for(;;)
  {
    fgets(str, 100, file);
    if(ferror(file) || feof(file)) return(-2);
    len = strlen(str);

    if(strncmp(keyword, str, strlen(keyword)) == 0)
    {
      if(str[len - 1] == '\n') str[--len] = 0;
      sprintf(value, "%s", &str[strlen(keyword)+1]);
      break;
    }
  }

  fclose(file);
  return 0;
}

/* must fix write_config_var */
/* may 16 [WD] */

int write_config_var(char *values_file, char *keyword, char value[])
{
  static char str[100];
  int len;
  FILE *file;

  if(keyword == NULL) return(-1);

  len = strlen(keyword);

  if(len > 97) return (-2);

  if(values_file)
  {
    file = fopen(values_file, "r+");
    if(file == NULL) return(-1);
  }

  else
    return(-2);

  if(fseek(file, 0, SEEK_SET))
  {
    fclose(file);
    return(-1);
  }

  for(;;)
  {
    fgets(str, 100, file);
    if(ferror(file) || feof(file)) return(-2);
    len = strlen(str);

    /* FIX ME!!! */

    if(strncmp(keyword, str, strlen(keyword)) == 0)
    {
      if(str[len - 1] == '\n') str[--len] = 0;
      fprintf(file, "%s", value);
      break;
    }


  }

  fclose(file);
  return 0;
}
