#include <stdio.h>
#include <stdlib.h>
#include "stdint.h"
#include <string.h>
#include <ctype.h>

#include "Inifile_Reader.h"

static char* strtrim(char* string)
{
	while (isspace(*string))
		string++;
	for (int i = strlen(string) - 1; i >= 0; i--)
	{
		if (isspace(string[i]))
		{
			string[i] = 0;
		}
		else
		{
			break;
		}
	}
	return string;
}

static char* newlines(char* string)
{
	for (char* i = string + strlen(string) - 1; i >= string; i--)
	{
		if ((*i == '\\') && (*(i+1) == 'n'))
		{
			*i = '\n';
			memmove(i+1, i+2, strlen(i+1));
		}
	}
	return string;
}

bool Inifile_Read(const char* filename, inifile_callback callback)
{
	FILE* fp = fopen(filename, "r");

	char inisection[30] = "";
	char option[30] = "";
	char value[200] = "";

	char readbuf[4096] = "";
	char* readptr;

	bool success = true;
	
	if (!fp)
		return false;
	
	while ((readptr = fgets(readbuf, sizeof(readbuf), fp))) // Loop through each line.
	{
		while (isspace(readptr[0])) // Skip whitespace.
			readptr++;

		if (readptr[0] == '\0' || readptr[0] == '#' || readptr[0] == '!') // Skip empty lines and comments.
			continue;

		if (sscanf(readptr, "[%[^]]]", inisection) == 1)
		{
		}
		else if (sscanf(readptr, "%[^=]=%[^\n]", option, value) == 2)
		{
			callback(inisection, strtrim(option), newlines(strtrim(value)));
		}
		else
		{
			success = false;
		}
	}
	
	fclose(fp);
	return success;
}

