calisto-20000323/
calisto-20000323/lib/
calisto-20000323/lib/etc/
calisto-20000323/lib/players/
calisto-20000323/lib/text/
calisto-20000323/log/
/*
 Calisto (c) 1998-1999 Peter Howkins, Matthew Howkins, Simon Howkins

 $Id: inifile.c,v 1.1 1999/12/29 17:53:09 peter Exp $

 $Log: inifile.c,v $
 Revision 1.1  1999/12/29 17:53:09  peter
 Initial revision


 */

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

#include "config.h"
#include "strplus.h"

static char rcsid[] = "$Id: inifile.c,v 1.1 1999/12/29 17:53:09 peter Exp $";

static FILE *inifile = NULL;

int inifile_open(const char *filename)
{
  inifile = fopen(filename, "r");
  return (inifile ? 0 : 1);
}

void inifile_close(void)
{
  if (inifile)
    fclose(inifile);
}

int inifile_get_token(const char *token_name, const char *format, void *value)
{
  char line[1024];
  int len;
  unsigned lineno = 0;

  /* Rule out file not being open */
  if (!inifile)
    return 1;

  rewind(inifile);
  while (fgets(line, sizeof(line), inifile)) {
    char *token;
    char *gap;
    char *val;
    int quoted = 0;

    lineno++;
    /* All but the last line will probably have a newline on the end */
    len = strlen(line);
    if (line[len - 1] == '\n')
      line[len - 1] = '\0';

    /* Remove leading whitespace */
    token = line;
    while (*token && isspace(*token))
      token++;

    /* Ignore comments and blank lines */
    if (*token == '\0' || *token == '#')
      continue;
 
    /* Find end of token */
    gap = token;
    while (*gap && (isalpha(*gap) || *gap == '_'))
      gap++;
    val = gap;

    /* Ignore whitespace (before =) */
    while (*val && isspace(*val))
      val++;

    /* Check for = */
    if (*val++ != '=') {
      fprintf(stderr, "inifile: error on line %u\n", lineno);
      continue;
    }

    /* Ignore more whitespace (after =) */
    while (*val && isspace(*val))
      val++;
    
    /* Terminate token with '\0' */
    *gap = '\0';

    /* Find end of value (first whitespace character or end-of-line */
    if (*val == '\"') {
      val++;
      quoted = 1;
    }
    gap = val;
    if (quoted) {
      while (*gap && *gap != '\"')
        gap++;
    } else {
      while (*gap && !isspace(*gap))
        gap++;
    }
    *gap = '\0';

/*    printf("%s %s (quoted = %d)\n", token, val, quoted);*/

    if (STRIEQ(token, token_name)) {
      if (STREQ(format, "%s")) {
        strcpy(value, val);
      } else {
        sscanf(val, format, value);
      }
      return 0;
    }
  }

  return 1;
}