/******************************************************************************
 * program:     wp2latex                                                      *
 * function:    module for conversion Text602 files into LaTeX 		      *
 * modul:       pass1602.cc                                                   *
 * description: This module contains parser for T602 documents. It could be   *
 *		optionally not compiled with WP2LaTeX package.		      *
 * licency:     GPL		                                              *
 ******************************************************************************/

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#include<stringa.h>
#include<lists.h>
#include<dbllist.h>

#include"wp2latex.h"
#include "cp_lib/cptran.h"


#define T602Version "0.03"


class TconvertedPass1_602: public TconvertedPass1
     {
public:
     string cmd,args;

     int color;
     int beg_par;  /* is begining of paragraph ? */
     int is_link;  /* is this a link ? */
     int wendl;    /* is this end of line only ? */
     int nsp;      /* nmuber of spaces */

     virtual int Convert_first_pass(void);
     };

static void ProcessKey602(TconvertedPass1_602 *cq);

/*Register translators here*/
TconvertedPass1 *Factory_602(void) {return new TconvertedPass1_602;}
FFormatTranslator Format602("T602",Factory_602);


/* Definition of special characters */
#define CR '\xd'
#define ENDL 141

#define NNSP 10

/* Known text styles */
#define BLD 2
#define ITL 4
#define UND 19
#define ENL 15
#define HIG 16
#define BIG 29
#define SUB 22
#define SUP 20

#define COLOR_SIZE 6


static void ProcessKey602(TconvertedPass1_602 *cq);

static void ChangeEncoding(TconvertedPass1_602 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#ChangeEncoding() ");fflush(cq->log);
#endif
long value;
string translator;

  cq->args.trim();
  value=atol(cq->args());
  switch(value)
     {
     case 0:translator="kam";break;	//"895"
     case 1:translator="cp852";break;	//latin2
     case 2:translator="koi8cs";break;	//koi8cs
     default:cq->ConvertCpg = NULL;
     }
if(translator!="")
     {
     translator+="TOinternal";
     cq->ConvertCpg = GetTranslator(translator);
     }
}


static void HeaderFooter602(TconvertedPass1_602 *cq, const string &args, char He_Fo=0)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#HeaderFooter602() ");fflush(cq->log);
#endif
  attribute OldAttr;
  string s;
  unsigned char OldFlag,OldEnvir;
  int i;
  const char *Header_Text = args();
  
  if(Header_Text==NULL) return;

  OldFlag = cq->flag;
  OldEnvir= cq->envir;

  cq->recursion++;

  cq->line_term = 's';		//Soft return
  if(cq->char_on_line == -20)   /* Left one empty line for new enviroment */
      {
      fputc('%', cq->table);
      fputc('%', cq->strip);
      NewLine(cq);
      }
  if(cq->char_on_line==true)
      {
      NewLine(cq);
      }

  Close_All_Attr(cq->attr,cq->strip);
  OldAttr=cq->attr;		/* Backup all attributes */

				/* Any of section's attr cannot be opened */
  for(i=First_com_section;i<=Last_com_section;i++)
		  _AttrOff(cq->attr,i,s); // !!!!!! toto predelat!

  InitHeaderFooter(cq,He_Fo,1);

  cq->envir='!';		//Ignore enviroments after header/footer
  NewLine(cq);

  cq->attr.InitAttr();		//Turn all attributes in the header/footer off

  cq->flag = HeaderText;
  cq->envir = ' ';
  cq->ActualPos = ftell(cq->wpd);
  cq->char_on_line = -10;
  while(*Header_Text!=0)
	{
	cq->by=*Header_Text++;

	if(cq->by=='#') PageNumber(cq);
		   else ProcessKey602(cq);
	}

  Close_All_Attr(cq->attr,cq->strip);
  if(cq->char_on_line==true)
     {
     cq->line_term = 's';    	//Soft return
     NewLine(cq);
     }
  putc('}', cq->strip);

  cq->line_term = 's';    	//Soft return
  cq->envir='^';		//Ignore enviroments after header/footer
  NewLine(cq);

  cq->attr=OldAttr;			/* Restore backuped attributes */
  cq->flag = OldFlag;
  cq->envir = OldEnvir;
  cq->char_on_line = -10;		// stronger false;
  cq->recursion--;

  strcpy(cq->ObjType,(He_Fo & 3)<=1?"Header":"Footer");
}


static void Image602(TconvertedPass1_602 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Image602() ");fflush(cq->log);
#endif
TBox Box;
char *str,ch;
char CommaCount;

  CommaCount=0;
  str = cq->args();
  if(str==NULL) return;
  initBox(Box);

  while((ch=*str)!=0)
     {
     switch(CommaCount)
	{
	case 0:if(isspace(ch) || ch==',') *str=0;
	       break;
	case 4:if(isdigit(ch))		//4'th argument is rotation angle
		  {
		  Box.RotAngle=atoi(str);
		  goto skip;
		  }
	       break;
	case 5:goto skip;
	}
     if(ch==',') CommaCount++;
     str++;
     }
skip:
  Box.Image_type=0;	//Image on disk
  Box.Contents = 3;
  Box.HorizontalPos=3;	//Full

  ImageWP(cq,cq->args,Box);
  *str=ch;
}


