
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//#include <dir.h>

#include <strings.h>
#include <lists.h>


/*This function read one line from the text file and store it to the string.*/
string & fGets2(FILE *f, string & pstr)
{
  char c;

  pstr="";
  while (!feof(f))
     {
     c = getc(f);
     if (c == '\n') break;
     if (c == '\r') continue;
     if ((unsigned char)c == 0xFF)
	if(feof(f)) break;	//Fix the situation, when 0xFF is read before eof

     pstr += c;
     }

 return(pstr);
}


list MkFile;


int main (int argc, char *argv[])
{
FILE *F;
string line;
int i,ModCnt;
int *moduls;
char *CurLine;
int State;

printf("<<<MenuConfig>>> Configurator of X2LaTeX (c)2002-2003 Jaroslav Fojtik\n");
if(argc<=1) {printf("Empty command line\n");return(0);}

if( (F=fopen(argv[1],"rt"))==NULL ) {printf("no file %s\n",argv[1]);return(-2);}
while(!feof(F))
    {
    fGets2(F, line);
    MkFile+=line;
    }
fclose(F);

moduls=(int *)calloc(length(MkFile),sizeof(int));
ModCnt=0;
for(i=0;i<length(MkFile);i++)
	{
	line=MkFile[i];
	if("OBJECTS+=" IN line)
		{
		moduls[ModCnt]=i;
		ModCnt++;
		}
	}

Again:
 for(i=0;i<ModCnt;i++)
	{
	CurLine=MkFile[moduls[i]];
	State=*CurLine!='#';
	if(*CurLine=='#') CurLine++;
	while(*CurLine!='#' && *CurLine!=0)
	   {
	   CurLine++;
	   }
        if(*CurLine=='#') CurLine++;
	printf("%c %s %s\n",'A'+i,State?"*On*":" -- ",CurLine);
	}

printf("Press ENTER to exit, or a letter A, B or ... to select/unselect component   ");
i=toupper(getc(stdin));

if(i!=13 && i!=10)
	{
	getc(stdin);
	if(i<'A' || i>='A'+ModCnt) goto Again;
	i-='A';
	line=MkFile[moduls[i]];
	if(line[0]=='#') line=copy(line,1,length(line)-1);
		    else line='#' + line;
	MoveSTRPos(MkFile,line.ExtractString(),moduls[i]);
	printf("-----------------------------------------------------\n");
	goto Again;
	}


if( (F=fopen(argv[1],"wt"))==NULL ) {printf("cannot write to file %s\n",argv[1]);return(-3);}
for(i=0;i<length(MkFile);i++)
    {
    fprintf(F,"%s\n",MkFile[i]);
    }
fclose(F);

return(0);
}



/*This procedure displays errors that occured inside atoms unit*/
//#ifdef ERROR_HANDLER
void RaiseError(int ErrNo,void *Instance)
{
static int LastErrNo=0;
static void *LastInstance=NULL;
char *UnitName="";
  if(LastErrNo!=ErrNo || LastInstance!=Instance)
    {
    if((ErrNo&0xFF00)==ListsId) UnitName=" Lists";
    if((ErrNo&0xFF00)==StringsId) UnitName=" Strings";
    fprintf(stderr,"\nERROR: Internal inside ATOMS unit%s 0x%X object:(%p)",
	UnitName,ErrNo,Instance);
    LastErrNo=ErrNo;LastInstance=Instance;
    }
}
//#endif