summaryrefslogtreecommitdiff
path: root/language/tibetan/steiner/ttt.c
blob: c5765dce58935bf5a07bab2041e3e0fa714e8478 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
/***********************************************************************/
/***********************************************************************/
/*                                                                     */
/*                    Tibetan Transcript Translator                    */
/*                                                                     */
/***********************************************************************/
/***********************************************************************/
/* 
   (C) Dec 1996 / Jan, Feb 1997 by 
   Beat Steiner, Brunngasse 12, 3011 Bern, Switzerland
   e-mail: Beat.Steiner@gseved.admin.ch
   Version 0.1 alpha prerelease


   LEGAL STUFF
   -----------
   Refer to GNU General Public License (feel free to use and distribute
   this program at your own risk but at no cost, keeping copyright 
   notices intact).

   
   DESCRIPTION
   -----------
   This program is intended to convert different transcript standards
   of the Tibetan language or even to perform a transcript import into 
   a document processing system.

   At present, it is able to convert transcripts to LaTeX, based
   on Jeff sparkes' and / or Sam Sirlin's fonts and ideas. Since I
   got into trouble to reverse engineer Sparkes' code, I have rewriten
   the complete transcript translator, only picking some ideas from his
   code.

   The main additional feature is fully automatic ligature generation,
   openness towards different transcript standards and inline LaTeX
   command support.

   The main disadvantages are: 
   ** Sparkes' and Sirlin's language mix handling is not supported yet.
   ** vovels on tsa, tsha, dza (resp. TZA, TSA, DZA) do not look nice. 

   WARNING: the ttd file format is still subject to change.
   If you create your own ttd files now, you risk to spend much work
   on updating them.


   INSTALLING
   ----------
   Install Sam Sirlin's fonts from the CTAN archive
   tex/language/tibetan/sirlin
   to the appropriate directory or set the Tex font path.
   Do the same with the tfm files. Look at the README file 
   for help on this. If you dont have metafont, use Jeff Sparkes' 
   pk and tfm files.

   This is a single file program which can be compiled without 
   complication by
   gcc ttt.c -o ttt
   or
   cc ttt.c -o ttt
   or whatever ANSI compliant C compiler you have.


   STARTING THIS PROGRAM
   ---------------------
   In order to translate ACIP to LaTeX, use

   ttt acip.ttd latex.ttd input.tib output.tex

   where acip.ttd   is the input  transcript definition file   
   .     latex.ttd  is the output transcript definition file
   .     input.tib  is your ACIP input text
   .     output.tex is the output file to be processed by latex
 
   On Linux, you will enjoy the feature of magic line support:
   In your input.tib file, add the following two lines at the
   VERY TOP (replacing the respective filenames):

   #!/bin/sh
   ttt acip.ttd latex.ttd $0 output.tex; latex output; exit

   Due to the magic line at the top, (ba)sh will think that your text 
   input.tib is a shell script, executing the 2nd line. 
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   This program will ignore the FIRST AND THE SECOND 
   line if the FIRST line starts with #!
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   Do not put anything, even not comments above these lines. 
   $0 is automatically replaced by the file name (e.g. input.tib).

   Then turn your input.tib file into an executable by
   chmod 755 input.tib

   Now, you can start this program by entering 
   input.tib
   at the shell command prompt.

   DOS users, please write an apropriate *.BAT file (without $0). 
   Windows users may set the command line options as program properties.


   RETURN VALUES
   -------------
   0: Normal program completion.
   1: x___error occurred (unknown input key, missing output ligature
   .                      and such) 
   2: Could not open a file or bad number of command line arguments
   3: Static memory allocation overrun


   IMPLEMENTATION NOTICE
   ---------------------
   This kind of implementation was motivated by the need of importing
   texts typed at Sera Monastery into the ClearLook document 
   processing system and solving other conversion problems like 
   differences between ACIP and Wiley transcripts plus the need to 
   import both of them into LaTeX, ClearLook, Lout and other programs. 
   
   Therefore, a very flexible solution based on Tibetan Transcript 
   Definition (ttd) files has been chosen. 
   They map the different transcribed letters, control sequences
   and ligatures (btags pa) to common keys.
   
   example: ACIP --> LaTeX conversion for the letter 'tsa
   the acip.ttd file says:
   c___tsa	TZ
   which associates the key 'tsa' to the value 'TZ'
   the tex.ttd file says:
   c___tsa	\tibetan\char16
   which associates the key 'tsa' to the tex font chracter.

   The magic characters before the transcript key have the following
   meaning:

   1st char:
   c: normal consonant
   p: potential prefix (negative bias for ligature generation)
   b: potential btagspa (simplified lower part of ligatureand ha, 
      positive bias for ligature generation)
   .: punctuation (Terminates syllable and suppresses tsheg)
   x: program control

   2nd char and 3rd char:
   reserved for generic ligature generation (join styles, 
   character substitution)

   4th char:
   _: just to increase readability of ttd file
   
   Meaning of x___ keys:

   General controls:
   x___preamble	     Will be at top of output without being asked for
   x___postamble     Will be at bottom of output without being asked for
   x___error	     Error message included to output file

   Generic ligatures:
   x___inner_box{    Encapsulation of individual characters (no vovels)
   x___inner_box}    
   x___outer_box{    Encapsulation of whole ligature without vovel
   x___outer_box}

   Mixed language handling (subject to change, not fully implemented yet)
   x___transp_word   Input will be put out without modification til space
   x___transp_char   Unmodified character passing
   x___transp_reg{   Unmodified region passing start
   x___transp_reg}   end
   x___transp_reg~   toggle


   WARNING: The values of the input ttd and the keys of the output
   ttd file MUST be unique, otherwise the result is undefined.
   
   The input stream is scanned for the largest matched value in the
   input ttd file, giving the common key. A lookup in the output ttd
   file generates the output stream.
   
   The ligature generation is a special issue documented at the 
   rather complicated if construct in the main function.


   To Do:
   ------

   ** Better char comparison in ttread
   ** Write documentation
   ** allow comments in ttd files
   ** Warn on ambiguous transcript (gyin, gyas, ...)
   ** Full support of Sirlin and Sparkes
   ** Mixed language support 
   Two flags allow mixing Tibetan, other languages and control sequences:
   'active' 	says wether or not the lookup and ligature generation
   .            take place or not. If not,
   'transparent' says wether the input stream is passed unmodified to
   .            the output stream or simply be ignored (crunched).

   ** Clean escape char handling for binary output
  
   ** More intelligence for Generic Ligatures
   ** Font: Character fragments for generic ligatures
   ** Vertically stretched (50% or 75%) chars for generic ligatures
   ** Mirrored gigu

   ALMOST DONE
   -----------
   ** Clean up and update comments and program style
   ** Read filenames from command line 
   .    (unflexible, no default handling, magic lines for linux only)
   ** Vovel support for generic ligatures (still a LaTeX problem to solve)
   ** (Only) two vovels on a character supported

   PERFORMANCE
   -----------
   The actual lookup process is performed by a binary search although
   a hash table lookup is expected to be about 5 times faster. This is
   just caused by my not being that much familiar with C++ and g++.
   Furtheron, bsearch is better documented and available on more 
   compilers.
   This program needs less than 1 second to produce 6 a4paper output pages
   on my 5x86 machine. So there are more important problems to solve now.
   */

