/* --> 'c.lowerhtml'  Martin Carradus 2003 */
/* Converts HTML selectively to lower case */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <kernel.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include "os.h"
#include <swis.h>

#define VERSION "1.12"
#define NAME "Martin Carradus"
#define  SELF         "lowerhtml"
#define  BRIEF        "Converts HTML file tags to lower case"
#define  DATE         "March 2nd 2003"
#define  OK             0
#define  BAD          1
#define TAGINC    16

/* For the purpose of messages output in panels from !LowerHTML */

struct messblock
{int errn;
  char mess[241];
  };

typedef struct messblock messblock;

/* For the testing of balancing of HTML tags */

struct tags
{int lino;
  char *tag;
  };

typedef struct tags tags;

/* List of tags */

tags *taglist;

int diagnostics=0;
int i=0;
struct tm *timeptr;
size_t maxsize=25;
time_t *timer;
int leave=0;
int nslash=0;
int all=0;
int name=0;
int href=0;
int src=0;
int line=1;
int cr=0;
int anal=0;
int maxtags=0;
int itags=0;

char *file_in;
char *file_out;
FILE *chanin;
FILE *chanout;
_kernel_swi_regs regs;

int analyse_tags(void)
{int ii,jj;
  ii=itags-1;
  if(ii>0 && !strcmp(&taglist[ii].tag[1],taglist[ii-1].tag)){
    printf("HTML Tag \'%s\' at line %d Matched at line %d\n",taglist[ii-1].tag,taglist[ii-1].lino,line);
    free(taglist[ii].tag);free(taglist[ii-1].tag);itags-=2;taglist[itags].lino=-1;
    
 } else if(ii>=0 && taglist[ii].tag[0]=='/'){
    for(jj=ii-1;jj>=0 && strcmp(&taglist[ii].tag[1],taglist[jj].tag);jj--);
    if(jj>=0){    
    printf("HTML Tag \'%s\' at line %d Matched at line %d\n",taglist[jj].tag,taglist[jj].lino,line);
    free(taglist[jj].tag);taglist[jj].tag=(char *)malloc(sizeof(char));strcpy(taglist[jj].tag,(char *)"");
    } else {
    printf("Terminating Tag \'%s\' not Matched at line %d\n",taglist[ii].tag,line);
                }
    free(taglist[ii].tag);itags-=1;taglist[itags].lino=-1;
                                                 }
 return(0);                                                
}                                                 

int close_files(void)
{char command[81];
  os_error *failure;
  int fclose_in,fclose_out;

            /* Close files and test for any error                */
                     fclose_in=fclose(chanin);
  if(fclose_in==EOF){printf("%s: Error on input file close!\n",SELF);}
                     strcpy(command,"SetType ");
                     strcat(command,file_out);
                     strcat(command," &faf");
                     failure=os_cli(command);
                     if(failure)printf("%s: Cannot set output file type to HTML!\n",SELF);
                     fclose_out=fclose(chanout);
  if(fclose_out==EOF){printf("%s: Error on output file close!\n",SELF);}
        return (0);
}

void exm(int close_flag)
{char *timestr;
  if(close_flag)close_files();
  timestr=(char *)malloc(50*sizeof(char));
  time(timer);
  timeptr=localtime(timer);
  strftime(timestr,maxsize,"%a %b %d %Y %H:%M:%S",timeptr);
  fprintf(stdout,"Ending Program on %s\n",timestr);
  free(timestr);
  exit(BAD);
  }

/* The main conversion routine */
    
