#include <stdio.h> 
#include <conio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <dir.h> 
#include "txdefs.h"

/* global scope */
char Progname[MAXPATH] ;
char Path[MAXPATH] = "\0" ;
char FileName[MAXFILE] = "\0" ;
char Extension[MAXEXT] = "\0" ;
char **menu[MAX_MENUS] ;
int NumMenus = 0;
int NumEntries[MAX_MENUS] ;
int CurrDrive ;
char ch_env_size[6] ; 
/* Text colors: 
   normal ->   yellow on blue 
   selected -> black on lightgray */
int color[2]={0x1E,0x70};
/* Alternative colors: */
/* int color[2]={0x30,0x0B};  */

void SplitPath(void) ;

/* File scope */

FILE *cnf ;
char ConfigFile[MAXPATH] = "\0" ;


void main(int argc, char *argv[])
{
  void ReadConfig(void) ;
  int i, env_size = ENV_SIZE ;
  extern void TxMain(void);
  strcpy(Progname,argv[0]);
  _wscroll = 0 ;            /* Disallow scrolling */
  textattr(color[0]) ;   /* Set menu colors */
  CurrDrive = getdisk() ;
  
  for ( i = 1 ; i < argc ; i++ ) {
    if ( argv[i][0] == CNF_COMLINE ) {  /* Configuration file name */
      ++argv[i] ;
      strcpy(ConfigFile,argv[i]) ;
    }
    else if ( !strcmp(argv[i],"-h") ) { /* help */
      fprintf(stderr,MSG_USAGE,Progname,CNF_ENVVAR);
      exit(0);
    }
    else if ( !strcmp(argv[i],"-m") ) { /* monochrome */
      color[0]=0x70;
      color[1]=0x0F;
      textattr(color[0]) ;
    }
    else if ( !strcmp(argv[i],"-e") ) { /* environment size */
      i++ ; /* get next argument */
      if ( ( i == argc ) ||  ( ( env_size = atoi(argv[i]) ) < 256 ) ) {
	fprintf(stderr,MSG_USAGE,Progname,CNF_ENVVAR);
	exit(0);
      }
    }
    else { /* Working file name */
      int OldDrive=CurrDrive;
      if (Path[0]) { /* We already have a working file name */
	fprintf(stderr,MSG_USAGE,Progname,CNF_ENVVAR);
	exit(0);
      }
      strcpy(Path,argv[i]) ;
      SplitPath() ;
      setdisk(CurrDrive) ;
      if ( chdir(Path) ) {
	CurrDrive=OldDrive;
	setdisk(CurrDrive);
	Path[0]='\0';
      }
    }
  }
  
/* Set environment size for child processes as a string to be passed
   to the command processor */
  itoa(env_size,ch_env_size,10);

/* Look for environmental variable CNF_ENVVAR */
  if (!ConfigFile[0]) {
    char *ppt;
    if ( (ppt=getenv(CNF_ENVVAR)) != NULL )
      strcpy(ConfigFile,ppt) ;
  }

/* Check for default file name, "tx.cnf" (or "progname.cnf" if the user
   renamed the program to "progname.exe") being present in directory in 
   which the executable resides. This should be the normal case. */

  if (!(ConfigFile[0])) {
    char drive[MAXDRIVE] , dir[MAXDIR] , file[MAXFILE], ext[MAXEXT] ;
    fnsplit(argv[0],drive,dir,file,ext) ;
    strcpy(ext,".cnf") ;
    fnmerge(ConfigFile,drive,dir,file,ext) ;
  }

/* Print usage message and exit if no config file exists */
  if ( (cnf = fopen(ConfigFile,"r")) == NULL )  {
    fprintf(stderr,MSG_NOCONFIG,Progname);
    fprintf(stderr,MSG_USAGE,Progname,CNF_ENVVAR);
    exit(1) ;
  }

  ReadConfig() ;

/* Set working file name if not supplied by user */
  if (!Path[0]) {
    getcwd(Path,MAXPATH) ;
#ifdef __GO32__
    strcat(Path,"/") ;
#else
    strcat(Path,"\\") ;
#endif
    strcat(Path,DEF_WFN) ;
    strcat(Path,DEF_WFEXT) ;
    SplitPath();
  }
  
  TxMain() ;  /* Branch to main body of tx */
}



