/******************************************************************************
 * program:     wp2latex                                                      *
 * function:    Convert WordPerfect files into LaTeX			      *
 * modul:       wp2latex.h                                                    *
 * description: Contains global definitions and prototypes                    *
 ******************************************************************************/
#ifndef __Wp2Latex__
#define __Wp2Latex__


#ifndef __TYPES_INCLUDED
 #include "typedfs.h"		/*File defines BYTE, WORD, DWORD types*/
#endif
#ifndef __Common_H_INCLUDED
 #include "common.h"		/*File defines compiler dependent features*/
#endif

#define LineLength   80		/* Split lines after more than LineLength charcters */

#define VersionWP2L	"3.97"
#define VersionDate	"16 Jun 2021"  /* day (space) month (space) full year */

#ifndef false
 #define  false          0
#endif
#ifndef true
 #define  true           1
#endif

/* Constants for a flag InputPS */
#define IMG_InputPS	0
#define IMG_graphicx	2
#define IMG_epsfig	4
#define IMG_graphics	8

extern unsigned short OutCodePage, WPcharset;
extern bool Index, Interactive, NFSS, TABs, twoside, ExactFnNumbers, CPStyles,
	 EraseStrip, UndoRedo, Noclobber;
extern SBYTE Cyrillic, colors, EndNotes, FancyHdr, Columns, cjHebrew, InputPS, MakeIdx,
	 textcomp, Wasy, Accents, Amssymb, Arevmath, LaTeXsym, LongTable, Bbm, TIPA, fontenc,
	 Rsfs, Ulem, pifont, PostScript, rus_yo, Rotate, Scalerel, LineNo, AmsMath,
         SaveWPG;
extern int LaTeX_Version;
extern signed char Verbosing;
extern bool TexChars,ExtendedCheck,OptimizeSection,FixSpaces;
#ifdef _REENTRANT
extern short JobCount;
#endif

typedef struct			/* Auto detection structure for file formats */
	{
	const char *DocumentType;
	const char *Converter;	///< ASCII key for looking converter module.
        const char *Extension;
	WORD DocVersion;
	float Probability;	///< <-1 surely not  0 don't know  1 surely yes>
        DWORD DocumentStart;
	} FFormatDetect;
extern FFormatDetect FilForD;

extern long num_of_lines_stripfile;

	/*Symbolical names of some attributes*/
#define First_com_section 17
#define Last_com_section  24
#define Hidden_Text	  26
#define Cyr_Font	  27
#define Heb_Font	  28
#define Line_Num	  29
extern int OutputStyle;


typedef struct
{
  const char *Open;
  const char *Close;
  const char *MathOpen;
  const char *MathClose;
} TStyleOpCl;
extern const TStyleOpCl StyleOpCl2[];
extern const TStyleOpCl StyleOpCl3[];
extern const TStyleOpCl *StyleOpCl;


/* functions of wp2lfuti.c */
int AbsolutePath(const char *TestedPath);
FILE *OpenWrChk(const char *name, const char *type, FILE *Err);
int  ReadAndSplitLine(FILE *fp, char *regel);
long filesize(FILE *f);
#define Rd_word(f,w) RdWORD_LoEnd(w,f);
#define Rd_dword(f,d) RdDWORD_LoEnd(d,f);
#define Wr_word(f,w) WrWORD_LoEnd(w,f);
#define Wr_dword(f,d) WrDWORD_LoEnd(d,f);

int GetPathEnd(const char *FullName);
const char *GetExtension(const char *FullName);
const char *GetFullFileName(const char *PathName);
int CopyFile(const char *Dest, const char *Src);
int CopyFile(const char *Dest, FILE *in, long size);
int CopyFile(FILE *out, FILE *in, long size);

DWORD ch_fgetc(FILE *F);
DWORD w_fgetc(FILE *F);
DWORD W_fgetc(FILE *F);