int convert(void)
{int c=0,ch=0,ch2=0,ii;
  int err=0;
  int tag=0;
  int string=0;
  int name_flag=0;
  int href_flag=0;
  int src_flag=0;
  char keyword[20];
  int first=0;
  int spaces=0;
  int end=0;
  int key=0;
  int endkey=2;
  int ibm_flag=0;
  int conv_flag=0;
  int all_lower=1;
  int name_count=0;
  int href_count=0;
  int src_count=0;
  int all_count=0;
  keyword[0]='\0';
  c=ch;
  ch=fgetc(chanin);
  while(!feof(chanin) && ch!=EOF && ch2!=EOF && err!=EOF){
    if(tag && ch=='\"')string=1-string;
    if(ch=='>' && !string && tag)tag=0;
    if(ch=='<' && ch2!='!' && tag==0){tag=1;first=1;spaces=1;};
    if(ch=='\n'){line++;if(cr && c!='\x0d'){err=fputc('\x0d',chanout);ibm_flag=2;}
                                   else if(cr && ibm_flag==0)ibm_flag=1;
                                     };
    if(err!=EOF){
    if(tag && !string && ch=='\\' && !nslash){ch='/';
                                                                           if(diagnostics)printf("%s: Backwards Slash Converted at line %d\n",SELF,line);
                                                                           }
    if(tag && !string && (isalnum(ch) || ch=='/')){keyword[key++]=((leave) ? ch : tolower(ch));keyword[key]='\0';endkey=0;spaces=0;
                                                            if(keyword[key-1]!=ch){conv_flag=1;all_lower=0;};}
 else if(ch!='<' && !spaces){key=0;if(!string && endkey==0)endkey=1;if(first)end=1;};
if(tag && !string && (!strcmp(keyword,"name") || !strcmp(keyword,"NAME")) && name)name_flag=1;
    else if(!string && ch!='=')name_flag=0;
    if(tag && !string && (!strcmp(keyword,"href") || !strcmp(keyword,"HREF")) && href)href_flag=1;
    else if(!string && ch!='=')href_flag=0;
    if(tag && !string && (!strcmp(keyword,"src") || !strcmp(keyword,"SRC")) && src)src_flag=1;
    else if(!string && ch!='=')src_flag=0;
    if(!tag)err=fputc(ch,chanout);
    else if(!leave && !string)err=fputc(tolower(ch),chanout);
    else if(all && string){err=fputc(tolower(ch),chanout);
                                       if(all==1){all_count++;all=2;};
                                       }
    else if(name_flag && string){err=fputc(tolower(ch),chanout);
                                                     if(name_flag==1){name_count++;name_flag=2;};
                                                     }
    else if(href_flag && string){err=fputc(tolower(ch),chanout);
                                                     if(href_flag==1){href_count++;href_flag=2;};
                                                  }
    else if(src_flag && string){err=fputc(tolower(ch),chanout);
                                                     if(src_flag==1){src_count++;src_flag=2;};
                                                }
    else err=fputc(ch,chanout);
    if(!string && all==2)all=1;
    if(anal && first && end){first=0;end=0;
if(strcmp(keyword,"IMG") && strcmp(keyword,"img") && strcmp(keyword,"META") && strcmp(keyword,"meta") && strcmp(keyword,"BR") && strcmp(keyword,"br") && strcmp(keyword,"HR") && strcmp(keyword,"hr")){
                                                                    if(maxtags==0){maxtags+=TAGINC;
                                                                                         taglist=(tags *)malloc((maxtags+1)*sizeof(tags));
                                                                     } else if(itags>=maxtags){
                                                                                                maxtags+=TAGINC;
                                                                               taglist=(tags *)realloc(taglist,(maxtags+1)*sizeof(tags));
                                                                                                               }
     taglist[itags].lino=line;
     taglist[itags].tag=(char *)malloc((strlen(keyword)+1)*sizeof(char));
     strcpy(taglist[itags].tag,keyword);
     itags++;
     taglist[itags].lino=-1;
     analyse_tags();
               }
       }     
        
    if(tag && diagnostics && endkey==1 && conv_flag){printf("%s: Tag Keyword \'%s\' Converted at line %d\n",SELF,keyword,line);endkey=2;keyword[0]='\0';conv_flag=0;}
    else if(tag && diagnostics && endkey==1){printf("%s: Tag Keyword \'%s\' Unaltered at line %d\n",SELF,keyword,line);endkey=2;keyword[0]='\0';}
                   }
    if(err!=EOF){c=ch;
                          ch=fgetc(chanin);
                           if(ch!=EOF){ch2=fgetc(chanin);
                             if(ch2!=EOF)ch2=ungetc(ch2,chanin);
                                               }
                          }
                        }
  if(ch!=EOF)err=fputc(ch,chanout);
  if(!feof(chanin) && (ch==EOF || ch2==EOF)){printf("%s: Byte Error in input file on line %d -Terminating!\n",SELF,line);
                         exm(1);
                         }  
  if(err==EOF){printf("%s: Byte Error in ouput file on line %d -Terminating!\n",SELF,line);
                         exm(1);
                         }
    if(diagnostics && strcmp(keyword,"") && conv_flag)printf("%s: Tag Keyword \'%s\' Converted at line %d\n",SELF,keyword,line);
    else if(diagnostics && strcmp(keyword,""))printf("%s: Tag Keyword \'%s\' Unaltered at line %d\n",SELF,keyword,line);
    if(anal && first){first=0;
if(strcmp(keyword,"IMG") && strcmp(keyword,"img") && strcmp(keyword,"META") && strcmp(keyword,"meta") && strcmp(keyword,"BR") && strcmp(keyword,"br") && strcmp(keyword,"HR") && strcmp(keyword,"hr")){
                                                                    if(maxtags==0){maxtags+=TAGINC;
                                                                                         taglist=(tags *)malloc((maxtags+1)*sizeof(tags));
                                                                     } else if(itags>=maxtags){
                                                                                                maxtags+=TAGINC;
                                                                               taglist=(tags *)realloc(taglist,(maxtags+1)*sizeof(tags));
                                                                                                               }
     taglist[itags].lino=line;
     taglist[itags].tag=(char *)malloc((strlen(keyword)+1)*sizeof(char));
     strcpy(taglist[itags].tag,keyword);
     itags++;
     taglist[itags].lino=-1;
     analyse_tags();
          }
        }
  if(anal){if(itags>0){for(ii=0;taglist[ii].lino!=-1;ii++)
    {
if(strcmp(taglist[ii].tag,(char *)""))printf("HTML Tag \'%s\' at line %d Unmatched at End of File\n",taglist[ii].tag,taglist[ii].lino);
      free(taglist[ii].tag);
    };free(taglist);
       }
    }
    
  if(all && all_count==0)printf("%s: No Quoted Strings Converted\n",SELF);
  else if(all && all_count==1)printf("%s: One Quoted String Converted\n",SELF);
  else if(all)printf("%s: %d Quoted Strings Converted\n",SELF,all_count);
  if(name && name_count==0)printf("%s: No NAME Quoted Strings Converted\n",SELF);
  else if(name && name_count==1)printf("%s: One NAME Quoted String Converted\n",SELF);
  else if(name)printf("%s: %d NAME Quoted Strings Converted\n",SELF,name_count);
  if(href && href_count==0)printf("%s: No HREF Quoted Strings Converted\n",SELF);
  else if(href && href_count==1)printf("%s: One HREF Quoted String Converted\n",SELF);
  else if(href)printf("%s: %d HREF Quoted Strings Converted\n",SELF,href_count);
  if(src && src_count==0)printf("%s: No SRC Quoted Strings Converted\n",SELF);
  else if(src && src_count==1)printf("%s: One SRC Quoted String Converted\n",SELF);
  else if(src)printf("%s: %d SRC Quoted Strings Converted\n",SELF,src_count);  
  if(ibm_flag==1)printf("%s: Warning: HTML File already in IBM Format\n",SELF);
  if(all_lower)printf("%s: Warning: All Keywords remain Unaltered\n",SELF);
  close_files();
  return(0);
  }