void ReadConfig(void)
{
  char line[1+MAX_ACTION], **cp ;
  int len , iscommand = 0 ;
  const int limit[2] = { MAX_WIDTH , MAX_ACTION } ;
  int  ReadLine(char *,int) ;
  
  NumEntries[0] = 0 ;
  menu[0]= (char **) malloc( 2 * MAX_ENTRIES * sizeof(char *) );
  cp = menu[0] ;          /* Position current pointer */
  
  while ( (len = ReadLine(line,limit[iscommand])) > 0 ) {
    if ( line[0] == NEW_MENU_SIGN ) { /* Start new menu */
      if (!NumEntries[0])
	continue ;   /* Ignore if menu 0 */
      if (iscommand) {  /* Error; were expecting a command */
	exit(3) ;
      }
      ++NumMenus ;
      if (NumMenus >= MAX_MENUS)
	break ;
      NumEntries[NumMenus] = 0 ;
      menu[NumMenus]= (char **) malloc(2*MAX_ENTRIES*sizeof(char *));
      cp = menu[NumMenus] ;           /* Position current pointer */
      continue ;
    }
    if ( NumEntries[NumMenus] >= MAX_ENTRIES )
      continue ;                       /* Ignore excess entries */
    *cp = (char *) malloc(len+1);
    strcpy(*cp,line) ;
    ++cp ;
    NumEntries[NumMenus] += iscommand ; /* New entry if it was command */
    iscommand = 1 - iscommand ;         /* Switch text/command */
  }
  fclose(cnf) ;
  return ;
}



int ReadLine(char *line,int max)
{
  int c , notin = 1 , count = 0 , wasspace = 0 ;
  
  while ( (c = fgetc(cnf)) != EOF && count < max ) {
    if ( notin ){ /* Skip whitespace while not reading a line */
      while ( isspace(c) && (c = fgetc(cnf)) != EOF ) ;
      if ( c == EOF )
	return -1 ;
      if ( c == NEW_MENU_SIGN ) { /* New menu */
	*line++ = c ;
	++count ;
	break ;   /* Do not allow any more characters */
      }
      notin = 0 ;
    }
    if ( c == COMMENT_SIGN ){  /* Skip till eol if COMMENT_SIGN */
      while ( (c = fgetc(cnf)) != EOF && c != '\n' ) ;
      if (count) /* We have read some valid characters */
	break ;
      notin = 1 ;  /* We have not read anything. Restart */
      continue ;
    }
    if ( c == '\r' )
      continue ;
    if ( c == '\n' )     /* reached end of line */
      break ;
    if ( isspace(c) ) {
      if (wasspace)
	continue ;   /* ignore extra spaces */
      wasspace = 1 ;   /* set space flag */
      c = ' ' ;        /* convert tabs to spaces */
    }
    else
      wasspace = 0 ;    /* clear space flag */
    *line++ = c ;
    ++count ;
  }
  if ( count ) {
    if (wasspace) {
      --count ;  /* Remove trailing spaces */
      --line ;
    }
    *line = '\0' ;
    return count ;
  }
  return -1 ;
}


void SplitPath(void) { 
  int flags ; 
  char drive[MAXDRIVE] , dir[MAXDIR]; 
  void StripBsl(char *) ; 
  
  flags = fnsplit(Path,drive,dir,FileName,Extension) ; 
 
  if ( flags & DRIVE ) { 
    drive[0] = toupper(drive[0]) ; 
    CurrDrive = ( (int) drive[0] ) - 'A' ; 
  } 
  else { 
    drive[0] = CurrDrive + 'A' ; 
    drive[1] = ':' ; 
    drive[2] = '\0' ; 
  } 
  
  if ( flags & DIRECTORY ) { 
    strcpy(Path,drive) ; 
    if ( dir[0] != BACKSLASH )
#ifdef __GO32__
      strcat(Path,"/");
#else
      strcat(Path,"\\");
#endif
    strcat(Path,dir) ; 
    StripBsl(Path);
  }
  else {
    Path[0]='\0';
    getcwd(Path,MAXPATH) ;
  }
  
  if ( !(flags & FILENAME) ) { 
    strcpy(FileName,DEF_WFN) ; 
    strcpy(Extension,DEF_WFEXT) ; 
  } 
} 
 
void StripBsl(char *Pname) 
{ 
  for ( ; *Pname ; Pname++);
  if ( *--Pname == BACKSLASH )
    *Pname-- = '\0';
  if ( *Pname == ':' )
    *++Pname = BACKSLASH ;
  *++Pname = '\0';
} 
 
