/*\v
 % write table of contents (only in single file mode):
     \ifmfiles\else\pagenumbering{roman}
     \tableofcontents\newpage\pagenumbering{arabic}\fi
     \centerline{\huge\bf File tiny\_t2l.l}
*/

/*\b
  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  <<<<<<<<<<<<<<<<<<<<<<<<<<<<***********************>>>>>>>>>>>>>>>>>>>>>>>>
  <*  filename  :  tiny_t2l.l                                              *>
  <*  purpose   :  this is a little lex file as an example for a simple    *>
  <*            :  converter using the position macros. Only a few         *>
  <*            :  basic conversions are implemented; all fonts etc. are   *>
  <*            :  hard-coded. You may use this file as example for use    *>
  <*            :  of the position macros or as starting point for an own  *>
  <*            :  converter project.                                      *>
  <*            :                                                          *>
  <*  cvt2ltx   :  This file is the tiny version of c2ltx; keywords,       *>
  <*  equiv.    :  strings and comments are recognized. A very simple      *>
  <*            :  version of embedded LaTeX is implemented (only append   *>
  <*            :  mode and verbatim mode; everything is copied verbatim   *>
  <*            :  to the output file in both cases.                       *>
  <*            :                                                          *>
  <*  version   :  1.4.0 from 25-feb-2000                                  *>
  <*  author    :  Michael Plugge <[email protected]>                *>
  <<<<<<<<<<<<<<<<<<<<<<<<<<<<***********************>>>>>>>>>>>>>>>>>>>>>>>>
  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/

%{
  /*\v \section{Declaration Part} */
#define VERSION "1.4.0"
#define VERSION_DATE "25-feb-2000"

#define TAB2SPC 3
#define BASE_FONT "basefont"
#define BLOCK_FONT "blockfont"
#define KEYWORD_FONT "keywordfont"
#define STRING_FONT "stringfont"
#define COMMENT_FONT "commentfont"
#define HEADFONT "headfont"
#define FOOTFONT "footfont"
#define LHEAD ""
#define CHEAD "Produced from %f on %D %t"
#define RHEAD ""
#define LFOOT ""
#define CFOOT "Page %p"
#define RFOOT ""
#define L2E_STYLE " \\documentclass[10pt]{article}\n\
\\usepackage{a4,position,fancyhdr}\n\
\\usepackage[latin1]{inputenc}\n\
\\textwidth18cm\\textheight25cm\\hoffset-3cm\\voffset-1cm"
#define L209_STYLE " \\documentstyle[a4,position,fancyhdr]{article}\n\
\\textwidth18cm\\textheight25cm\\hoffset-3cm\\voffset-1cm"
#define L2E_STYLE_LINE " \\documentclass[10pt]{article}\n\
\\usepackage{a4,position,fancyhdr}\n\
\\usepackage[latin1]{inputenc}\n\
\\textwidth18cm\\textheight25cm\\hoffset-3cm\\voffset-1cm"
#define L209_STYLE_LINE " \\documentstyle[a4,position,fancyhdr]{article}\n\
\\textwidth18cm\\textheight25cm\\hoffset-3cm\\voffset-1cm"

#define LEN(val) if((leng+=val)>70){leng=0; fprintf(yyout,"%%\n  ");}
#if VMS
#undef ECHO
#define ECHO yyleng==1 ? fputc(*yytext,yyout) : fprintf(yyout,"%s",yytext)
#endif

#include <string.h>
#include <time.h>

char *ptr,*ptr1,*kern,*inputname,buffer[256],init=1,cmt_mode;
int pos,old_pos,brace_open,tmp,leng,tab2spc=TAB2SPC,skip_cnt,cmt_pos,line=1,show_lines,use_header=1;
long year;
time_t time_val;
struct tm *atime;

char *lhead=LHEAD,*chead=CHEAD,*rhead=RHEAD,*headfont=HEADFONT,
    *lfoot=LFOOT,*cfoot=CFOOT,*rfoot=RFOOT,*footfont=FOOTFONT,
    *latex_prolog1=
