#include "..\..\lib\8000a.h"
#include <stdio.h>
#include <string.h>
#include "ini.h"



void parseSec(char* secStr,char* resStr);
int HighRamMode;
extern int bNeedDisableHighRam;


int ReadLine(FILE *f, char *bp,int findex)
{   char c = '\0';
    int i = 0,j=0;
    /* Read one line from the source file */   
    
    if(findex>=f->size)
    	return 0;
    for(i=findex;i<f->size;i++)
    {
    	if(f->addr[i]=='\n'||f->addr[i]=='\r')
    		break;
    	bp[j++]=f->addr[i];    	
    }
    bp[j] = '\0';   
   
    return(i+1);
}

int GetINIString(char *section, char *key, char *defaultStr,
    char *valStr, int buffer_len ,int disk, char *file_name)
{   
	FILE *fp;
    char buff[MAX_LINE_LENGTH],temp[MAX_LINE_LENGTH];
    char *ep;
    int i;
    int secBegin=-1, secEnd=-1;
    int fIndex=0;
    char t_section[MAX_LINE_LENGTH];
    int len = strlen(key);
    
    if(disk==0)
    {
		if(bNeedDisableHighRam) 
		{
			HighRamMode=GetHighRamMode();
			DisableHighRam();
		} 
		fp = GetFileInfoByName(file_name);
	}
	else
	{	
    	fp = GetFileInfoByName_AB(1,file_name); 
    }    
   
    if( !fp ) return(0);
    sprintf(t_section,"[%s]",section);    /* Format the section name */
    /*  Move through file 1 line at a time until a section is matched or EOF */
     while(fIndex<fp->size)
     {
     	fIndex=ReadLine(fp,temp,fIndex);
     	
	     	if(secBegin<0)
	     	{
		    	parseSec(temp,buff);
		    	
		     	if(strncmp(buff,t_section,strlen(t_section))==0)
		     	{		     		
		     		secBegin=1;
		     	}		     	
		    }
		    else
		    {
		    	if(temp[0]=='[')
		    	{		    		
		    		break;
		    	}
		    	else
		    	{
		    		if(strncmp(temp,key,len)==0)
		    		{		    			
		    			ep = strrchr(temp,'=');    /* Parse out the equal sign */
	   					ep++;
	   					/* Copy up to buffer_len chars to buffer */
	   					strncpy(valStr,ep,strlen(temp));   
	   					
		    			secEnd=1;
		    			break;	    			
		    		}
		    	}
		    }
		}
     	
        
    if(secEnd==-1)
     	strcpy(valStr,defaultStr);
    valStr[i+1] = '\0';
    if(disk==0)
    {
		if(bNeedDisableHighRam) {
			SetHighRam(HighRamMode);
		}
	}    
    return(strlen(valStr));
}

void parseSec(char* secStr,char* resStr)
{
	int i,j=0;
	int len=strlen(secStr);
	for(i=0;i<len;i++)
	{
		if((secStr[i]!=0x20)&&(secStr[i]!=0x0d)&&(secStr[i]!=0x0a)&&(secStr[i]!=0x09))
			resStr[j++]=secStr[i];
	}
	resStr[j]='\0';
}