/******************************************************************************
 * program:     wp2latex                                                      *
 * function:    module for conversion DocBook files into LaTeX		      *
 * modul:       pass1dcb.cc                                                   *
 * description: This module contains parser for DocBook documents. It could   *
 *		be optionally 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"pass1xml.h"
#include "cp_lib/cptran.h"


extern list HTMLChars;


/*Register translators here*/
class TconvertedPass1_Docbook: public TconvertedPass1_XML
     {
public:
     virtual int Convert_first_pass(void);
     };
TconvertedPass1 *Factory_Docbook(void) {return new TconvertedPass1_Docbook;}
FFormatTranslator FormatDocbook("docbook",Factory_Docbook);

#define DocbookVersion "0.2"


static void ProcessKeyDocbook(TconvertedPass1_XML *cq);


static void ItemizeDocbook(TconvertedPass1_XML *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#ItemizeDocbook() ");fflush(cq->log);
#endif
unsigned char OldFlag;
char OldEnvir;
long FilePos;

  FilePos = ftell(cq->wpd);
  OldFlag = cq->flag;
  OldEnvir = cq->envir;
  cq->flag = Nothing;
  cq->recursion++;

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

  cq->envir = ' ';

  if(OldEnvir=='B') fprintf(cq->strip, "\\vbox{"); //protect itemize inside table
  fprintf(cq->strip, "\\begin{itemize}");

  cq->char_on_line = false;
  cq->nomore_valid_tabs = false;
  cq->rownum++;
  Make_tableentry_attr(cq);
  cq->latex_tabpos = 0;

	/*Process all content of the table */
  cq->flag=OldFlag;
  fseek(cq->wpd,FilePos,SEEK_SET);
  cq->ReadXMLTag(false);
  while(!feof(cq->wpd))
	{
/*	if(cq->by==0 && (cq->subby==10 || cq->subby==13))
		{
		cq->subby=' ';	// remove \n from cell text
		} */
	ProcessKeyDocbook(cq);
	if(cq->by==144)
		{
		if(cq->subby==1) break; /*End of itemize*/
		if(cq->subby==2) fprintf(cq->strip, "\\item ");
		}

	cq->ReadXMLTag(false);
	}

  fprintf(cq->strip, "\\end{itemize}");
  if(OldEnvir=='B') fprintf(cq->strip, "}");
  if(cq->char_on_line <= -10)    /* Left one enpty line for ending enviroment */
	{
	fputc('%', cq->table);fputc('%', cq->strip);
	NewLine(cq);
	}
  cq->envir='^';		//Ignore enviroments after table
  fputc('%', cq->table);
  NewLine(cq);
  cq->char_on_line = -10;		// stronger false;

  cq->recursion--;

  cq->flag=OldFlag;
  cq->envir=OldEnvir;
cq->TAG="ITEMIZE";
strcpy(cq->ObjType, "Itemize Start");
}


/*This function extracts some information from meta ?xml tag*/
static void MetaXML(TconvertedPass1_XML *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#MetaXML() ");fflush(cq->log);
#endif
int i;
char *charset;
  //strcpy(cq->ObjType, "?xml");

  if((i=cq->TAG_Args IN "encoding")>=0)
	{
	charset=cq->TAG_Args.Member(i,1);
	if(charset==NULL) return;

	cq->SelectTranslator(charset);
	}
}


