/*****************************************************************/
/* functions for the #help command                               */
/*****************************************************************/
#include <ctype.h>
#include "tintin.h"
#include <stdlib.h>

void help_command(arg)
  char *arg;
{
  FILE *myfile;
  char *cptr, text[80], line[80], temp_ch, filestring[300];
#if COMPRESSED_HELP
  char sysfile[BUFFER_SIZE];
#endif
  int  tmp,flag, counter;
  flag=TRUE;
  if (!strncmp(DEFAULT_FILE_DIR, "HOME", 4))
    sprintf(filestring, "%s/.tt_help.txt", getenv("HOME"));
  else sprintf(filestring, "%s/.tt_help.txt", DEFAULT_FILE_DIR);
#if COMPRESSED_HELP
  sprintf(sysfile, "%s %s", DEFAULT_EXPANSION_STR, filestring);
  system(sysfile);
#endif
  if((myfile=fopen(filestring, "r"))==NULL) {
    tintin_puts2("#Help text not found, no help available.", NULL);
    prompt(NULL);
    return;
  }
  if (*arg) {
    sprintf(text, "~%s", arg);
    cptr=text;
    
    while (*++cptr) {
      *cptr=toupper(*cptr);
    }
    while (flag) {
      fgets(line, sizeof(line), myfile);
      if (*line=='~') {
        if (*(line+1)=='*') {
          tintin_puts2("#Sorry, no help on that word.", (struct session *)NULL);
          flag=FALSE;
        }
        else if(is_abrev(text,line)) {
          counter=0;
          while (flag) {
            fgets(line, sizeof(line), myfile);
            if (*line=='~') 
              flag=FALSE;
            else {
              *(line+strlen(line)-1)='\0';
              tintin_puts2(line, (struct session *)NULL);
            }
            if (flag && (counter++>23)) {
              alarm(0);
              tintin_puts2("[ -- Press a key to continue -- ]",
		(struct session *)NULL);
	      getchar();
              alarm(1);
              counter=0;
            }
          }
        }
      }
    }
  }
  else {
    while(flag) {
      fgets(line, sizeof(line), myfile);
      if (*line=='~') 
        flag=FALSE;  
      else {
        *(line+strlen(line)-1)='\0';
        tintin_puts2(line, (struct session *)NULL);
      }
    }
  }
  prompt(NULL);
  fclose(myfile);
#if COMPRESSED_HELP
  sprintf(sysfile, "%s %s", DEFAULT_COMPRESSION_STR, filestring);
  system(sysfile);
#endif
}