void LoadConfigFile(const char *filename);
int CheckFileFormat(FILE *wpd,FFormatDetect & FilForD);

/* Variables for Convert_first_pass: */
#define NormalText      0
#define HeaderText      1
#define CharsOnly       2
#define Nothing         3


#define MaxAttributes 17	/*the capacity of attribute stack*/
class attribute
{
public:
	unsigned Math_Depth;
        unsigned Opened_Depth;		///< This is a number of currently opened attributes.
        unsigned Closed_Depth;		///< This denotes a number of attributes.
	char stack[MaxAttributes+1];

        attribute()	{InitAttr();}
        attribute(const attribute&src)	{Math_Depth=src.Math_Depth; Opened_Depth=src.Opened_Depth; Closed_Depth=src.Closed_Depth;}
        void InitAttr(void);
        int ClosedAttr(void) const {return(Closed_Depth>Opened_Depth);}

        static unsigned getStackLimit(void) {return MaxAttributes+1;}
};


void AttrOn(attribute & a, char Attr);
void Close_All_Attr(attribute & a, FILE *f, unsigned StartAttr=0);
int IsAttrOn(const attribute & a, char Attr);
void Open_All_Attr(attribute & a, FILE * f);
#ifdef __Stringa_h
void AttrFit(attribute & Base, const attribute & A_New, string & s);
void _AttrOff(attribute & a, char Attr, string & s);
void Close_All_Attr(attribute & a, string & s, unsigned StartAttr=0);
void Open_All_Attr(attribute & a, string & s);
#endif



typedef enum
{
  BOX_ANCHOR_PAR = 0,
  BOX_ANCHOR_PAGE = 1,
  BOX_ANCHOR_CHAR = 2
} TBoxAnchor;

typedef struct
	{
	BYTE  AnchorType;	//< 0-Paragraph, 1-Page, 2-Character
	BYTE  HorizontalPos;    //< 0-Left, 1-Right, 2-Center, 3-Full
	BYTE  Contents;		//< 1-text, 2-disk image, 3-buildin image, 4-equation
	BYTE  Type;
	float Width;		//< Expected width of image in [mm] ?? or [cm]??, or <=0 when unknown.
	float VScale;
	float HScale;
	WORD RotAngle;		//< Rotation in degrees
	WORD  CaptionSize;
	DWORD CaptionPos;
	SBYTE Image_type;	//< 0-external, 1-buildin WPG1, 2-buildin WPG2
	DWORD Image_offset;     //< Ofset of embedded image blob in a host file.
	DWORD Image_size;	//< Size of embedded image blob.
	} TBox;


class Percentor
	{
protected:
	long Range;
	int Shift;		///< Speedup precalculated values.
public: long StartValue;	///< Percentor starts from this.
	long EndValue;		///< Percentor shows 100% when reaches this value.
	int CurrentPercent;
	bool displayed;
        char Recursion;

	Percentor(void);
	~Percentor(void);

	void Actualise(long NewValue);
	void Hide(void);
	void Init(long Start, long End, const char *text=NULL);
	void SetPercent(int NewPercent);
	void Show(void);
	};


#define TAB_POS_SIZE 40

class CpTranslator;

extern CpTranslator *UserWPCharSet;

class TconvertedPass1
  {
public:
  virtual ~TconvertedPass1()	{}

  Percentor perc;
  DWORD DocumentStart;
  attribute attr;

  char indenting;
  char Columns;
  bool CentrePage;

  signed char char_on_line;
  bool nomore_valid_tabs, indent_end, ind_text1;
  bool Linebegin;

  char envir, line_term;

  int num_of_tabs, latex_tabpos;
  WORD tabpos[TAB_POS_SIZE];
  char tab_type;

  int WP_sidemargin,Lmar,Rmar;

  WORD ind_leftmargin, ind_rightmargin;

  unsigned char by, subby;
  DWORD ActualPos;

  unsigned rownum;

  unsigned char Font;		///< Current font.
  unsigned char RequiredFont;	///< Font to be newly switched.
  unsigned char flag;
  short int FirstSection;
  signed char recursion;
  char ObjType[48];

  FILE *wpd, *table, *strip, *log, *err;
  CpTranslator *ConvertCpg;

  virtual int Convert_first_pass(void)=0;
  virtual int Dispatch(int Func, const void *arg=NULL) {return(-1);}
  void InitMe(FILE *FileIn, FILE *Table, FILE *StripOut, FILE *LogFile,FILE *ErrorFile);
};