"%%%% This file was generated by tiny_t2l (version %s, %s)\n\n\
\\ifx\\getformat\\undefined\n\
\\newcount\\getformat\\getformat0\n\
\\else\n\
\\mfilestrue\\getformat3\n\
\\fi\n\
\\ifx\\documentclass\\undefined\\advance\\getformat1\\fi\n\n\
\\ifcase\\getformat\n\
%s\n\
\\or\n\
%s\n\
\\else\\fi %% multiple file input: don't load format\n%s",

  *latex_prolog2="\\ifmfiles\\else\\begin{document}\\fi\\begin{flushleft}\n\n",

*month[]={
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
},
*local_month[]={
  "Januar",
  "Februar",
  "M�rz",
  "April",
  "Mai",
  "Juni",
  "Juli",
  "August",
  "September",
  "Oktober",
  "November",
  "Dezember"
},
*month1[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"},
*local_month1[]={"Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"},
*usage_text1="   Usage: tiny_t2l [options] [infile [outfile]] [options]\n\
  infile and/or outfile may be omitted; in this case stdin/stdout are used.\n\
  valid options are:\n\
   -hn        don't generate header or footer text\n\
   -hl<txt>   header text: left side (default \"\")\n\
   -hc<txt>   header text: center (default \"Produced from %f on %D %t\")\n\
   -hr<txt>   header text: right side (default \"\")\n\
   -fl<txt>   footer text: left side (default \"\")\n\
   -fc<txt>   footer text: center (default \"Page %p\")\n\
   -fr<txt>   footer text: right side (default \"\")\n\
     possible escape sequences for the -h. and -f. switches are:\n\
        %f: input file name        %m: month (numeric value)\n\
        %p: page number            %n: (english) name of month (full form)\n\
        %t: time (HH:MM)           %s: (english) name of month (short form)\n\
        %D: date (DD-MMM-YYYY)     %N: (local) name of month (full form)\n\
        %h: hour                   %S: (local) name of month (short form)\n\
        %M: minute                 %y: year\n\
        %d: day of month           %: the `%' character itself\n\
   -o         outputname (if stdin is used for input)\n\
   -t<cnt>    number of spaces per tab character (default: ",
*usage_text2=")\n\
   -d         debug (debug output is written to tiny_t2l.dbg)\n\
   -?         show this help screen\n";

void keyword(void);
void skip_msg(void);
void print_jmpo(int linebegin);
void init_out(int mode);
int die(char *cmd,int mode);
void substitute_format(char *format);
char *subst(int c);
void current_line(void);
%}