/***********************************************************************/
/*                May this program contribute to the                   */
/*                  Dharma practice of many people                     */
/***********************************************************************/

/******************************/
/******************************/
/*                            */
/*        Includes            */
/*                            */
/******************************/
/******************************/

#include <stdio.h>
#include <stdlib.h>   /* contians qsort and bsearch */
#include <string.h>


/******************************/
/******************************/
/*                            */
/* Static Memory Allocations  */
/*                            */
/******************************/
/******************************/

const int MAX_SYL_SIZE_LINE = __LINE__ + 1;
#define MAX_SYL_SIZE 50
/* maximum characters per syllable (ligature complexity)
   very cheap and should be enough
   */

const int MAX_KEY_VAL_LENGTH_LINE = __LINE__ + 1;
#define MAX_KEY_VAL_LENGTH 44
/* maximum ttd key/value length
   critical for output preamble
   hint: try to include the preamble
   */

const int TTSIZE_LINE = __LINE__ + 1;
#define TTSIZE 300
/* transcript table size
   critical for predefined ligatures
   keep in mind that you add an appropriate command margin
   to the number of characters in your font.
   */

const int INPUT_LINEBUFFER_LENGTH_LINE = __LINE__ + 1; 
#define INPUT_LINEBUFFER_LENGTH 180
/* Maximum line length of input text file */


