/** 
 *  _   _        _  _                           _             
 * | |_| |  ___ | || |  ___   __ _  _ __  _ __ (_)  ___  _ __ 
 * |  _  | / _ \| || | / __| / _` || '__|| '__|| | / _ \| '__|
 * | | | ||  __/| || || (__ | (_| || |   | |   | ||  __/| |   
 * |_| |_| \___||_||_| \___| \__,_||_|   |_|   |_| \___||_|   
 * 
 *  (c) 2001 Free Lunch Design, Teknisk-IT, AerotechTelub
 *			  http://www.freelunchdesign.com
 * 
 * This source code is released as is under GPL (General Public
 * License). Please refer to license.txt for more information.
 * 
 */
 
#include <stdio.h>
#include <string.h>
#include "allegro.h"
#include "config.h"

	
config::config() {
	for(int i=0;i<MAX_POSTS;i++)
		post[i].used = FALSE;
}

config::~config() {
}

void config::set_post(int index, char *k, char *d) {
	if (index < 0 || index >= MAX_POSTS) return;

	strcpy(post[index].key, k);  
	strcpy(post[index].data, d);  
	post[index].used = TRUE;
}

int config::load_data(char *fname) {
	FILE *fp;
	char buf[128];
	char *ret;
	char k[32], d[32];
	int row = 0;

	if (!exists(fname)) return 0;

	fp = fopen(fname, "rt");
    ret = fgets(buf, 128, fp);  // read a line
	while(ret != NULL) {
		if (buf[0] != '#' && buf[0] != ' ') {
			int i=0;
			while(buf[i] != ' ' && i<32) {
				k[i] = buf[i];
				i++;
			}
			k[i] = NULL;

			while(buf[i] == ' ' || buf[i] == '=' && i<128) i++;

			int j=0;
			while(buf[i] != ' ' && buf[i] != '\n' && j<32) {
				d[j] = buf[i];
				i++; j++;
			}
			d[j] = NULL;

			set_post(row, k, d);

			row++;
		}
	    ret = fgets(buf, 128, fp);  // read a line
	}
	fclose(fp);

	return row;
}

void config::get_data_string(char *key, char *dest) {
	for(int i=0;i<MAX_POSTS;i++)
		if (post[i].used)
			if (!stricmp(post[i].key, key)) {
				strcpy(dest, post[i].data);
				return;
			}

	dest = NULL;
}


int config::get_data_int(char *key) {
	for(int i=0;i<MAX_POSTS;i++)
		if (post[i].used)
			if (!stricmp(post[i].key, key)) 
				return atoi(post[i].data);

	return 0;
}

float config::get_data_float(char *key) {
	for(int i=0;i<MAX_POSTS;i++)
		if (post[i].used)
			if (!stricmp(post[i].key, key)) 
				return atof(post[i].data);

	return 0;
}