void ReportNoMemory(TconvertedPass1 *cq=NULL);


extern CpTranslator *Convert2Target;

typedef enum
{
  DISP_WRAPPER = 0,
  DISP_PROCESSKEY,
  DISP_EXTRACTIMAGE,
  DISP_NOCONVERTIMAGE,
  DISP_EXTRACT_LABEL,
  DISP_DO_CAPTION
} WP2LaTeXDispatch;

typedef enum
{
  FONT_NEUTRAL = 0,
  FONT_NORMAL = 1,
  FONT_CYRILLIC = 2,
  FONT_HEBREW = 3
} FontTypes;


#ifndef RGBQuad_DEFINED
#define RGBQuad_DEFINED
struct RGBQuad
	{
	unsigned R,G,B,O;
	};
#endif

/* Variables for Convert_second_pass: */
/*  .... only in pass2.cc ...  */

/* global functions of charactr.cc */
#define ISO8859_1	1
#define ISO8859_2	2
#define KOI8R		8
#define UTF8		16384

const char *Ext_chr_str(WORD char_code, TconvertedPass1 *cq, CpTranslator *ConvertCP=NULL);

typedef enum {aExtraLarge=0, aVeryLarge1=1, aLarge=2, aSmall=3, aFine=4,
	      aSupscript=5, aSubscript=6, aOutline=7, aItalic=8, aShadow=9,
	      aRedline=10, aDblUnderline=11, aBold=12, aStrikeOut=13,
	      aUnderline=14, aSmallCaps=15 } TxtAttrs;

/* global functions of pass1.cc */
void Finalise_Conversion(TconvertedPass1 *cq);
void Make_tableentry_envir_extra_end(TconvertedPass1 *cq);
void Make_tableentry_attr(TconvertedPass1 *cq);
void Make_tableentry_tabset(TconvertedPass1 *cq);
void Initialise_Conversion(TconvertedPass1 *cq);
void AttrOff(TconvertedPass1 *cq, char attr_num);
void Attr_ON(TconvertedPass1 *cq,unsigned char b=0xFF);
void Attr_OFF(TconvertedPass1 *cq,unsigned char b=0xFF);
void CancelHyph(TconvertedPass1 *cq);
void CellTable(TconvertedPass1 *cq);
void Center(TconvertedPass1 *cq);
void CenterPage(TconvertedPass1 *cq);
void CharacterStr(TconvertedPass1 *cq,const char *LatexCode);
void Color(TconvertedPass1 *cq, signed char WP, RGBQuad *RGB=NULL);
void Column(TconvertedPass1 *cq,signed char number);
void DateCode(TconvertedPass1 *cq);
void End_of_indent(TconvertedPass1 *cq);
void EndTable(TconvertedPass1 *cq);
void Flush_right(TconvertedPass1 *cq, char type);
void HardHyphen(TconvertedPass1 *cq);
void HardPage(TconvertedPass1 *cq);
void HardReturn(TconvertedPass1 *cq);
void HLine(TconvertedPass1 *cq, signed char WP);
void Hyphenation(TconvertedPass1 *cq,char state);
void Indent(TconvertedPass1 *cq, char WP);
void initBox(TBox &Box);
void InitHeaderFooter(TconvertedPass1 *cq, char HorF, char occurance);
void InvisibleSoftReturn(TconvertedPass1 *cq);
void Justification(TconvertedPass1 *cq, unsigned char WPx);
void Language(TconvertedPass1 *cq, WORD WPx_Language);
void LineNumbering(TconvertedPass1 *cq, BYTE LineNumbering);
void PageNumber(TconvertedPass1 *cq);
void PlaceEndnotes(TconvertedPass1 *cq);
void PlaceIndex(TconvertedPass1 *cq);
//void PutCharacter(TconvertedPass1 *cq,char *CharStr);
void EndSection(TconvertedPass1 *cq, signed char WP);
void Page_number_position(TconvertedPass1 *cq, unsigned char WP);
void ParagraphNumber(TconvertedPass1 *cq);
void RowTable(TconvertedPass1 *cq, char LineType=2);
void SetEndnoteNum(TconvertedPass1 *cq, unsigned char WP);
void SetFont(TconvertedPass1 *cq, int PointSize, const char *FontName);
void SetFontSize(TconvertedPass1 *cq, char WP);
void SetFootnoteNum(TconvertedPass1 *cq, signed char WP);
void SetPgNum(TconvertedPass1 *cq, unsigned char WP);
void SoftHyphen(TconvertedPass1 *cq);
void SoftReturn(TconvertedPass1 *cq);
void StartSection(TconvertedPass1 *cq, signed char WP);
void Suppress(TconvertedPass1 *cq, char WP);
void Tab(TconvertedPass1 *cq, char WP);
void TableOfContents(TconvertedPass1 *cq, char WP);
void Terminate_Line(TconvertedPass1 *cq, char line_term);
void WidowOrphan(TconvertedPass1 *cq,signed char type);