/******************************/
/******************************/
/*                            */
/*       Global stuff         */
/*                            */
/******************************/
/******************************/

typedef struct
{
  char key[MAX_KEY_VAL_LENGTH];
  char val[MAX_KEY_VAL_LENGTH];
} ttentry;

char ESCAPE_CHAR='\xff';
int KEY_LEN[MAX_KEY_VAL_LENGTH];
int X_ERROR_OCCURRED = 0;
static FILE *OUTTEXT;

/******************************/
/******************************/
/*                            */
/*         Functions          */
/*                            */
/******************************/
/******************************/

void trace(char *message)
{
  /*
  if (message == NULL)
    {
      fprintf(stderr, "<NULL>");
      fflush(stderr);
    }else{
      fprintf(stderr, "<%s>", message);
      fflush(stderr);
    }
  */
}


/******************************/

/* clean interface for strncmp */
int ttcmp(const void *first, const void *second) 
{
  return strncmp(((ttentry*)first)->key, ((ttentry*)second)->key, 
		 MAX_KEY_VAL_LENGTH); }


/******************************/

void ttprepare(ttentry ttable[])
{
  qsort(&ttable[0], TTSIZE, sizeof(ttentry), ttcmp);
}


/******************************/

char *ttlookup(const char *key, const ttentry ttable[])
{
  ttentry *found=NULL;

  if (key)
    {
      found=(ttentry*)bsearch(key, ttable, TTSIZE, 
			      sizeof(ttentry), ttcmp);

      if (found)
	{
	  return found->val;
	}else{
	  return NULL;
	}
    }
}


/******************************/

void ttread(const char *name, int swap, ttentry ttable[])
{
  /* This procedure reads the transcript definition files.
     The first column MUST be strictly left aligned.
     'name' is the filenamae
     'swap' is a flag which swaps the key/value reading order:
     file contents for swap=0:
     <key> <value>
     file contents for swap=1:
     <value> <key>
     'ttable' is the transcript table where the file is read into.
     'TTSIZE' is allocated statically and needed to avoid an 
     index overflow
     */
  char c = ' ';  /* not EOF */
  char *cp = NULL;
  char *cp_start = NULL;  /* Needed for ptr range check */
  FILE *ttd = NULL;
  int idx = 0;

  void CheckCP(void)
    {
      if ((cp - cp_start) >= (MAX_KEY_VAL_LENGTH - 1))
	{
	  fprintf(stderr, "Insufficient static memory allocation. ");
	  fprintf(stderr, "Please increase MAX_KEY_VAL_LENGTH in ");
	  fprintf(stderr, "line %d of %s and compile again.\n",
		  MAX_KEY_VAL_LENGTH_LINE, __FILE__);
	  exit(3);
	}
    }
  
  /* Clear array storing input ttd key length flags
     for boosting performance in charparse() */
  for (idx = 0; idx < MAX_KEY_VAL_LENGTH; idx++)
    {
      KEY_LEN[idx] = 0;
    }
  idx = 0;

  /* Clear transcript table struct arrays */
  for (idx = 0; idx < TTSIZE; idx++)
    {
      *ttable[idx].key = '\0';
      *ttable[idx].val = '\0';
    }
  idx = 0;


  if (!(ttd = fopen(name, "r") ))
    {
      fprintf(stderr, "%s %s\n", "could not open ttd file ", name);
      exit(2);
    }


  /* ev. better with strpbrk() */
  while (c != EOF && idx < TTSIZE)
    {
      /* Read ttd keys/values */
      if (swap) cp = ttable[idx].val;
      else      cp = ttable[idx].key;

      cp_start = cp;

      c = fgetc(ttd);
      while ( c != ' ' && c != '\t' && c != '\n' && c != EOF)
	{
	  *cp++ = c; CheckCP();
	  c=fgetc(ttd);
	}
      *cp++ = '\0'; CheckCP();

      /* Eliminate separtor garbage */
      while ( c == ' ' || c == '\t' )
	{ c = fgetc(ttd);
	}

      /* Read ttd values/keys */
      if (swap) cp = ttable[idx].key;
      else      cp = ttable[idx].val;

      cp_start = cp;
      while ( c != '\t' && c != '\n' && c != EOF ) 
	/* ev. add comment char and spaces */
	{ 
	  *cp++ = c; CheckCP();
	  c = fgetc(ttd);
	}
      *cp++ = '\0'; CheckCP();

      /* Eliminate trailing garbage */
      while ( c != '\n' && c != EOF )
	{ c = fgetc(ttd);
	}

      /* mark existing key lengths */
      KEY_LEN[strlen(ttable[idx].key)] = !0;

      idx++;
    }
  if (idx >= TTSIZE)
    {
      fprintf(stderr, "Insufficient memory allocation. Please increase");
      fprintf(stderr, 
	      " TTSIZE in line %d of %s and compile again.\n", 
	      TTSIZE_LINE, __FILE__);
      exit(3);
    }
}


