#include <string.h>
#include <sys/xboxkrnl.h>
#include <stdlib.h>


#include "pconfig.h"
#include "ntfile.h"
#include "I2C.h"
#include "debug.h"

void GetParm(char *szBuffer, char *szOrig) {
	char *ptr,*copy;
	int nBeg = 0;
	int nCopy = 0;

	copy = szBuffer;
	for(ptr = szOrig;*ptr != 0;ptr++) {
		if(*ptr == ' ') nBeg = 1;
		if(*ptr != ' ' && nBeg == 1) nCopy = 1;
		if(nCopy == 1) {
			*copy = *ptr;
		 	copy++;
		}
	}
	*copy = 0;
}

CONFIGENTRY * GetConfig(char *szDrive) {
	char *filename;
	PUCHAR Buffer;
	ULONGLONG lFileSize = 0;
	CONFIGENTRY *entry;
	
	filename = (char *)MmAllocateContiguousMemoryEx(BUFFERSIZE,MIN_KERNEL,
			MAX_KERNEL, 0, PAGE_READWRITE);
	entry = MmAllocateContiguousMemoryEx(sizeof(CONFIGENTRY),MIN_KERNEL,
			MAX_KERNEL, 0, PAGE_READWRITE);

	memset(entry,0,sizeof(CONFIGENTRY));
	strcpy(filename, szDrive);
	strcat(filename, CONFIG_FILE);

	Buffer = LoadFile(filename, lFileSize);

	if(Buffer == NULL) {
		Die("Error loading config file");
	}

	ParseConfig(szDrive,Buffer,entry);

	MmFreeContiguousMemory(filename);
	MmFreeContiguousMemory(Buffer);
	return entry;
}

int ParseConfig(char *szPath,char *szBuffer, CONFIGENTRY *entry) {
	char *szTmp;
	BYTE VideoStandard[4];
	char *ptr;
	//,ptr1;
	int i;
	char szDelim[2];
	
        szTmp = (char *)MmAllocateContiguousMemoryEx(MAX_LINE,MIN_KERNEL,
	                        MAX_KERNEL, 0, PAGE_READWRITE);

	for(i = 0; i < 4 ; i++) {
		VideoStandard[i] = I2CTransmitByteGetReturn(0x54, 0x58 + i);
	}
	
	memset(entry,0,sizeof(CONFIGENTRY));
	
	ptr = szBuffer;
	szDelim[0] = 10;
	szDelim[1] = 0;
	ptr = strtok(szBuffer,szDelim);

	entry->timeout = 150000;
	entry->nValid = 1;
	strcpy(entry->szPath,szPath);
	while(1) {
                if(strlen(ptr) > 0) {
			if(ptr[strlen(ptr) - 1] == 13) ptr[strlen(ptr) - 1] = 0;
		}
		if(strlen(ptr) < MAX_LINE) {
			if(strncmp(ptr,"RC4Key",strlen("RC4Key")) == 0) {
				GetParm(szTmp, ptr);
				strcpy(entry->szRC4Key, szTmp);
			}
			if(strncmp(ptr,"EEPROMKey1_0",strlen("EEPROMKey1_0")) == 0) {
				GetParm(szTmp, ptr);
				strcpy(entry->szEEPROMKey1_0, szTmp);
			}
			if(strncmp(ptr,"EEPROMKey1_1",strlen("EEPROMKey1_1")) == 0) {
				GetParm(szTmp, ptr);
				strcpy(entry->szEEPROMKey1_1, szTmp);
			}

			if(strncmp(ptr,"LEDSequence",strlen("LEDSequence")) == 0)  {
				GetParm(szTmp, ptr);
				strcpy(entry->szLED, szTmp);
			}
			if(strncmp(ptr,"Debug",strlen("Debug")) == 0)  {
				GetParm(szTmp, ptr);
				if (strncmp(szTmp,"true",strlen("true")) == 0) {
					entry->DebugFlag = TRUE;
				}
			}
			if(strncmp(ptr,"Romfile",strlen("Romfile")) == 0)
			{
				GetParm(szTmp, ptr);
				strcpy(entry->szRom,szPath);
				strcat(entry->szRom,"Bioses\\");
				strcat(entry->szRom,szTmp);
			}
			if(strncmp(ptr,"Timeout",strlen("Timeout")) == 0)
			{
				GetParm(szTmp, ptr);
				entry->timeout = strtol(szTmp,NULL,10);
			}
		} else {
			entry->nValid = 0;
		}
		ptr = strtok(0,szDelim);
		if(ptr == 0) break;
	}


	
	
	MmFreeContiguousMemory(szTmp);

	return entry->nValid;
}
