#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cfgconfig.h>

char    cfgname[60];

long Str2Dec(char *cpHex)
{
	char cpBuf[100];
	int nLen,nLoop;
	long lnResult=0,lnMultiple=1;

	strcpy(cpBuf,cpHex);
	if(strncmp(cpBuf,"0x",2)==0)
		strcpy(cpBuf,cpBuf+2);
	else
		return atol(cpBuf);

	nLen = strlen(cpBuf);
	for(nLoop=nLen-1;nLoop>=0;nLoop--)
	{
		if(cpBuf[nLoop]>='0'&&cpBuf[nLoop]<='9')
			lnResult += ((cpBuf[nLoop]-'0')*lnMultiple);
		else if(cpBuf[nLoop]>='A'&&cpBuf[nLoop]<='F')
			lnResult += ((cpBuf[nLoop]-'A'+10)*lnMultiple);
		else if(cpBuf[nLoop]>='a'&&cpBuf[nLoop]<='f')
			lnResult += ((cpBuf[nLoop]-'A'+10)*lnMultiple);

		lnMultiple *=16;
	}

	return lnResult;
}
		
char *	makeToken(cpApp, cpRxt)
char *cpApp;
char *cpRxt;

{
	int	loop;
	int in = 0;
	int	leng;

	leng = strlen(cpApp);

	for(loop=0; loop < leng; loop ++)
	{
		if(cpApp[loop] == '#') 
		{
			cpRxt[0] = '\0';
			return &cpApp[leng];
		};

		if((cpApp[loop] == ' ') || (cpApp[loop] == '\t') || (cpApp[loop] == '=') ||  (cpApp[loop] == '\n') )
			continue;
		
		for(loop; loop < leng; loop ++)
		{
			if((cpApp[loop] == ' ') || (cpApp[loop] == '\t') || (cpApp[loop] == '=') ||  (cpApp[loop] == '\n') )
			{
				cpRxt[in] ='\0';
				return &cpApp[loop];
			};
			cpRxt[in++] = cpApp[loop];
		};
	};
	cpRxt[in] ='\0';
	return &cpApp[loop];
}

int	ReadProfile(cpApp, cpKey, cpRxt)
char *cpApp;
char *cpKey;
char *cpRxt;
{

	char cpBuf[MAX_BUF];
	char cpTmp[MAX_BUF];
	char cpAppBuf[MAX_BUF];
	char *cpPtr;
	FILE *fp;

	sprintf(cpAppBuf,"[%s]", cpApp);

	fp = fopen(cfgname, "r");

	if(fp == NULL)
	{
		return -1;
	};

	if( (strlen(cpApp) < 1) || (strlen(cpKey) < 1) ) return -2;

	for(;;)
	{
		fgets(cpBuf,MAX_BUF, fp);
		if(feof(fp) )
		{
			fclose(fp);
			return -3;
		};
		
		cpPtr =  makeToken(cpBuf, cpTmp);
		
		if(strcmp(cpTmp, cpAppBuf) == 0)
			break;
	};

	for(;;)
	{
		fgets(cpBuf,MAX_BUF, fp);
		if(feof(fp) )
			break;

		cpPtr = makeToken(cpBuf, cpTmp);

		if( (cpTmp[0] == '[') && (cpTmp[strlen(cpTmp) -1] == ']') ) return -2;

		if(strcmp(cpTmp, cpKey) == 0)
		{
//			printf("%s, %s\n", cpTmp, cpKey);
			cpPtr = makeToken(cpPtr, cpRxt);
			fclose(fp);
			return 1;
		};
	};

	fclose(fp);
	return -4;
}
						
void	SetIniName(name)
char    *name;
{
	strcpy(cfgname, name);
}

int	GetProfileInt(part, spart, dval)
char	*part;
char	*spart;
int	dval;
{

	int	rxt;
	char	buf[100];
	rxt = ReadProfile(part, spart,buf);

	if(rxt < 0)
		return dval;

	return (int) Str2Dec(buf);
}

char	*GetProfile(part, spart, rval, dval )
char    *part;
char    *spart;
char	*rval;
char    *dval;

{
	int     rxt;

    rxt = ReadProfile(part, spart,rval);
	if(rxt < 0)
	{
		strcpy(rval, dval);
		return dval;
	}

	return rval;
}