/* Function makes description messages from !BBC_C RISC OS 3 compatible */
/* Does not sound bell */

int descmess(int fatal,char *format,char *str1,char *str2,char *str3)
{messblock *block;
  int i;
  char *message;
  block=(messblock *)malloc(sizeof(messblock));
  message=(char *)malloc(241*sizeof(char));
  sprintf(message,format,str1,str2,str3);
  block->errn=fatal;
  i=0;
  while(message[i]!='\0' && i<240){block->mess[i]=message[i];i++;};
  block->mess[i]='\0';
  regs.r[0]=(int)block;
  regs.r[1]=0x81;
  regs.r[2]=(int)SELF;
  _kernel_swi(Wimp_ReportError,&regs,&regs);
  free(message);
  free(block);
  return(0);
  }

/* Function makes help messages from !BBC_C RISC OS 3 compatible */
/* Does not sound bell */

int infomess(int fatal,char *format,char *str1,char *str2,char *str3,char *str4,char *str5)
{messblock *block;
  int i;
  char *message;
  block=(messblock *)malloc(sizeof(messblock));
  message=(char *)malloc(241*sizeof(char));
  sprintf(message,format,str1,str2,str3,str4,str5);
  block->errn=fatal;
  i=0;
  while(message[i]!='\0' && i<240){block->mess[i]=message[i];i++;};
  block->mess[i]='\0';
  regs.r[0]=(int)block;
  regs.r[1]=0x81;
  regs.r[2]=(int)SELF;
  _kernel_swi(Wimp_ReportError,&regs,&regs);
  free(message);
  free(block);
  return(0);
  }

/* Gives help on selection of -H switch                                    */