SP       [ \t]+
SPO      [ \t]*
WS       [ \t\n]
WSO      [ \t\n]*
WSSEMI   [ \t\n;]
WSBRSEMI [ \t\n(;]
WSBR     [ \t\n(]
WSBR2    [ \t\n)]
WSBC     [ \t\n{]
WSS      [ \t\n*]
WSSB     [ \t\n*)]
WSC      [ \t\n:]
OPER     [ \t\n+\-*/%|&^~!=<>\[(,]
CA       [ \t\n<]
WSB2     [ \t\n\[(]
NEW_DEL  [ \t\n\[(<]

%x LINE_BEGIN OMIT

%option 8bit noyywrap outfile="tiny_t2l.c" debug

%%
     /*\v \section{Rules section}\subsection{\LaTeX Prolog} */
  if(show_lines)
     fprintf(yyout,latex_prolog1,VERSION,VERSION_DATE,L2E_STYLE_LINE,
        L209_STYLE_LINE,use_header?"\\pagestyle{fancy}\n":"");
  else
     fprintf(yyout,latex_prolog1,VERSION,VERSION_DATE,L2E_STYLE,
        L209_STYLE,use_header?"\\pagestyle{fancy}\n":"");
     fprintf(yyout,"\\plcntmargin{777}\n");
  if(use_header){
     fprintf(yyout,"\\lhead{\\%s ",headfont);
     substitute_format(lhead);
     fprintf(yyout,"\\chead{\\%s ",headfont);
     substitute_format(chead);
     fprintf(yyout,"\\rhead{\\%s ",headfont);
     substitute_format(rhead);
     fprintf(yyout,"\\lfoot{\\%s ",footfont);
     substitute_format(lfoot);
     fprintf(yyout,"\\cfoot{\\%s ",footfont);
     substitute_format(cfoot);
     fprintf(yyout,"\\rfoot{\\%s ",footfont);
     substitute_format(rfoot);
  }
  if(!show_lines)
     fprintf(yyout,"\\plinenowidth0pt\n");
  else
     fprintf(yyout,"\\plcntmargin{77}\n");
  fprintf(yyout,latex_prolog2);
  BEGIN(LINE_BEGIN);

     /*\v \subsection{Rules for Line Begin} */
<LINE_BEGIN>{
  /* special cases: blank lines, Blanks at end of line */
^{SPO}\n   {
     fprintf(yyout,"\\init0");
     current_line();
     fprintf(yyout,"\\n\n");
     pos=brace_open=0;
     line++;
  }
{SP}$          /* ignore spaces at end of line */

  /* general line begin (we need the \init macro here) */
^" "    pos++; fprintf(yyout,"\\init1"); current_line(); fprintf(yyout,"\\njo{-1}{"); brace_open=1; leng=16; BEGIN(INITIAL);
^{SP}   print_jmpo(1); BEGIN(INITIAL);
^[^ \t\n]  {
     fprintf(yyout,"\\init0"); current_line(); fprintf(yyout,"\\njo0{");
     yyless(0);
     brace_open=1;
     leng=14;
     cmt_pos=1;
     BEGIN(INITIAL);
  }
.    yyless(0); cmt_pos=pos+1; BEGIN(INITIAL);
}

  /*\v \subsection{Rules for Blanks and Tabs} */
{
" " {
     pos++;
     if(brace_open)fputc('}',yyout);
     fprintf(yyout,"\\njo{%d}{",pos);
     brace_open=1;
     LEN(10);
  }
{SP} print_jmpo(0);
}

\n {
     if(brace_open)fputc('}',yyout);
     line++;
     pos=leng=brace_open=0;
     fprintf(yyout,"\\n\n");
     BEGIN(LINE_BEGIN);
  }

{
{SP}$          /* ignore spaces at end of line */

  /*\v \subsection{Rules for special characters} */
\<{2,9}       init_out(0); fprintf(yyout,"\\mlt{%d}",yyleng); LEN(7);
\>{2,9}       init_out(0); fprintf(yyout,"\\mgt{%d}",yyleng); LEN(7);
\\{2,}        init_out(0); fprintf(yyout,"\\bs{%d}",yyleng); LEN(6);
\*{2,9}       init_out(0); fprintf(yyout,"\\mast{%d}",yyleng); LEN(8);

  /*\v \subsection{``Leader'' rules} */
\<{10,}  |
\>{10,}  |
\+{10,}  |
\${10,}  |
\#{10,}  |
\%{10,}  |
\~{10,}  |
\*{10,}  {
     switch(*yytext){
        case '<':  kern="-2pt";  ptr="$<$";      break;
        case '>':  kern="-2pt";  ptr="$>$";      break;
        case '+':  kern="0pt";   ptr="+";        break;
        case '$':  kern="0pt";   ptr="\\$";      break;
        case '#':  kern="0pt";   ptr="\\#";      break;
        case '%':  kern="0pt";   ptr="\\%";      break;
        case '~':  kern="0pt";   ptr="$\\sim$";  break;
        case '*':  kern="2pt";   ptr="$\\ast$";  break;
        default:   kern="0pt";   ptr="";         break;
     }
     if(brace_open)fputc('}',yyout);
     fprintf(yyout,"\\mpout{%d}{%d}{%s}{%s}",pos,pos+yyleng-1,ptr,kern);
     pos+=yyleng;
     brace_open=0;
     LEN(strlen(kern)+strlen(ptr)+19);
  }
}


{
. {
     init_out(0);
     fprintf(yyout,"%s",subst(*yytext));
  }
\f\n?         fprintf(yyout,"\\newpage\n"); if(*(yytext+yyleng-1)=='\n')line++;
[a-zA-Z0-9]+  init_out(0); fprintf(yyout,"%s",yytext);
}

     /*\v \subsection{Rules for omitting Code} */
<LINE_BEGIN>{
{SPO}"/*"\\o[q+]"*/"{SPO}\n  {
     for(ptr=yytext;*ptr++!='o';);
     if(*ptr=='+')
        skip_cnt=0;
     else
        skip_cnt= -1;
     tmp= -1;
     BEGIN(OMIT);
     line++;
  }
{SPO}"/*"\\o[1-9]+q?"*/"{SPO}\n {
     for(ptr=yytext;*ptr++!='o';);
     tmp=atoi(ptr);
     skip_cnt= -1;
     for(;*ptr && *ptr!='q';ptr++)if(*ptr=='*')skip_cnt=0;
     BEGIN(OMIT);
     line++;
  }
}

<OMIT>{
{SPO}"/*\\o-*/"{SPO}\n {
     skip_msg();
     brace_open=0;
     BEGIN(LINE_BEGIN);
     line++;
  }
\*+
\/+
\\
[^\\\"*\/\n]+     /* skip */
\n {
     if(skip_cnt>=0)skip_cnt++;
     line++;
     if(!--tmp){
        skip_msg();
        brace_open=0;
        BEGIN(LINE_BEGIN);
     }
  }
<<EOF>> skip_msg(); yyterminate();
}

%%

  /*\v \subsection{Function skip\_msg(void)} */
void skip_msg(void)
{
  if(skip_cnt==1)
     fprintf(yyout,"\\par\\centerline{/\\mast{20}{ \\commentfont SKIP A LINE }\\mast{20}/}\\par\n");
  else if(skip_cnt>1)
     fprintf(yyout,"\\par\\centerline{/\\mast{20}{ \\commentfont SKIP %d LINES }\\mast{20}/}\\par\n",skip_cnt);
}

  /*\v \subsection{Function init\_out(void)} */
void init_out(int mode)
{
     /* mode==0: kein \cmtinit
      * mode==1: \cmtinit f�r C-Kommentar
      * mode==2: \cmtinit f�r C++-Kommentar
      */
  pos+=yyleng;
  if(mode==0){
     if(!brace_open){
        fprintf(yyout,"\\njo0{");
        leng+=7;
     }
  }
  brace_open=1;
}

  /*\v \subsection{Function print\_jmpo(int linebegin)} */
void print_jmpo(int linebegin)
{
  int old=pos;
  for(ptr=yytext;*ptr==' ' || *ptr=='\t';ptr++){
     if(*ptr=='\t')
        pos+=tab2spc-pos%tab2spc;
     else
        pos++;
  }
  if(linebegin){
     fprintf(yyout,"\\init{%d}",pos);
     current_line();
     fprintf(yyout,"\\njo{%d}{",-pos);
     leng=18;
  }
  else if(brace_open){
     fputc('}',yyout);
        fprintf(yyout,"\\jmpo{%d}{",pos);
        LEN(10);
  }
  else{
        fprintf(yyout,"\\jmpo{%d}{",pos);
        LEN(10);
  }
  brace_open=1;
}

  /*\v \subsection{Function die(char *cmd,int mode)} */
int die(char *cmd,int mode)
{
  switch(mode){
     case 1:
        fprintf(stderr,"Can't open %s for read; exit\n",cmd);
        exit(4);
     case 2:
        fprintf(stderr,"Can't open %s for write; exit\n",cmd);
        exit(4);
     case 3:
        fprintf(stderr,"%s\n",cmd);
        exit(4);
     default:
        return 0;
  }
}

  /*\v \subsection{Function subst(int c)} */
char *subst(int c)
{
  static char retbuffer[2];

  if(c<0)c+=256;
  switch(c){
     case '#':   leng+=2; return "\\#";
     case '$':   leng+=2; return "\\$";
     case '%':   leng+=2; return "\\%";
     case '&':   leng+=2; return "\\&";
     case '\'':  leng+=3; return "\\sq{}";
     case '*':   leng+=6; return "$\\ast$";
     case '-':   leng+=5; return "{\\mm}";
     case '<':   leng+=3; return "$<$";
     case '>':   leng+=3; return "$>$";
     case '[':   leng+=3; return "{[}";
     case '\\':  leng+=4; return "\\bs{1}";
     case ']':   leng+=3; return "{]}";
     case '^':   leng+=9; return "$\\hat{~}$";
     case '_':   leng+=5; return "{\\ul}";
     case '`':   leng+=3; return "{`}";
     case '{':   leng+=6; return "\\brl{}";
     case '|':   leng+=6; return "$\\mid$";
     case '}':   leng+=6; return "\\brr{}";
     case '~':   leng+=6; return "$\\sim$";
     case '"':   leng+=7; return "{\\tt \"}";
     default:    leng++; *retbuffer=c; return retbuffer;
  }
}

  /*\v \subsection{Function substitute\_format(char *format)} */
void substitute_format(char *format)
{
  char c,*ptr1;

  for(ptr=format;*ptr;ptr++){
     if(*ptr=='%'){          /* escape sequences: */
        switch(*++ptr){
           case 'd':         /* %d: day of month */
              fprintf(yyout,"%d",atime->tm_mday);
              break;
           case 'D':         /* %D: date (format DD-MMM-YYYY) */
              fprintf(yyout,"%d{\\mm}%s{\\mm}%ld",atime->tm_mday,month1[atime->tm_mon],year);
              break;
           case 'f':         /* %f: input file name */
              for(ptr1=inputname;*ptr1;)fprintf(yyout,"%s",subst(*ptr1++));
              break;
           case 'h':
              fprintf(yyout,"%02d",atime->tm_hour);
              break;
           case 'm':         /* %m: month (numeric value) */
              fprintf(yyout,"%d",atime->tm_mon+1);
              break;
           case 'M':         /* %M: minute */
              fprintf(yyout,"%02d",atime->tm_min);
              break;
           case 'n':         /* %n: (english) name of month (full form) */
              fprintf(yyout,"%s",month[atime->tm_mon]);
              break;
           case 'N':         /* %N: (local) name of month (full form) */
              fprintf(yyout,"%s",local_month[atime->tm_mon]);
              break;
           case 's':         /* %s: (english) name of month (short form) */
              fprintf(yyout,"%s",month1[atime->tm_mon]);
              break;
           case 'S':         /* %S: (local) name of month (short form) */
              fprintf(yyout,"%s",local_month1[atime->tm_mon]);
              break;
           case 'p':         /* %p: page (in the LaTeX file) */
              fprintf(yyout,"\\thepage");
              break;
           case 't':         /* %t: time (format HH:MM) */
              fprintf(yyout,"%02d:%02d",atime->tm_hour,atime->tm_min);
              break;
           case 'y':         /* %y: year */
              fprintf(yyout,"%ld",year);
              break;
           case '%':         /* %%: the `%' character itself */
              fputc('\\',yyout);
              fputc('%',yyout);
              break;
           default:          /* unknown escape sequence: just print it out */
              fprintf(stderr,"Unknown escape sequence `%%%c' detected; print it out.\n",*ptr);
              fprintf(stderr,"(format string was >%s<)\n",format);
              fputc('%',yyout);
              fprintf(yyout,"%s",subst(*ptr));
              break;
        }
     }
     else
        fprintf(yyout,"%s",subst(*ptr));
  }
  fprintf(yyout,"}\n");
}

  /*\v \subsection{Function current\_line(void)} */
void current_line(void)
{
  if(show_lines>0 && line%show_lines==0){
     fprintf(yyout,"{%d}",line);
  }
  else
     fprintf(yyout,"{}");
  LEN(10);
}

  /*\v \subsection{Function main(int argc, char **argv)} */
int main(int argc, char **argv)
{
  int i;

#ifdef FLEX_DEBUG
  yy_flex_debug=0;
#endif   /* FLEX_DEBUG */
  time(&time_val);
  atime=localtime(&time_val);
  year=time_val/(365L*24L*60L*60L)+1970L;
  for(i=1;i<argc;i++){
       if(*argv[i]=='-'){
          for(ptr=argv[i]+1;*ptr;)switch(*ptr++){
             case 'd':
#ifdef FLEX_DEBUG
              yy_flex_debug=1;
#else
              fprintf(stderr,"tiny_t2l was compiled without debug info; ignore switch -d\n");
#endif
              break;
           case 'h':
              switch(*ptr++){
                 case 'n': use_header=0; break;   /* no header */
                 case 'l': lhead=ptr; break;      /* left header text */
                 case 'c': chead=ptr; break;      /* center header text */
                 case 'r': rhead=ptr; break;      /* right header text */
                 default: break;
              }
              while(*ptr)ptr++;   /* forget the rest of the argument */
           break;
           case 'l':
              if(*ptr)
                 show_lines=atoi(ptr);
              else
                 show_lines=5;
              while(*ptr)ptr++;   /* forget the rest of the argument */
              break;
           case 'f':
              switch(*ptr++){
                 case 'l': lfoot=ptr; break;      /* left footer text */
                 case 'c': cfoot=ptr; break;      /* center footer text */
                 case 'r': rfoot=ptr; break;      /* right footer text */
                 default: break;
              }
              while(*ptr)ptr++;   /* forget the rest of the argument */
           break;
           case 'o': /* output name */
              if(!yyout)(yyout=fopen(ptr,"w")) || die(ptr,2);
              break;
           case 't':
              tab2spc=atoi(ptr);
              break;
           case '?':
              fprintf(stderr,"tiny_t2l Version %s (%s)\n%s%d%s",
                 VERSION,VERSION_DATE,usage_text1,TAB2SPC,usage_text2);
#if VMS
              exit(1);
#else
              exit(0);
#endif
           default:
              break;
        }
     }
     else if(!yyin)   /* argument without leading '-': input or output name */
        (yyin=fopen(inputname=argv[i],"r")) || die(inputname,1);
     else if(!yyout)
        (yyout=fopen(argv[i],"w")) || die(argv[i],2);
  }
  if(!yyin)yyin=stdin;       /* no inputname specified */
  if(!yyout)yyout=stdout;    /* no outputname specified */
  if(inputname){
     for(ptr=inputname,ptr1=buffer;*ptr;)
        switch(*ptr){
           case '_':
           case '$': *ptr1++='\\';
           default:
              *ptr1++= *ptr++;
              break;
        }
     *ptr1=0;
  }
  else
     strcpy(buffer,inputname="(stdin)");
#ifdef FLEX_DEBUG
  if(yy_flex_debug){
        /* FLEX gives very much debug info; write the stuff to a file */
     fprintf(stderr,"redirect stderr to file tiny_t2l.dbg\n");
     (freopen("tiny_t2l.dbg","w",stderr))
        || die("error opening file tiny_t2l.dbg for stderr (freopen)",3);
  }
#endif   /* FLEX_DEBUG */
  yylex();

     /* write the end of the LaTeX file */
  if(brace_open)fputc('}',yyout);
  fprintf(yyout,"\\end{flushleft}\n\
\\ifmfiles\\def\\END{\\relax}\\else\\def\\END{\\end{document}}\\fi\n\
\\END\n");
  fclose(yyin);
  fclose(yyout);
}