void NewLine(TconvertedPass1 *cq);
void NewLines(TconvertedPass1 *cq, int Lines, bool CRFlag=true);


/* global functions of pass2.cc */
void Convert_second_pass(FILE *Strip,FILE *table, FILE *FileOut, FILE *log, FILE  *ErrorFile);


/* global functions of formulas.cc */
void AnyBox(TconvertedPass1 *cq, DWORD end_of_code);
void BoxTexFoot(TconvertedPass1 *cq, const TBox & Box);
#ifdef __Stringa_h
 char Remove1stArg(string & str,string & arg);
 bool RemoveLastArg(string & str,string & arg);
 bool RemoveSymbol(string & str1,string & str2,const char * symbol);
 string & FixFormulaStrFromTeX(string & StrEnd,const char chr_set=0);
 bool OptimizeFormulaStr(TconvertedPass1 *cq, string & StrBeg);
 bool FixFormula(TconvertedPass1 *cq, string & EquStr, int & Braces, int & BegBrace);
#endif
bool BoxTexHeader(TconvertedPass1 *cq, const TBox & Box);
extern int FormulaNo;

struct FmlTranslationArray
    {
    const char *szWP;			/* original WordPerfect term */
    const char *szTeX;			/* translated LATEX term     */
    char styles;			/* styles required for this glyph */
    };
extern const struct FmlTranslationArray FmlTransTable[];
#define MAX_ACCENT_TRN_ARR	9


/* global functions of image.cc */
void ImageWP(TconvertedPass1 *cq, const char *Filename, TBox & Box);
char *GetSomeImgName(const char *Ext=NULL);


/* global functions and variables of gettext.cc */
#define EnvLanguage "LANGUAGE="
#ifdef __gettext__

 #ifdef __cplusplus
  extern "C" {
 #endif
 void InitGettext(const char *GtxtDomain);
 void CheckGettext(const char *PROG_NAME, const char *GtxtDomain);
 //char *gettext__ (const char *__msgid);
 #ifdef __cplusplus
  }
 #endif

// #define HAVE_CATGETS 1
 #define ENABLE_NLS 1
 #include <locale.h>
 #include<libintl.h>
 #ifndef N_
  #define N_(EnString) EnString
 #endif
 #ifndef _
   #define _(EnString) gettext(EnString)
 #endif
