#include <stdio.h>
#include <exec/types.h>

main(unsigned int num_arg, char * arg[])
 {unsigned char sfx[6], reply[20], file_in[40], file_out[40], cur_file[40];
  int choice;
  FILE *fin = NULL, *fout = NULL;
  void splitter(FILE *, FILE *, char *, char *, char *);
  void re_align(FILE *, FILE *);
  BOOL print_verse(FILE *fout, char *, char *, int, int, int, int *);
  void copy_icon(char *, char *);

  /* Set up window size */
  if (num_arg < 4)
   {printf("Please make certain that the window is at least 620 pixels wide\n");
    printf("and 200 pixels high.  Hit enter when ready.");
    getchar();}

  /* Introduction */
  if (num_arg < 1) printf("\n\n\nResize v2.1       by Simcha Kuritzky\n\n");
  else printf("\n\n\n%s v2.1       by Simcha Kuritzky\n\n",arg[0]);
  if (num_arg < 4)
   {printf("This program reads in an ASCII file of the Masoretic (Hebrew) Bible,\n");
    printf("and either changes the number of characters per line,  or splits the\n");
    printf("file up into smaller files on chapter boundaries.\n\n");
    if ((num_arg > 1) && (arg[1][0] == '?'))
      {printf("Expert mode is RESIZE input_file output_file choice.\n\n"); num_arg = 1;}
    printf("Do you wish to continue (y/n)? ");
    scanf(" %s",reply);
    reply[0] = toupper(reply[0]); if (reply[0] == 'N') goto end_section;}

  /* Selection */
  choice = 0;  if (num_arg > 3) sscanf(arg[3],"%d",&choice); 
  while ((choice < 1) || (choice > 3))
   {printf("\nWhich do you wish to do?\n\n");
    printf("[1]  Split a long file into smaller files (on chapter boundaries)\n");
    printf("[2]  Reformat the length of each line and change the beginning string\n");
    printf("[3]  End this program now\n");
    printf("\nWhich do you wish? \n"); scanf("%d",&choice);}
  if (choice == 3) goto end_section;

  /* Determine Input and Output File Names */
  if (num_arg > 1)
   {strcpy(file_in,arg[1]); fin = fopen(file_in,"r");
    printf("\nInput file: %s\n",file_in);}
  while (fin == NULL)
   {printf("\nWhat is the full path and name of the input file?\n");
    scanf(" %s",file_in);
    if ((fin = fopen(file_in,"r")) == NULL) printf("File not found.\n");}
  strcpy(file_out,file_in);
  if (choice == 2) {strncat(file_out,".new",5); strcpy(sfx,'\0');}
  else strcpy(sfx,".1");
  if (num_arg > 2)
   {strcpy(file_out,arg[2]); strcpy(cur_file,file_out); strcat(cur_file,sfx);
    if (file_out[strlen(file_out)-1] == '+')
     {file_out[strlen(file_out)-1] = '\0'; fout = fopen(file_out,"a");}
    else {fout = fopen(cur_file,"w"); copy_icon(file_in,cur_file);}}
  while (fout == NULL) 
   {printf("The output file will be \"%s\"\n",file_out);
    if (choice == 1)
      printf("plus a period followed by the beginning chapter number.\n");
    printf("Is this acceptable (Y/N)? \n");
    scanf(" %s",reply);
    reply[0] = toupper(reply[0]);
    if (reply[0] == 'N')
     {printf("What is the full path and name of the output file?\n");
      if (choice == 2) printf("(end with + to append) ");
      else printf("(do not include the chapter suffix.) ");
      scanf(" %s",file_out);}
    strcpy(cur_file,file_out); strcat(cur_file,sfx);
    if (file_out[strlen(file_out)-1] == '+')
     {file_out[strlen(file_out)-1] = '\0'; fout = fopen(file_out,"a");}
    else {fout = fopen(cur_file,"w"); copy_icon(file_in,cur_file);}}
  if (fout != NULL) 
    switch (choice)
     {case 1:  splitter(fin,fout,file_out,file_in,sfx); break;
      case 2:  re_align(fin,fout); break;}

  end_section:
  fclose(fin);
  printf("\nFinished.\n");
  exit(20);}

/*The Bible fonts contain certain left-to-right English characters, used in
  printing the chapter headings.  These function detects these characters.*/
int L2R(unsigned char c)
 {if (c == 96) return TRUE;
  if ((c >= 129) && (c <= 154)) return TRUE;
  if ((c >= 176) && (c <= 185)) return TRUE;
  return FALSE;}

/*The Bible files contain three kinds of characters:  those which do not
  affect the length of the line (e.g., vowel signs), those which are of
  average size, and those which are narrow.  This function is given a
  particular character, and the widths of narrow are regular letters.  It
  determines which type of character the input is, and assigns its width.*/
