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

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(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(char *cpApp, char *cpKey, char *cpRxt)
int ReadProfile(char *cpKey, char *cpRxt)
{

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

    fp = fopen(cfgname, "r");

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

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

    for(;;)
    {
        fgets(cpBuf,MAX_BUF, fp);
        if(feof(fp) )
            break;
        cpPtr = makeToken(cpBuf, cpTmp);

        if(strcmp(cpTmp, cpKey) == 0)
        {
            cpPtr = makeToken(cpPtr, cpRxt);
            fclose(fp);
            return 1;
        };
    };

    fclose(fp);
    return -4;
}

void SetIniName(char *name)
{
    strcpy(cfgname, name);
}

int GetProfileInt(char *spart, int dval)
{
    int rxt;
    char    buf[100];
    rxt = ReadProfile(spart,buf);

    if(rxt < 0)
        return dval;

    return (int)Str2Dec(buf);
}

char* GetProfile(char *spart, char *rval, char *dval)
{
    int     rxt;

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

    return rval;
}