#else
 #ifdef __BORLANDC__
  inline const char *_(const char *s) {return s;}
 #else
  #define _(arg) (arg)
 #endif
 #define N_(EnString) EnString
#endif


/* Global functions from wp2latex.cc */
extern long UnknownCharacters,UnknownObjects,CorruptedObjects;
void RunError(int ExitCode, const char *s="", const void *arg=NULL);
int CommandLine(int argc, char *argv[]);
void Heading(void);
void ShowHelp(void);
void ShowCopyright(void);
char YesNoIgnore(const char *str);


typedef TconvertedPass1 *(* Factory_Pass1)(void);
TconvertedPass1 *GetConverter(const char *ShortKey);


class FFormatTranslator
	{
private:static FFormatTranslator *First;
	FFormatTranslator *Previous;
	FFormatTranslator *Next;

	const char *ShortKey;
	Factory_Pass1 Factory;

public: explicit FFormatTranslator(const char *NewShortKey, Factory_Pass1 NewConverter=NULL);
	~FFormatTranslator();

	const char *shortkey() {return(ShortKey);}
	static FFormatTranslator *first() {return(First);}
	FFormatTranslator *next() {return(Next);}
	friend TconvertedPass1 *GetConverter(const char *ShortKey);
	};


typedef struct
{
   char LangShort[2];		///< Language abbreviation
   BYTE WP3LangId;
   const char *LangDesc;	///< LaTeX Language description
   SBYTE      UseLang;
} LangItem;

extern LangItem LangTable[31];

#define GERMAN_IDX	0
  

/* The Posix Standard do not require these constants to be defined. */
#ifndef SEEK_SET
 #define SEEK_SET 0
#endif
#ifndef SEEK_CUR
 #define SEEK_CUR 1
#endif
#ifndef SEEK_END
 #define SEEK_END 2
#endif

#ifdef __Stringa_h  //Only Strings related stuff
string Attributes2String(DWORD Attributes);
string & fGets2(FILE *f, string & pstr,long MaxStrSize=0);
temp_string MergePaths(const string & Path, const string & RelPath, bool EnsureTrail=true);
void PutFormula(TconvertedPass1 *cq, char *Str,const TBox & Box);
extern string RelativeFigDir, OutputDir;
#endif

#ifdef __Lists_h
extern list Counters;
extern list ImgInputDirs;
#endif

#ifdef __sets
extern set WP2LaTeXsty;
typedef enum 
{
  sty_foottext,
  sty_headtext,
  sty_trademark,
  sty_servicemark,
  sty_circchar,
  sty_astrike,
  sty_ostrike,
  sty_between,
  sty_bigominus,
  sty_bigsqcap,
  sty_because,
  sty_degrees,
  sty_identical,
  sty_image,
  sty_rimage,
  sty_therefore,
  sty_primechar,
  sty_twottchars,
  sty_Bullet,
  sty_HollowBullet,
  sty_shadebox,
  sty_grbox,
  sty_mathsmaller,
  sty_ctab,
  sty_xvadjust,
  sty_showuserlist,
  sty_rotate,
  sty_pagenumpos,
} wp2latex_sty_set;
#endif


/* Functions from wp2l_lib.cc */
void FixLabelText(const char *str, FILE *f);
void UpdateFigDir(void);
void Sys_Variable(void);
void PrintPackageList(void);

typedef struct
{
  const char	*Name;
  const char    *Translator;
  WORD		Id;
  bool		UseCpStyles;
} TOutCodePage;

extern const TOutCodePage OutCodepages[11];


#ifndef __Have_stricmp
 #ifdef __Have_strcasecmp
  #define stricmp strcasecmp
 #endif
 #ifndef stricmp        //already fixed?
  #define stricmp strcmp
 #endif
#endif


#ifdef __cplusplus
extern "C" {
#endif

/* functions from utf8.c */
DWORD utf8_fgetc(FILE *F);
#ifdef __cplusplus
}
#endif


#endif