int char_width(unsigned char c, int narrowwid, int regwid)
 {if ((c == 39) || (c == 47) || (c == 49)) return narrowwid;
  if ((c == 32) || (c == 44) || (c == 46)) return regwid;
  if (c <= 48) return 0;
  if (c <= 58) return regwid;
  if ((c == 62) || (c == 66) || (c == 68)) return narrowwid;
  if ((c == 71) || (c == 72) || (c == 79)) return narrowwid;
  if ((c == 85) || (c == 90) || (c == 98)) return narrowwid;
  if ((c >= 92) && (c <= 96)) return narrowwid;
  if ((c == 100) || (c == 104) || (c == 105)) return narrowwid;
  if ((c == 117) || (c == 122)) return narrowwid;
  if (c <= 123) return regwid;
  return 0;}

/*This function copies the output file's icon from the input file's */
void copy_icon(char *file_in, char *file_out)
 {char icon_in[50], icon_out[50];
  int temp;
  FILE *iin,*iout;
  strcpy(icon_in,file_in); strcat(icon_in,".info");
  if ((iin = fopen(icon_in,"r")) == NULL) 
    printf("Info file not found.  Will not create icon for new file.\n");
  else
   {strcpy(icon_out,file_out); strcat(icon_out,".info");
    if ((iout = fopen(icon_out,"w")) == NULL) 
      printf("Info file not opened.  Will not create icon for new file.\n");
    else
     {while ((temp = fgetc(iin)) != EOF) fputc(temp,iout);
      fclose(iin); fclose(iout);}}
  return;}

/*This function splits the input file into smaller output files, but always
  on a chapter boundary.

  fin, fout  input and output file pointers
  file_out   base file name for output
  sfx        current suffix for output file (contains number of the first chapter in file)
  txt        current line input from file
  kb         minimum size of output file (in kilobytes)
  sz         number of bytes written to current output file
  temp       address of text, which equals NULL if end of file is reached
  l          number of lines written to output file
  i,j,k      pointers used in decoding chapter heading line (i=last space, j= chapter
             number, k = numeric value of chapter number) */
void splitter(FILE *fin, FILE *fout, char *file_out, char *file_in, char *sfx)
 {unsigned char txt[1024];
  int kb=0, l=0, i,j;
  long sz=0;
  char k, *temp, cur_file[40];
  temp = fgets(txt,1023,fin);
  printf("\n\nThis program will read in  up to  a given number of kilobytes,\n");
  printf("and then look for a chapter ending, before closing the current\n");
  printf("file and starting on the next file.   What is the minimum size\n");
  printf("of the new files (in kilobytes)?  ");
  scanf("%d",&kb);
  printf("\nCurrent output file is %s%s\n",file_out,sfx);

  while(temp != NULL)  /* read until EOF or reach kb bytes input */
   {while ((sz < kb*1024+1) && (temp != NULL))
     {fprintf(fout,"%s",txt); sz += strlen(txt);
      temp = fgets(txt,1023,fin); 
      printf("currently on line %d and file size %ld\13\n",++l,sz);}

    while ((!L2R(txt[0])) && (temp != NULL))  /* read until end of chapter */
     {fprintf(fout,"%s",txt);  sz += strlen(txt); temp = fgets(txt,1022,fin);
      printf("Currently on line %d and file size %ld\13\n",++l,sz);}

  fclose(fout); strcpy(sfx,"."); sz = 0;  /* start new output file */

  if (temp == NULL) fprintf(fout,"%s",txt);
  else  /* decode chapter heading and use it in the name of the new output file */
   {for (i = strlen(txt)-1;txt[i] != 96; i--);
    for (j = i+1; j < strlen(txt); j++)
     {k = txt[j]-128; if (k > 1) {i = strlen(sfx); sfx[i]=k; sfx[i+1]='\0';}}
    strcpy(cur_file,file_out); strcat(cur_file,sfx);
    fout = fopen(cur_file,"w"); copy_icon(file_in,cur_file);
    sz = 0; printf("\n\nCurrent output file is %s\n",cur_file);}}
  return;}

/*This function takes a verse, counts forward until the line width is greater than the line
  allows, then prints out all the characters up to the last space, and starts its count
  over again, until the verse is completely printed out.

  fout      pointer to output file
  verse     text which contains the entire verse, with no return characters
  lp        a pointer which points to first unprinted character of verse
  st        startup string, consisting of either one tab or several #229
  linelen   the maximum length of each line (in character width units)
  charwid   the width of a regular character
  narrowwid the width of a narrow character (e.g., nun, zayin, gimmel)
  no        the current output line number
  l         a counter of the total widths of all unprinted characters (thru position i)
  i         a counter of the current character within verse being examined
  istart    the value of i as of the last time characters within this verse were printed
  j         a counter which limits the number of characters printed out
  sp        a counter which tracks the position of the last space character encountered */