/******************************/

void prepare_flags(ttentry inptrans[], ttentry outtrans[], 
		   int *active, int *transparent) 
{
  char *charptr;

  /* Set activity flag according to INPUT ttd */
  charptr=ttlookup("x___init_active", inptrans);
  if (charptr)
    {
      if ( strcasecmp("yes", charptr) == 0 )
	{ *active = 1;    }else{      *active = 0;
	}
    }

  /* Set transparency flag according to OUTPUT ttd */
  charptr=ttlookup("x___init_transprent", outtrans);
  if (charptr)
    {
      if ( strcasecmp("yes", charptr) == 0 )
	{ *transparent = 1;    }else{      *transparent = 0;
	}
    }


  /* Set escape character
     In this release, escapechar is only accepted if it is the first
     char in the output ttd */

  charptr=ttlookup("x___escape_char", outtrans);
  if (charptr)
    {
      ESCAPE_CHAR = *charptr;
    }
}


/******************************/

char *charparse(const char *input, int *parsestep,
                const ttentry *inptrans) 
{
  char yigcpy[MAX_KEY_VAL_LENGTH+1];
  char *charptr=NULL;
  int parselen;
  int yiglen;

  strncpy(yigcpy, input, MAX_KEY_VAL_LENGTH);
  parselen=strlen(input);
  if (parselen > MAX_KEY_VAL_LENGTH) parselen=MAX_KEY_VAL_LENGTH;
  yiglen=parselen;

  while (yiglen > 0 && charptr == NULL)
    {
      yigcpy[yiglen] = '\0';
      if (KEY_LEN[yiglen]) charptr = ttlookup(yigcpy, inptrans);
      yiglen--;
    }
  *parsestep=yiglen+1;
  return charptr;
}


/******************************/

void yigprint(char *yig, 
              ttentry *outtrans)
{
  char *charptr=NULL;
  if (yig != NULL)
    {
      charptr=ttlookup(yig, outtrans);
      if (charptr)
	{
	  /* DIRTY: detects escape char only if it is the first one. */
	  if (*charptr != ESCAPE_CHAR)
	    {
              if (*charptr != '\0') fprintf(OUTTEXT, "%s", charptr);
	      /* fflush(OUTTEXT); */
	    }else{
	      charptr++;	/* skip the escape char itself */
	      fprintf(OUTTEXT, "%c", (char)strtol(charptr, NULL, 0));
	      /* fflush(OUTTEXT); */
	    }
	}else{ /* no output ttd match */
	  X_ERROR_OCCURRED = !0;
	  fprintf(OUTTEXT, "%s", ttlookup("x___error", outtrans));
	  fflush(OUTTEXT);
	  trace(yig);
	}
    }else{
      /* trace("gugus"); */
    }
}

 
/******************************/

