/******************************************************************************
 * 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"		/*Define types for BYTE, WORD, DWORD ...*/
#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	"4.22"
#define VersionDate	"30 Jun 2026"  /* day (space) month (space) full year */


/** Constants for a flag InputPS */
typedef enum
{
    IMG_InputPS	=	0,
    IMG_graphicx =	2,
    IMG_epsfig =	4,
    IMG_graphics =	8
} EflagsInputPS;

extern uint16_t OutCodePage, WPcharset;
extern bool Index, Interactive, NFSS, TABs, twoside, ExactFnNumbers, CPStyles,
	 EraseStrip, UndoRedo, Noclobber;
extern int8_t arabtex, 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, NewUnicodeChar,
	 SaveWPG, mxedruli;
extern signed char CheckOversize;
extern int LaTeX_Version;
extern signed char Verbosing;
extern bool TexChars,ExtendedCheck,OptimizeSection,FixSpaces;
#ifdef _REENTRANT
extern short Job4Run;
#endif

typedef struct			/* Auto detection structure for file formats */
	{
	const char *DocumentType;
	const char *Converter;	///< ASCII key for looking converter module.
	const char *Extension;
	uint16_t DocVersion;
	float Probability;	///< <-1 surely not  0 don't know  1 surely yes>
	uint32_t 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
#define Georgia_Font	  30
#define Arabic_Font	  31
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);
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);

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


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

/* Variables for Convert_first_pass: */

typedef enum
{
    NormalText =  0,
    HeaderText,
    CharsOnly,
    Nothing
} E_OBJECT_FILTER;


#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);

temp_string CutFileName(const char *FullFilename); //from wp2lfuti.cc

extern string wpd_filename;
#endif



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

typedef struct
	{
	uint8_t  AnchorType;	///< 0-Paragraph, 1-Page, 2-Character
	uint8_t  HorizontalPos;	///< 0-Left, 1-Right, 2-Center, 3-Full
	uint8_t  Contents;	///< 1-text, 2-disk image, 3-buildin image, 4-equation
	uint8_t  Type;
	float Width;		///< Expected width of image in [mm] ?? or [cm]??, or <=0 when unknown.
	float VScale;
	float HScale;
	uint16_t RotAngle;	///< Rotation in degrees
	uint16_t  CaptionSize;
	uint32_t CaptionPos;
	int8_t Image_type;	///< 0-external, 1-buildin WPG1, 2-buildin WPG2
	uint32_t Image_offset;	///< Ofset of embedded image blob in a host file.
	uint32_t 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;
  uint32_t 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;
  uint16_t tabpos[TAB_POS_SIZE];
  char tab_type;

  int WP_sidemargin,Lmar,Rmar;

  uint16_t ind_leftmargin, ind_rightmargin;

  unsigned char by, subby;
  uint32_t 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[64];

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

  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);

#ifdef __Limited_Proc_Size
  void PleaseReport(const char *Feature, const char *Type) const {}
#else
  void PleaseReport(const char *Feature, const char *Type);
#endif
};

/* 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 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,
  FONT_GEORGIA = 4,
  FONT_ARABIC = 5
} FontTypes;


/* 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(uint16_t char_code, TconvertedPass1 *cq, const 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;

#ifdef __Rasters_h
void Color(TconvertedPass1 *cq, signed char WP, RGBQuad *RGB=NULL);
#endif
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, uint16_t WPx_Language);
void LineNumbering(TconvertedPass1 *cq, uint8_t LineNumbering);
void PageNumber(TconvertedPass1 *cq);
void PlaceEndnotes(TconvertedPass1 *cq);
void PlaceIndex(TconvertedPass1 *cq);
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, uint32_t 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);
 void FixConsole2UTF8(void);
 #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
   uint8_t WP3LangId;
   const char *LangDesc;	///< LaTeX Language description
   int8_t  UseLang;
} LangItem;

extern LangItem LangTable[31];

#define GERMAN_IDX	0
  

/* The Posix Standard does 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
temp_string Attributes2String(uint32_t Attributes);
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;
  uint16_t	Id;
  bool		UseCpStyles;
} TOutCodePage;

extern const TOutCodePage OutCodepages[14];


#ifndef FINAL
void CrackObject(TconvertedPass1 *cq, uint32_t end_of_code);
#endif

#ifdef __cplusplus
extern "C" {
#endif

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

typedef enum
{
  LEAVE_ONE_EMPTY_LINE = -20,	/**< Left one empty line for new enviroment. */
  FIRST_CHAR_MINIPAGE =	 -10,	/**< Line before nested enviroment change, first line of minipages. */
  JUNK_CHARS =		 -1,	/**< The line contains not text directives. */
  NO_CHAR =	 	  0,	/**< No valid character on the line. */
  CHAR_PRESENT =	  1,	/**< Valid character placed on the line. */
} TCharOnLine;


typedef enum
{
  STYLE_DISABLED = -1,
  STYLE_NOTUSED = 0,
  STYLE_USED = 1
} TStyle;


#if defined(__MINGW32__) || defined(__MINGW64__)
 #ifdef printf
   #undef printf
 #endif
#endif

#endif