BOOL print_verse
(FILE *fout, char *verse, char *st, int linelen, int charwid, int narrowwid, int *no)
 {int sp=0, i=0, istart = 0, l=0;
  char *lp=verse;
  if (verse > NULL)
    while ((l < linelen) && (i < strlen(verse)))
     {int j; l += char_width(verse[i], narrowwid, charwid);
      if (verse[i] == 32) sp = i;
      if (l < linelen) {i++; continue;}
      fprintf(fout,"%s",st); 
      for (j=istart;j<sp;j++) {fputc(*(lp),fout); lp++;}
      fputc('\n',fout);
      printf("Currently on line %d\13\n",++*(no)); 
      if (i < strlen(verse)-1)
       {i = sp+1; lp++; istart = i; l = 0; sp = 0;
        if (lp > " ") continue;}}
    if (strlen(lp) > 1) fprintf(fout,"%s%s\n",st,lp);
    strcpy(verse,"");
    return (TRUE);}

void re_align(FILE *fin, FILE *fout)
 {int lg=0, linelen=0, n=0, i=0, charwid=0, narrowwid=0, bgn=0, no=0;
  unsigned char reply[20], st[99], *temp, verse[1024], txt[1024], *tp=txt;
  char nl='\0';
  printf("\nEach file is composed of Hebrew and English lines.   The chapter headers\n");
  printf("are in English, and their format never changes (they are written left to\n");
  printf("right).   The rest of the text is in right-to-left Hebrew.   Each Hebrew\n");
  printf("line is composed of two sections:  a starting string and then the actual\n");
  printf("text.   The  starting string  is required to prevent the characters from\n");
  printf("running off  the edge of  the screen.   Two types of startup strings are\n");
  printf("supported:   a  series of large left-to-right spaces (represented in the\n");
  printf("Torah fonts as alt-b or character 226), and one tab (character 9).   The\n");
  printf("following information is needed in order to  know  how  to  reformat the\n");
  printf("file.   The values that were used in the original files will be given in\n");
  printf("parentheses.\n\n");
  printf("What is the size of the large left-to-right character?\n");
  printf("(default is 40, enter 0 to use the tab character) "); 
  scanf("%d",&lg);

  strcpy(reply,"N");
  while (reply[0] != 'Y')
   {printf("\nWhat is the length of each line (70)? ");
    scanf("%d",&linelen); putchar('\n');
    if (linelen > 0)
     {if (lg == 0) n = 0; else {n = linelen/lg; if (linelen % lg > 0) n++;}
      if (lg > 0) printf("Each line will begin %d units from the left edge.",n*lg);
      printf("\nThe Hebrew text will continue to the right for %d units.",linelen);
      if (lg > 0) printf("\nThis leaves a minimum left margin of %d units.",n*lg-linelen);
      printf("\nIs this correct? ");
      scanf(" %s",reply); reply[0] = toupper(reply[0]);}}
  while (charwid == 0)
   {printf("\nWhat is the width of most characters (2)? ");
    scanf("%d",&charwid);}
  while (narrowwid == 0)
   {printf("What is the width of the narrow characters \n");
    printf("gimmel, vov, zayin, & nun (1)? ");    
    scanf("%d",&narrowwid);}
  strcpy(verse,""); printf("\n");
  if (n == 0) {st[0]='\t'; st[1]='\0';} 
  else {for (i=0;i<n;i++) st[i] = 226; st[n] = '\0';}
  temp = reply; 

  while(temp != NULL)
   {int k;
    temp = fgets(txt,1023,fin); 
    if (temp) {tp = txt; for (k = strlen(txt)-1;txt[k] < 33;k--) txt[k] = '\0';}
    else tp = &nl;
    if (L2R(txt[0]))
     {if (strlen(verse) > 0) print_verse(fout, verse,st, linelen, charwid, narrowwid, &no);
      fprintf(fout,"%s\n",txt);}
    else
     {if (bgn == 0)
       {bgn = 1; while (txt[bgn] == 226) bgn++;}
      if (temp) tp += bgn; 
      if ((*tp < 48) || (*tp > 57))
       {strcat(verse,tp); 
        strcat(verse," ");}
      else
       {print_verse(fout, verse, st, linelen, charwid, narrowwid, &no);
        strcpy(verse,tp);
        strcat(verse," ");}}}
  print_verse(fout, verse, st, linelen, charwid, narrowwid, &no);
  return;}

