#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "lib.h"
#include "sini.h"
static char *ini_list[1200];
static char *ini_val[1200];
#define FALSE 0
#ifndef TRUE 
#define TRUE (!FALSE)
#endif

#include "defines.h"
int sini_init(char *vini_list[])
{
	int i;
	for (i=0; vini_list[i]!=NULL;i++) {
		ini_list[i] = strdup(vini_list[i]);
	}
	return TRUE;
}
int sini_load(char *fname, char *reason)
{
	FILE *f;
	char *s;
	int i;
	char var[BFSZ];
	char val[BFSZ];
	char *x;
	int ret=TRUE;
	char bf[BFSZ];
	f = fopen(fname,"r");
	if (f==NULL) {
		sprintf(reason,"%s %s",fname,strerror(errno));
		return FALSE;
	}
	for (;!feof(f);) {
		if (fgets(bf,BFSZ-1,f)==NULL) break;
		s = mystrtok(bf," ",&x);
		if (s==NULL) continue;
		ncpy(var,s,BFSZ-1);
		s = mystrtok(NULL,"\r\n",&x); if (s==NULL) continue;
		ncpy(val,s,BFSZ-1);
		for (i=0; ini_list[i]!=NULL;i++) {
			if (strcmp(ini_list[i],var)==0) {
				ini_val[i] = strdup(val);
				break;
			}
		}
		if (ini_list[i]==NULL) {
			sprintf(reason,"invalid setting %.100s",var);
			ret = FALSE;
		}
	}
	return ret;
}
char *sini_get(int ivar)
{
	if (ini_val[ivar]==NULL) return "";
	return ini_val[ivar];
}
int sini_true(int ivar)
{
	if (ini_val[ivar]==NULL) return FALSE;
	if (strcmp(sini_get(ivar),"true")==0) return TRUE;
	if (strcmp(sini_get(ivar),"True")==0) return TRUE;
	if (strcmp(sini_get(ivar),"TRUE")==0) return TRUE;
	return FALSE;
}