static void give_help(void)
{char *timestr;
  infomess(0, "Help Information: %s [%s] %s Version %s - %s.. Put input file name in slot provided. File is processed and offered for saving.",NAME,DATE, SELF, VERSION, BRIEF);
  infomess(0, "Help Information: %s [%s] %s Version %s - %s.. For further information use the Acorn !Help facility, or select Help from the bar icon menu.",NAME,DATE, SELF, VERSION, BRIEF);
  timestr=(char *)malloc(50*sizeof(char));
  time(timer);
  timeptr=localtime(timer);
  strftime(timestr,maxsize,"%a %b %d %Y %H:%M:%S",timeptr);
  fprintf(stdout,"Ending Program on %s\n",timestr);
  free(timestr);
  exit(OK);
}

/* Description of program                                                  */

static void describe_function(void)
{char *timestr;
  descmess(0,"Description: %s [%s] %s: Translates an HTML file to one with chosen tags made lower case. Input the HTML file name in the slot provided.",NAME,DATE, SELF);
  descmess(0,"Description: %s [%s] %s: The file is processed and a window appears giving the option of saving. The output file is the translated HTML with the same name prefixed by \'L\'",NAME,DATE, SELF);
  timestr=(char *)malloc(50*sizeof(char));
  time(timer);
  timeptr=localtime(timer);
  strftime(timestr,maxsize,"%a %b %d %Y %H:%M:%S",timeptr);
  fprintf(stdout,"Ending Program on %s\n",timestr);
  free(timestr);
  exit(OK);
}

/* Main program                                                            */

int main(argc, argv)
int argc;
char *argv[];
{
  char *arg;
  static char *cur_name;
  int j, nerr;
  char *timestr;
  /* Proprietary info */
  fprintf(stdout," %s %s %s %s [%s]\n",NAME,SELF,"Version",VERSION,DATE);
  /* Starting message with date and time */
  timeptr=(struct tm *)malloc(sizeof(struct tm));
  timer=(time_t *)malloc(sizeof(time_t));
  timestr=(char *)malloc(50*sizeof(char));
  time(timer);
  timeptr=localtime(timer);
  strftime(timestr,maxsize,"%a %b %d %Y %H:%M:%S",timeptr);
  fprintf(stdout,"Starting Program on %s\n",timestr);

  /*                                                             */
    /* parse help or identify args */
  for (j = 1;  j < argc;  ++j) {
    arg = argv[j];
    if (strcmp("-help", arg) == 0 || strcmp("-h", arg) == 0 ||
        strcmp("-HELP", arg) == 0 || strcmp("-H", arg) == 0)
      give_help();
  }

  file_in = file_out = NULL;
  nerr = diagnostics = 0;
  for (j = 1;  j < argc;  ++j) {
    arg = argv[j];
    if (arg[0] == '-') {
      if (arg[1] == 'z' || arg[1] == 'Z')
        ++diagnostics;
      else if (arg[1] == 'd' || arg[1] == 'D') {
        describe_function();
        exit(OK);
              }
         else if(!strcmp(arg,"-leave")){
           ++leave;
               }
         else if(!strcmp(arg,"-nslash")){
           ++nslash;
               }
           else if(!strcmp(arg,"-all")){
           ++all;
               }
           else if(!strcmp(arg,"-name")){
           ++name;
               }
           else if(!strcmp(arg,"-href")){
           ++href;
               }
         else if(!strcmp(arg,"-src")){
           ++src;
               }
         else if(!strcmp(arg,"-cr")){
           ++cr;
               }
         else if(!strcmp(arg,"-anal")){
           ++anal;
               }                             
        else {
        printf("%s: unknown flag '%s'\n",SELF,arg);
        ++nerr;
      }
      } else {
      if (file_in == NULL) file_in = arg;
      else if (file_out == NULL) file_out = arg;
      else {
        printf("%s: too many filenames: '%s' ignored\n",SELF,arg);
      }
    }
  }

  if (nerr) exm(0);

  if (file_in && file_out)
  { chanin = fopen(file_in, "rb");
    if (chanin == NULL)
    { printf("%s: can't open input file '%s'\n",
                      SELF, file_in);
                      exm(0);
    }
  }
  else chanin = NULL;
  if (chanin == NULL)
  {
    give_help();
  }
  else cur_name = file_in;

  if (file_out) chanout = fopen(file_out, "w");
  else chanout = NULL;
  if (chanout == NULL) chanout = stdout;

  printf("Converting HTML file \'%s\' to Lower Case...\n",file_in);

  convert();

  time(timer);
  timeptr=localtime(timer);
  strftime(timestr,maxsize,"%a %b %d %Y %H:%M:%S",timeptr);
  fprintf(stdout,"Ending Program on %s\n",timestr);
  free(timestr);
  exit(OK);
}