int vovel_left(char *syl[MAX_SYL_SIZE], int start, int syllength)
{
  int i;
  int result = 0;

  for (i=start; i<syllength; i++)
    {
      /* trace(syl[i]); */
      if (*syl[i] == 'v') result = !0;
    }
  return result;
}


/**********************************************************************/
/**********************************************************************/
/*********************                            *********************/
/*********************           Main             *********************/
/*********************                            *********************/
/**********************************************************************/
/**********************************************************************/

int main(int argc, char **argv)
{
  /* Trnscript tables
     TTSIZE is #defined at the static memory allocations at top of code
     */
  ttentry inptrans[TTSIZE];
  ttentry outtrans[TTSIZE];

  /* Filter activity flag */
  int active = 0; /* 0=non-Tibetan, 1=Tibetan text */

  /* Filter transparency flag */
  int transparent = 0; /* 0=crunch non-Tibetan, 1=pass non-Tibetan */

  int pending_tsheg = 0;        /* (c) by Jeff Sparkes */
  int pending_shad_space = 0;	/* (c) by Jeff Sparkes */

  /* Char & syllable buffers */
  char linebuf [INPUT_LINEBUFFER_LENGTH + 1];
  char inner_vovel_key_buf [MAX_KEY_VAL_LENGTH + 2];  
  char outer_vovel_key_buf [MAX_KEY_VAL_LENGTH + 2];
  char lig_key[MAX_SYL_SIZE * MAX_KEY_VAL_LENGTH];
  char *charptr  = NULL;
  char *parseptr = NULL;
  char *yig      = NULL;
/*  char *yigbuf   = NULL; */
  
  char *syllable[MAX_SYL_SIZE];
  int  sylindex;
  int  sylend;
  int  parsestep;
  int  i;
  int  geni;
  int  firstline = !0;
  int  skipline  = 0;

  char *active_start  = NULL;
  char *active_end    = NULL;
  char *active_toggle = NULL;

  int  active_start_len  = 0;
  int  active_end_len    = 0;
  int  active_toggle_len = 0;
  
  
  /* Input text file */
  static FILE *inptext;
  /* OUTTEXT is defined in the global section */


/******************************/
/*                            */
/*        Preparation         */
/*                            */
/******************************/


  if (argc != 5)
    {
      /* fprintf(stderr, "You gave %d arguments:\n", argc - 1);
	 fprintf(stderr, "Input  ttd: %s\n", argv[1]);
	 fprintf(stderr, "Output ttd: %s\n", argv[2]); */
      fprintf(stderr, 
	      "USAGE: %s input.ttd output.ttd input.text output.text\n",
	      argv[0]);
      exit(2);
    }


  /* Read transcript tables from files and prepare (sort) them
     for binary search. Input ttd MUST be read last in order to
     maintain the KEY_LEN array
     */
  ttread (argv[2], 0, outtrans);
  ttread (argv[1], 1, inptrans);
  ttprepare(inptrans);
  ttprepare(outtrans);


trace(ttlookup("c___ka", outtrans));

trace("prepare activity flags");

//  active_start      = ttlookup("x___active_in{", outtrans);
//  if (active_start  != NULL) active_start_len  = strlen(active_start);
//  trace(active_start);
//  active_end        = ttlookup("x___active_in}", outtrans);
//  if (active_end    != NULL) active_end_len    = strlen(active_end);
//  trace(active_end);
//  active_toggle     = ttlookup("x___active_in~", outtrans);
//  if (active_toggle != NULL) active_toggle_len = strlen(active_toggle);
//  trace(active_toggle);

  if (ttlookup("x___active_init", inptrans) != NULL)
    {
      active = !0;
    }else{
      active = 0;
    }

/******************************/
/*                            */
/*        Open Files          */
/*                            */
/******************************/


  /* Open input text file */
  if (strncmp(argv[3], "-", 2) != 0)
    {
      if (!( inptext = fopen(argv[3], "r") ))
	{
	  fprintf(stderr, "%s", "Could not open input text file");
	  exit(2);
	}
    }else{
      inptext = stdin;
    }
  
  /* Open output text file (outtext is global)*/
  if (strncmp(argv[4], "-", 2) != 0)
    {
      if (!( OUTTEXT = fopen(argv[4], "w") ))
	{
	  fprintf(stderr, "%s", "Could not open output text file");
	  exit(2);
	}
    }else{
      OUTTEXT = stdout;
    }


/******************************/
/*                            */
/*       Start Output         */
/*                            */
/******************************/

  /* Output preamble */
  yigprint("x___preamble", outtrans);
  
  prepare_flags(inptrans, outtrans, 
		&active, &transparent);  
  

  /* read input text file */
  while (fgets(linebuf, INPUT_LINEBUFFER_LENGTH, inptext) != NULL)
    {
      if (strlen(linebuf) >= (INPUT_LINEBUFFER_LENGTH-1))
	{
	  fprintf(stderr, "Input file contains too long lines. ");
	  fprintf(stderr, "Please keep them shorter than %d ",
		  INPUT_LINEBUFFER_LENGTH);
	  fprintf(stderr, "characters or increase ");
	  fprintf(stderr, "INPUT_LINEBUFFER_LENGTH in line %d of %s",
		  INPUT_LINEBUFFER_LENGTH_LINE, __FILE__);
	  fprintf(stderr, " and compile again.\n");
	  exit(3);
	}

      if (skipline)
	{
	  *linebuf = '\0';
	  skipline = 0;
	}

      /* Filter out magic lines for Linux */
      parseptr = linebuf + 1;
      if (firstline && (*linebuf == '#') && (*parseptr == '!'))
	{
	  *linebuf = '\0';
	  skipline = !0;
	}
      firstline = 0;
 
      parseptr = linebuf;
      
      /* parse until end of line */
      while (*parseptr != '\0' && *parseptr != '\n' && *parseptr != '\13')
	{
	  yig = charparse(parseptr, &parsestep, inptrans);
	  if (yig != NULL)
	    {
	      if (*yig == 'x')  trace(yig);

	      if (strncmp(yig, "x___active{", MAX_KEY_VAL_LENGTH) == 0)
		{
		  parseptr += parsestep;
		  active = !0;
		  if (ttlookup("x___active{", outtrans))
		    {
		      yigprint("x___active{", outtrans);
		    }
		}
	  
	      if (strncmp(yig, "x___active}", MAX_KEY_VAL_LENGTH) == 0)
		{
		  parseptr += parsestep;
		  active = 0;
		  if (ttlookup("x___active}", outtrans))
		    {
		      yigprint("x___active}", outtrans);
		    }
		}

	      if (strncmp(yig, "x___active~", MAX_KEY_VAL_LENGTH) == 0)
		{
		  parseptr += parsestep;
		  trace("active toggle");
		  active = !active;
		  if (active)
		    {
		      if (ttlookup("x___active{", outtrans))
			{
			  yigprint("x___active{", outtrans);
			}
		    }else{
		      if (ttlookup("x___active}", outtrans))
			{
			  yigprint("x___active}", outtrans);
			}
		    }
		}
	    }
	  if (active)
	    {	  
	      /*** read one syllable ***/
	      sylindex = 0;
	  
	      do{
		yig = charparse(parseptr, &parsestep, inptrans);
		if (yig == NULL)
		  {
		    sylend = !0;
		    if (   *parseptr == ' '  || *parseptr == '\x0D' 
			   || *parseptr == '\0' || *parseptr == '\n'
			   || *parseptr == '\t'   )
		      {
		      }else{
			X_ERROR_OCCURRED = !0;
			yigprint("x___error", outtrans);
			/* fprintf(OUTTEXT, "Input not defined"); */
		      }
		    parseptr++;
		  }else{
		    if (*yig != '.' && *yig != 'x')
		      {
			sylend = 0; 
		      }else{
			pending_tsheg = 0;
			sylend = !0;
			if (strncmp(yig, ".___shad", MAX_KEY_VAL_LENGTH) == 0)
			  {
			    pending_shad_space = !0;
			  }
			if (strncmp(yig, ".___tshegshad", 
				    MAX_KEY_VAL_LENGTH) == 0)
			  {
			    pending_shad_space = !0;
			  }
			if (strncmp(yig, "x___transp_line",
				    MAX_KEY_VAL_LENGTH) == 0)
			  {
			    while(!(   *parseptr == '\0'
				    || *parseptr == '\n'))
			      {
				fprintf(OUTTEXT, "%c", *parseptr++);
			      }
			  }
			if (strncmp(yig, "x___transp_word",
				    MAX_KEY_VAL_LENGTH) == 0)
			  {
			    while(!(*parseptr == ' '  
				    || *parseptr == '\x0D' 
				    || *parseptr == '\0'
				    || *parseptr == '\t'
				    || *parseptr == '\n'))
			      {
				fprintf(OUTTEXT, "%c", *parseptr++);
			      }
			  }
			if (strncmp(yig, "x___transp_char",
				    MAX_KEY_VAL_LENGTH) == 0)
			  {
			    fprintf(OUTTEXT, "%c", *parseptr++);
			  }
		      }
		    if (   *yig == 'v' || *yig == 'c' 
			   || *yig == 'p' || *yig == 'b')
		      {
			pending_tsheg = !0;
		      }
		    syllable[sylindex++] = yig;
		    if (parsestep > 0)
		      {
			parseptr += parsestep;
		      }else{
			X_ERROR_OCCURRED = !0;
			yigprint("x___error", outtrans);
			fprintf(OUTTEXT, "sylr 2");
			parseptr++;
		      }
		  }
	      }
	      while (!sylend);
	  
	      /*** trace("syllable read"); ***/
	  
	      /******************************/
	      /*                            */
	      /*     Syllable Analysis      */
	      /*                            */
	      /******************************/

	  
	      /* does syllable contain a prefix ? */
	      if (sylindex >= 3)		
		/* at least 2 chars + 1 (inherent)vovel */
		{
		  if (*syllable[0] == 'p'		
		      /* potential prefix marked as such in ttd */

		      && *syllable[1] != 'v'	
		      /* vovel? -> pot. prefix is main letter */

		      /* is pot. prefix part of a ligature? */
		      && !(strncmp(syllable[0], "p___'a", 
				   MAX_KEY_VAL_LENGTH) != 0  
			   /* 'a is NEVER upper part of a ligature */
			   /* ( I at least hope so ) */

			   && *syllable[1] == 'b'
			   /* ya, ra, la, wa subjoined to pot. prefix */

			   && *syllable[2] == 'v' 
			   /* ligature complete -> no prefix
			      examples: bya, gya ....
			      negative examples: brgyad ... */
		       
			   /* WARNING: gyin, gyas ... give wrong result 
			      (ambiguous transcript).
			      Work around this using the 
			      dummy vovel (usually '-').
			      Examples:  g-yin, g-yas, bu -ddha, ...
			      */                         
			   ) 
		      )
		    {
		      yigprint(syllable[0], outtrans);   /* output prefix */
		      for (i = 0; i < sylindex; i++)
			{
			  /* shift away prefix */
			  syllable[i] = syllable[i + 1]; 
			}
		      sylindex--;
		    }
		} /* min length for prefix */

	      /******************************/
	      /*                            */
	      /*     Ligature Generation    */
	      /*                            */
	      /******************************/

	      i = 0;
	      while (vovel_left(syllable, i, sylindex))
		{
		  if (*syllable[i] == 'v' && 
		      strncmp(syllable[i], "v___dummy", MAX_KEY_VAL_LENGTH) 
		      != 0)
		    {
		      strncpy(lig_key, "c___a", MAX_KEY_VAL_LENGTH);
		    }
		  else if(*syllable[i + 1] == 'v')
		    {
		      strncpy(lig_key, syllable[i++], MAX_KEY_VAL_LENGTH);
		    }
		  else
		    {
		      geni = i;
		      strncpy(lig_key, "l__", MAX_KEY_VAL_LENGTH);
		      while (i < sylindex && *syllable[i] != 'v')  
			/* compose ligature key */
			{
			  charptr = syllable[i]; 
			  charptr += 3; /* cut off type */
			  /* example p___ba + b___ya => l___ba_ya */

			  strncat(lig_key, charptr, MAX_KEY_VAL_LENGTH);
			  i++;
			}
		    }
		  strncpy(inner_vovel_key_buf, syllable[i++], 
			  MAX_KEY_VAL_LENGTH);

		  if (i < sylindex)
		    {
		      if (*syllable[i] == 'v')
			{
			  strncpy( outer_vovel_key_buf, syllable[i++], 
				   MAX_KEY_VAL_LENGTH);
			  strncat( outer_vovel_key_buf, "{", 
				   MAX_KEY_VAL_LENGTH);
			  yigprint(outer_vovel_key_buf, outtrans);
			}else{
			  *outer_vovel_key_buf = '\0';
			}
		    }else{
		      *outer_vovel_key_buf = '\0';
		    }
		  strncat( inner_vovel_key_buf, "{", MAX_KEY_VAL_LENGTH);
		  yigprint(inner_vovel_key_buf, outtrans);

		  if (ttlookup(lig_key, outtrans))
		    {
		      /* Predefined ligature */
		      yigprint(lig_key, outtrans);
		    }else{
		      /* Automatic ligature generation */
		      yigprint("x___outer_box{", outtrans);
		      while (*syllable[geni] != 'v')
			{
			  yigprint("x___inner_box{", outtrans);
		      
		      
			  /* Look for predefined two-letter ligatures 
			     within generic ligature */
			  charptr = NULL;
			  if (*syllable[geni+1] != 'v')  
			    {
			      strncpy(lig_key, "l__", MAX_KEY_VAL_LENGTH);
			      charptr = syllable[geni]; 
			      charptr += 3; 
			      strncat(lig_key, charptr, MAX_KEY_VAL_LENGTH);
			      charptr = syllable[geni+1]; 
			      charptr += 3; 
			      strncat(lig_key, charptr, MAX_KEY_VAL_LENGTH);
			      charptr = ttlookup(lig_key, outtrans);
			    }
		      
			  if (charptr)  
			    {
			      yigprint(lig_key, outtrans);
			      geni += 2;
			    }else{
			      /* Single-letter generic ligature part */
			      yigprint(syllable[geni++], outtrans);
			    }
			  yigprint("x___inner_box}", outtrans);
			}
		      yigprint("x___outer_box}", outtrans); 
		    }
	      
		  inner_vovel_key_buf[strlen(inner_vovel_key_buf) - 1] = '}';
		  yigprint(inner_vovel_key_buf, outtrans);

		  if (*outer_vovel_key_buf != '\0')
		    {
		      outer_vovel_key_buf[strlen(outer_vovel_key_buf) - 1]
			= '}';
		      yigprint(outer_vovel_key_buf, outtrans);
		    }

		} /* while vovel left */
	  
	      while (i < sylindex)		/* output suffix */
		{
		  yigprint(syllable[i], outtrans);
		  i++;
		}
	  
	      if (pending_tsheg)
		{
		  yigprint(".___tsheg", outtrans);
		  pending_tsheg = 0;
		}
	  
	      if (pending_shad_space && (*parseptr == ' ' 
					 || *parseptr == '\t'
					 || *parseptr == '\x0D' 
					 || *parseptr == '\0' 
					 || *parseptr == '\n'))
		{
		  yigprint(".___shad_space", outtrans);
		}
	      pending_shad_space = 0;     /* MUST be after '}' */
	  
	    }else{  /* not active */
//	      if (strncmp(parseptr, "%%", 2) == 0)
//		{
//		  active = !0;
	      fprintf(OUTTEXT, "%c", *parseptr++);
	    }
	  
	} /* while parseptr */
      
      fprintf(OUTTEXT, "\n");
      
    } /* while fgets */
  
  yigprint("x___postamble", outtrans);
  fprintf(OUTTEXT, "\n");

  if (X_ERROR_OCCURRED)
    {
      exit(1);
    }else{
      exit(0);
    }
}