static void ProcessKey602(TconvertedPass1_602 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#ProcessKey602() ");fflush(cq->log);
#endif
string TAG;
const char *tag;
BYTE by,subby;

 *cq->ObjType=0;
 if(cq->by==0) cq->by=fgetc(cq->wpd);
 by=cq->by;
 subby=cq->subby;

 switch (by)
    {
    case '@':if (cq->char_on_line<=0)
		    {
		    cq->cmd="";
		    while(!feof(cq->wpd))
		       {
		       subby=fgetc(cq->wpd);
		       if(isspace(subby)) break;
		       cq->cmd+=subby;
		       }
		    fGets2(cq->wpd, cq->args);
		    cq->char_on_line=0;
		    if(cq->cmd=="CT") ChangeEncoding(cq);
		    if(cq->cmd=="FO") HeaderFooter602(cq,cq->args,2);
		    if(cq->cmd=="HE") HeaderFooter602(cq,cq->args,1);
		    if(cq->cmd=="PA") HardPage(cq);
		    break;
		    }
	      goto DEFAULT;
     case '{':if (!cq->is_link)
		  {
		  char tmp;
		  tmp=fgetc(cq->wpd);
		  if (tmp=='#')
		      {
		      //scanf("%s", cmd);
		      printf("<A NAME=\"POS%s\">", cq->cmd());
		      cq->is_link=1;
		      }
		  else if (tmp=='!')
		      {
		      //scanf("%s", cq->cmd());
		      printf("<A HREF=\"#POS%s\">", cq->cmd());
		      cq->is_link=1;
		      }
		  else
		      {
		      ungetc(tmp, cq->wpd);
		      goto DEFAULT;
		      }
		  }
		  break;
      case '}' :if (cq->is_link)
		    {
		    cq->is_link=0;
		    printf("</A>");
		    }
		  else goto DEFAULT;
		  break;
      case CR   : break;
      case ENDL : SoftReturn(cq);
		  cq->wendl=1;
		  break;
      case BLD  : if (IsAttrOn(cq->attr,12)<0) Attr_ON(cq,12);
					  else Attr_OFF(cq,12);
		  break;
      case ITL  : if (IsAttrOn(cq->attr,8)<0) Attr_ON(cq,8);
					 else Attr_OFF(cq,8);
		  break;
      case UND  : if (IsAttrOn(cq->attr,14)<0) Attr_ON(cq,14);
					  else Attr_OFF(cq,14);
		  break;
      case ENL  : if (IsAttrOn(cq->attr,2)<0) Attr_ON(cq,2);
					 else Attr_OFF(cq,2);
		  break; 		//<FONT SIZE=+1>
      case HIG  : if (IsAttrOn(cq->attr,1)<0) Attr_ON(cq,1);
					 else Attr_OFF(cq,1);
		  break; 		//<FONT SIZE=+3>
      case BIG  : if (IsAttrOn(cq->attr,0)<0) Attr_ON(cq,0);
					 else Attr_OFF(cq,0);
		  break; 		//<FONT SIZE=+4>
      case SUB  : if (IsAttrOn(cq->attr,6)<0) Attr_ON(cq,6);
					 else Attr_OFF(cq,6);
		  break;
      case SUP  : if (IsAttrOn(cq->attr,5)<0) Attr_ON(cq,5);
					 else Attr_OFF(cq,5);
		  break;
      case '\n' : cq->beg_par=1;
		  if(!cq->wendl) HardReturn(cq);
		  cq->wendl=0;
		  break;
      case ' '  : if (cq->char_on_line<=0) cq->nsp++;
				      else fputc(' ',cq->strip);
		  break;
      case '.'  : if (cq->char_on_line<=0)
		    {
		    cq->cmd="";
		    while(!feof(cq->wpd))
		       {
		       subby=fgetc(cq->wpd);
		       if(isspace(subby)) break;
		       cq->cmd+=subby;
		       }
		    fGets2(cq->wpd, cq->args);
		    if(cq->cmd=="PI") Image602(cq);
		    else {
			 fprintf(cq->strip,"%% .%s %s",cq->cmd(),cq->args());
			 }
		    cq->char_on_line=0;
		    break;
		    }
		  goto DEFAULT;
      default   :
DEFAULT:          if(cq->beg_par)
		    {
		    if (cq->nsp > NNSP)
			{if(toupper(cq->envir)!='C') Justification(cq,0x82);} //center
		    else if(cq->char_on_line<=0 && toupper(cq->envir)=='C')
			Justification(cq,0x81);	//full
		    }

		  if (cq->nsp>0) fputc(' ',cq->strip);
		  if ((unsigned)by > ' ')
		       {		//Normal character
		       tag = Ext_chr_str(by,cq,cq->ConvertCpg);
		       CharacterStr(cq,tag);
		       }
		  cq->char_on_line=1;
		  cq->beg_par=cq->nsp=cq->wendl=0;
		  break;
    }

 cq->ActualPos = ftell(cq->wpd);
}


int TconvertedPass1_602::Convert_first_pass(void)
{
#ifdef DEBUG
  fprintf(log,"\n#Convert_pass1_602() ");fflush(log);
#endif
DWORD fsize;

  if(Verbosing >= 1)
     printf(_("\n>>>T602toLaTeX<<< Conversion program: From T602 to LaTeX Version %s\n"
	      "      Made by J.Fojtik  (Hosted on WP2LaTeX :))))\n\n"),
	    T602Version);

  DocumentStart=ftell(wpd);

  fsize=filesize(wpd);
  perc.Init(ftell(wpd), fsize,_("First pass T602:") );

  color=1;
  beg_par=1;
  is_link=0;
  wendl=0;
  nsp=0;

  ActualPos = ftell(wpd);
  while (ActualPos < fsize)
      {
      if(Verbosing >= 1)		//actualise a procentage counter
	      perc.Actualise(ActualPos);

      by = 0;
      ProcessKey602(this);
      }

  Finalise_Conversion(this);
  return(1);
}


/*------------------------------------------------------------------------*/