static void ChapterDocbook(TconvertedPass1_XML *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#TableHTML() ");fflush(cq->log);
#endif
unsigned char OldFlag;
char OldEnvir;

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

//fprintf(cq->log,"!!!<chapter>");

do {
   cq->TAG = "";
   ProcessKeyDocbook(cq);

   //fprintf(cq->log,cq->TAG);

   if(cq->by==135)
	{
	if(cq->subby==1) break; //</chapter>
	}

   if(cq->by==150)
     {
     if(cq->subby == 0)	StartSection(cq,-1);  // <title>
     if(cq->subby == 1) EndSection(cq,-1);    // </title>
     }
   } while(!feof(cq->wpd));

  cq->recursion--;

  cq->flag=OldFlag;
  cq->envir=OldEnvir;
cq->TAG="CHAPTER";
strcpy(cq->ObjType, "chapter");
}


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

 *cq->ObjType=0;
 if(cq->TAG=="") cq->ReadXMLTag(false);
 by=cq->by;
 subby=cq->subby;

 switch(by)
	{
	case XML_char:
               switch(cq->subby)                        //Normal character
		  {
		  case 10:
		  case 13:by=128;break; //CR
		  case  9:strcpy(cq->ObjType, "!Tab");
		  case 32:by=32;break;  //Space
		  }
	       break;
/*	case 1:if(cq->TAG=="") break;			//Extended chatacter &xxx;
	       TAG=Ext_chr_str(cq->TAG[0],cq)+copy(cq->TAG,1,length(cq->TAG)-1);
	       tag=TAG();
	       by=201;
	       break;*/
	case XML_extchar:
	case XML_badextchar:
               TAG = copy(cq->TAG,1,length(cq->TAG)-2);   //Extended chatacter &xxx;
	       if( (tag=TAG())==NULL) break;
	       if(TAG=="nbsp")	{by=200;break;}  	//Hard space

	       if((i=(TAG() IN HTMLChars))>0)
		  {
		  i--;
		  by=201;
		  tag = Ext_chr_str(i, cq, cq->ConvertHTML); /*Translate HTML character set to WP5.x one*/
		  }
	       break;

	case XML_tag:
               TAG = copy(cq->TAG,1,length(cq->TAG)-2);	//Normal tag <xxx>
	       if( (tag=TAG())==NULL) break;

	       if(TAG=="?xml")    {MetaXML(cq);break;}
	       if(TAG=="para")    {by=132;break;} 	//new paragraph
	       if(TAG=="chapter") {by=135;subby=0;break;} //section level 1
	       if(TAG=="title")   {by=150;subby=0;break;}
	       if(TAG=="orderedlist"){by=144;subby=0;break;} //Start of itemize
	       if(TAG=="listitem"){by=144;subby=2;break;} //Begin of item

	       break;
	case XML_closetag:
               TAG = copy(cq->TAG,2,length(cq->TAG)-3);	//Closing tag </xxx>
	       if((tag=TAG())==NULL) break;

	       if(TAG=="para")    {by=133;break;} 	//end paragraph
	       if(TAG=="chapter") {by=135;subby=1;break;} //section off level 1
	       if(TAG=="title")	  {by=150;subby=1;break;}
	       if(TAG=="orderedlist"){by=144;subby=1;break;} //End of itemize
	       if(TAG=="listitem"){by=144;subby=3;break;} //End of item

	       break;
	case XML_comment: 			//comment
        case XML_CDATA:
	       break;
	}

  cq->by = by;
  cq->subby = subby;
  if(cq->flag<Nothing)
    switch(by)
	{
	case XML_char:		//Normal character
               tag=Ext_chr_str(subby,cq,cq->ConvertCpg);
	       CharacterStr(cq,tag);
	       break;		//Normal character
        case XML_CDATA:
	case XML_comment:
               cq->CommentXML();
	       break;
	case XML_unicode:
               CharacterStr(cq,cq->TAG);
	       break;		//Already expanded unicode character

	case 32:putc(' ', cq->strip);   /*soft space*/
		break;

	case 128:if(cq->TablePos!=1 && cq->TablePos!=3)
		   if(cq->char_on_line)
			SoftReturn(cq);
		 break;
	case 129:AttrOn(cq->attr,subby);break;
	case 130:AttrOff(cq,subby);     break;
	case 131:HardReturn(cq);        break;
	case 132:if(cq->char_on_line) HardReturn(cq);  //Paragraph on
		 SoftReturn(cq);
		 break;
	case 133:if(cq->char_on_line) HardReturn(cq);  //Paragraph off
		 break;

	case 135:if(subby==0) ChapterDocbook(cq);
		 break;

        case 144:switch(subby)
		   {
		   case 0:ItemizeDocbook(cq);break;
		   }
		 break;

	case 200:fputc('~', cq->strip);strcpy(cq->ObjType, " ");
		 break;
	case 201:CharacterStr(cq,tag);break; //
	}


 cq->by = by;
 cq->subby = subby;
 if (cq->log != NULL)
    {   /**/
    if(by==128) fputc('\n',cq->log);
    else if(by==' ' || by==200) fputc(' ',cq->log);
    else if(by==0 || by==201)
	{
	fprintf(cq->log,"%s",tag);
	}
    else
	{
	fprintf(cq->log, _("\n%*s [%s %s]   "),
		  cq->recursion * 2, "", cq->TAG(), cq->ObjType);
//	if(*cq->ObjType==0) UnknownObjects++;
	}
    }

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


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

  if(Verbosing >= 1)
     printf(_("\n>>>Docbook2LaTeX<<< Conversion program: From Docbook to LaTeX Version %s\n"
	      "      Made by J.Fojtik  (Hosted on WP2LaTeX :))))\n\n"),
			DocbookVersion);
  ConvertHTML = GetTranslator("htmlTOinternal");
  CharReader = &ch_fgetc;

  TablePos=0;

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

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

      TAG = "";
      ProcessKeyDocbook(this);
      }

  Finalise_Conversion(this);
  return(1);
}

