/********************************************************************************
 * program:     wp2latex                                                        *
 * function:    convert WordPerfect 1.x,2.x,3.x,4.x,5.x and 6.x files into LaTeX*
 * modul:       wp2latex.cc                                                     *
 * description: The main module that communicates with OS.                      *
 * licency:     GPL		                                                *
 ********************************************************************************/

///To do list:///
// u minipage se musi nacist vertical position a v pripade full nastavit \vsize
// podivat se na pismo wsuipa
// sjednotit LineSpacing pro vsechny verze WP
// vnorene dokumenty
// udelat titulni stranku i pro WP6.x
// pokusit se zkonvertovat invisible characters
// nechodi center tab a right tab
// konverze prikazu alignr, alignl, alignc v matematickem modu
// List of authotrities neni dodelan

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

#include "common.h"	// This header ensures that __UNIX__ is properly defined.

#if defined(__UNIX__) || defined(__DJGPP__) || defined(_MSC_VER)
 #define SIGNALS_SUPPORTED
 #include <signal.h>
#endif

#if defined(__UNIX__) || defined(__DJGPP__)
 #include <unistd.h>
#endif

//Non standard include files
#include "stringa.h"
#include <lists.h>
#include "wp2latex.h"

#ifdef _MSC_VER
 #include <locale.h>
#endif

#ifdef _REENTRANT 
 #include "jobs/jobs.h"
 #ifndef INFINITE
  #define INFINITE            0x7fffffffL
 #endif
#endif

//#include <alloc.h>


extern FILE *wpd, *table;
extern FILE *strip, *logg, *err;
extern FILE *latex;
extern string force, FORCE;


extern string strip_filename, table_filename, latex_filename,
       log_filename;
extern string wpd_password;

extern list ImgInputDirs;

#ifdef _has_MemStreams
extern int UseMemStream;
#endif


/// Definition of methods of the Percentor class - only integer arithmetic due to the speed problems.
void Percentor::Actualise(long NewValue)
{
 NewValue -= StartValue;
 NewValue >>= Shift;
 NewValue = (100*NewValue)/Range;

 if(NewValue != CurrentPercent)
 {
   CurrentPercent = NewValue;
   Show();
 }		
}


void Percentor::Hide(void)
{
 if(displayed) printf("\b\b\b\b");
 displayed=false;
 CurrentPercent=-1;
}


void Percentor::Init(long Start, long End, const char *text)
{
 StartValue=Start;
 EndValue=End;
 if(Start==End) Range=1;
	   else Range=End-Start;
 Shift=0;
 while(Range>=512) 	   
     {
     Shift++;
     Range>>=1;
     //printf("R=%ld\n",Range);
     }
 if(Verbosing >= 1)
     {
     if(text) puts(text);	// appends \n automatically
         else putchar('\n');
     printf(_("Converting-percentage: "));
     }
}


Percentor::Percentor(void)
{
 Range = 100;
 Shift = 0;
 displayed = false;
 CurrentPercent = -1;
}


Percentor::~Percentor(void)
{
 return;
}


void Percentor::SetPercent(int NewPercent)
{
 if(NewPercent==CurrentPercent && displayed) return;
 CurrentPercent=NewPercent;
 Show();
}


void Percentor::Show(void)
{
 printf(displayed?"\b\b\b\b%3d%%":"%3d%%",CurrentPercent);
 fflush(stdout);
 displayed=true;
}


/** This function reads string from standard console input. */
void StrGets(string & s)
{
char c;

  c = 0;
  s.erase();
  while(c!='\n')
      {
      c = fgetc(stdin);
      switch(c)
	 {
	 case '\n':break;
	 default:s+=c;
	 }
      }
}


/// This procedure displays errors that occured inside atoms unit
#ifdef ERROR_HANDLER
void RaiseError(int ErrNo, const void *Instance)
{
static int LastErrNo=0;
static const void *LastInstance=NULL;
const char *UnitName="";
  if(Verbosing<=-1) return;
  if(LastErrNo!=ErrNo || LastInstance!=Instance)
    {
    switch(ErrNo&0xFF00)
      {
      case ListsId: UnitName=" Lists"; break;
      case StringsId: UnitName=" Strings"; break;
      case SetsId:  UnitName=" Sets"; break;
      case MatrixId:UnitName=" Matrices"; break;
      case StackId: UnitName=" Stacks"; break;
      case IntervalId: UnitName=" Intervals"; break;
      case RasterId: UnitName=" Rasters"; break;
      case DblListId: UnitName=" DblLists"; break;
      }
    fprintf(err,_("\nERROR: Internal inside ATOMS unit%s 0x%X object:(%p)"),
	UnitName,ErrNo,Instance);
    LastErrNo=ErrNo;LastInstance=Instance;
    }
}
#endif


/** This function handles error situation. */
void RunError(int ExitCode, const char *s, const void *arg)
{
#ifdef _REENTRANT
  AbortJobs();
#endif
  putchar('\n');
  switch(ExitCode)
    {
    case -2:
    case -1:   ExitCode=0;	/*silently exit program*/
	       break;
    case 0:    fprintf(err,_("Conversion completed.\n\n"));
	       break;
    case 0x2:  fprintf(err,_("Error: File %s not found.\n"),chk(s));
	       break;
    case 0x3:  fprintf(err,_("Error: Path not found.\n"));
	       break;
    case 0x4:  fprintf(err,_("\nError: File %s can not be created."),chk(s));
	       break;
    case 0x6:  fprintf(err,_("Error: Temporary file %s cannot be created!\n"),chk(s));
	       break;
    case 0x10: fprintf(err,_("Info: Program was aborted.\n"));
	       break;
    case 0x15: fprintf(err,_("Info: Please report this situation to enable further developping WP2LaTeX.\n%s"),chk(s));
	       break;
    case 0x20: fprintf(err,_("Error: Output device is full.\n"));
    	       break;
    case 0x8B: fprintf(err,_("Fatal: Program Error. Write full bug report.\n"));
               break;
    case 0x200:fprintf(err,_("Error: No filename entered!\n"));
               break;
    case 0x201:fprintf(err,_("Error: File \"%s\" is not a WordPerfect document!\n"),wpd_filename());
	       break;
    case 0x202:fprintf(err,_("\nError: Unsupported format "));
	       if(arg)
		 {
		 const FFormatDetect *FFD = (const FFormatDetect *)arg;
		 fprintf(err,"(%s",FFD->DocumentType);
		 if(FFD->DocVersion!=0)
		   fprintf(err," r%u.%u", FFD->DocVersion>>8, FFD->DocVersion & 0xFF);
		 fprintf(err,")");
		 }
	       fprintf(err,"!\n");
	       break;
    case 0x203:fprintf(err,_("Error: Sorry, I have no idea how to decrypt this file!\n"));
	       break;
    case 0x204:fprintf(err,_("Fatal: Memory exhausted!\n"));
	       break;
    }

  if(wpd != NULL)   fclose(wpd);     	  wpd = NULL;
  if(strip != NULL)
  	{
	fclose(strip);			  strip = NULL;
#ifndef DEBUG
	if(EraseStrip) unlink(strip_filename);
#endif
	}
  if (table != NULL)
	{
	fclose(table);			 table = NULL;
#ifndef DEBUG
	if(EraseStrip) unlink(table_filename);
#endif
	}
  if (latex_filename != '-')
      if (latex != NULL) fclose(latex);   latex = NULL;
  if (logg != NULL)
        {
        if(!ExitCode)
	  fprintf(logg,_("\n!!!! Fatal Exit No %d!!!!\n"),ExitCode);
	fclose(logg);		          logg = NULL;
        }

  exit(ExitCode);
}


/** This function asks user to enter password. */
void ObtainPassword(string & password)
{
  printf(_("\nEnter Password: "));
  StrGets(password);
}


/** This function asks waits for user response Yes, Ino or Ignore.
 * Note: This function is replaced in GUI and it emits dialog here.
 * @param[in]	Prompt for user. */
char YesNoIgnore(const char *str)
{
char c;

//TryAgain:
  printf("%s",str);

NextChar:
  c = getchar();
//putchar('\n');
  switch(c)
	{
	case 'A':
	case 'a':
	case 'Y':
	case 'y':getchar();return('Y');
	case '\n':return('Y');//goto TryAgain;
	case 'n':
	case 'N':getchar();return('N');
	case 'I':
	case 'i':getchar();
		 ExtendedCheck=true;
		 return('I');		// ignore=run anyway
	default:if(isspace(c)) goto NextChar;
	}
return('?');
}


/** This function prints text console WP2LaTeX heading. */
void Heading(void)
{
static bool printed=false;
 if(printed) return;
 printed = true;

 if(Verbosing < 1) return;
 printf(_("\n>>>WP2LaTeX<<< Conversion program: From Wordperfect to LaTeX Version %s \n"
	  "  (c) Made by J.Fojtik  ---- Date : 1996-2024\n"),
	    VersionWP2L);
}


static char StyleUsed(int8_t u)
{
  if(u<=-1) return '-';
  if(u>=+1) return '+';
return '*';
}



/** This function prints wp2latex help to the text console. */
void ShowHelp(void)
{
 puts(_("\nWrite any suggestions, reports or bugs to address JaFojtik@seznam.cz"
	  "\nor JaFojtik@yandex.com."));

 puts(_("\nPackage signalling: '-' disabled, '+' enable on demand, '*' enabled always."));

 printf(_(
	  "\nParameters: WP2LATEX [switches] [input_file [output_file]] [switches]"
	  "\n   -?  --help   Display this help page."
	  "\n   -configfile -@ filename   Load an external configuration file."
	  "\n   -copyright   Display information about Copyright of WP2LaTeX."
	  "\n   -cp-codepage Use \"codepage\" for output text. Supported code pages are"
	  "\n         \"852\"(ISO8), \"866\"(Russ), \"895\"(Kamenicky), \"1250\"(Win),"
	  "\n         \"1251\"(WinRuss), \"ISO8859_1\", \"ISO8859-2\", \"KOI8R\", \"UTF8\"."
	  "\n   -cp-styles   Turn on special styles for codepages."
	  "\n   -CurrentFontSet  codepage    Change codepage for a current font."
	  "\n               \"Magical\" WP's codepage 12. Same argunents as -cp-"
	  "\n   -epsfig      %cUse style epsfig.sty for PostScript images."
	  "\n   -extract-images %sImages will be extracted into separate files."
	  "\n   -fancyhdr    Use package fancyhdr.sty for headers and footers"
	  "\n   -fig-output-dir Use this directory for storing images. Prefer relative path."
	  "\n   -fix-spaces  Try to fix multiple spaces by ~."
	  "\n   -force-xxx   Force of defined format xxx = WP4.x, WP5.x, HTML, RTF"
	  "\n   -FORCE-xxx   Like -force but override any attempt of autodetection."
	  "\n   -graphics    %cUse style graphics.sty for PostScript images."
	  "\n   -graphicx    %cUse style graphicx.sty for PostScript images."
	  "\n   -charset1    %sSwitch internal WordPerfect charset to set 1."
	  "\n   -charsetCZ   %sSwitch internal WordPerfect charset to keybcs."
	  "\n   -i; -o; -l   Explicitly define an input; output; log file"
	  "\n   -ignore-tabs %sRemove all [TAB] symbols from WP document."
	  "\n   -image-path PATH/  Add one item to searching path for images."
	  "\n   -input-PS    %cUse PostScript features in the LaTeX (mainly images)."
	  "\n   -L LANGUAGE  Switch message translations to language LANGUAGE."
	  "\n   -LaTeX2      %sOptimize output for LaTeX 2.09."
	  "\n   -LaTeX3      %sOptimize output for LaTeX 2e or LaTeX 3.0"
	  "%s"					// reserved for optional memstreams
          "\n   -no-FEATURE  Disable given feature. Available features are (accents, amssymb,"
	  "\n                 bbm, columns, extractWPG, fancyhdr, latexsym, texchars, wasy)."
	  "\n   -no-lang-XXX Disable language XXX."
	  "\n   -no-safemode Disable checking features - faster conversion."
	  "\n   -safemode    %sCheck safely consistency of each object and try to fix all"
	  "\n                incorrect things. Good for corrupted WP files."
	  "\n   -s \"password\" Password for decoding WP document (WP4.x & WP5.x only)."
	  "\n   -S -silent   %sSwitch to the silent mode."
	  "\n   -texchars    %cDo not interpret TeX macros (all chars 32-128 will not be"
	  "\n                converted to TeX sequences)."
          "\n   -use-all     Use all character styles available (some graphic styles"
          "\n                are mutually exclusive)."
	  "\n   -v           Get info about version."
	  "\n"),	  
          StyleUsed(((InputPS&~1)==IMG_epsfig)?(InputPS&1):-1),
	  (SaveWPG>0)?"*":"",
          StyleUsed(((InputPS&~1)==IMG_graphics)?(InputPS&1):-1),
	  StyleUsed(((InputPS&~1)==IMG_graphicx)?(InputPS&1):-1),
	  WPcharset==1?"*":"",
	  WPcharset==2?"*":"",
	  (TABs==false)?"*":"",
	  StyleUsed(((InputPS&~1)==IMG_InputPS)?(InputPS&1):-1),
	  (LaTeX_Version & 0xFF00) == 0x200?"*":"",
	  (LaTeX_Version & 0xFF00) == 0x300?"*":"",
#ifdef _has_MemStreams
          _("\n   -MemStream     Use memory stream instead of temporary files."),
#else
          "",
#endif
	  ExtendedCheck==true?"*":"",
	  Verbosing>0?"":"*",
	  StyleUsed(TexChars)
	  );
   PrintPackageList();
#ifndef Registered
   puts(_("\nPlease send me a postcard. Run \"wp2latex -copyright\" for more details."));
#endif
   //printf("InputPS=%d %d %d %d",InputPS, (InputPS&~1)==IMG_graphics, InputPS&~1, IMG_graphics);
}


void ShowCopyright(void)
{
  puts(_("\nThis program and related files are copyright (c) 1996-2024 Fojtik Jaroslav."
	 "\nThis code can be redistributed and/or modified under the terms of the GNU"
	 "\nGeneral Public License available from: http://www.gnu.org/copyleft/gpl.html."
	 "\nWith one additional requirement:"
	 "\n         If you decide to modify, you should somehow sign a modified"
	 "\nplace in the code and you must append your name at the end of this message"
	 "\nin this manner:"
	 "\n \"Modified by Mr Xxxxx Yyyy month.day.year\""
	 "\n        If you decide to modify this code, try to ask me first. Your change may"
	 "\nbe useful for others and it will be good to include it into further releases."
	 "\n        If you didn't contribute to WP2LaTeX in any way, you must not say that"
	 "\nyou are author of it."));

  puts(_("\nSomebody at Eindhoven Univ of Techn wrote a WordPerfect 5.0 to LaTeX"
	 "\nconversion program (only running on MSDOS of course) :=)"
	 "\n           This program was completely rewritten by Jaroslav Fojtik"
	 "\nand many new functions were added (eg conversion of math equations)"));

  puts(_("\nImportant note: Conversions performed by wp2latex are only partial."
         "\nPrint the resulting document and compare carefully with original."
         "\nIn all but the simplest documents you will have to do further editing."
         "\nOr you may wish to edit the WordPerfect document to remove unwanted"
         "\ncodes (such as Tab, Tab Set), then run it through wp2latex again."));

  puts(_("\nThanks to:R.C.Houtepen            for initial WP2LaTeX pascal release (1990)"
	 "\n          Rafael Rodriguez Pappa  for several notes and bugfixes"
	 "\n          Damil Cavar             for several bugreports"
	 "\n          Hilmar Preusse          for translating several WP extended chars; creating"
	 "\n                                  Debian package and translating messages to the German."
	 "\n          Christoffer Sorensen    for formula conversion related bugreports"
	 "\n          Aleksey Gulvanjuk       for adding Russian codepages"
	 "\n          Fridrich Strba          for valuable hints and WP MAC documentation"
	 "\n          David Derbes            for hints about MAC compilation"
         "\n          Peter Dyballa           for preparation of MAC binaries and useful hints."
         "\n          Schobeiri, Taher M.     for donating WP2LaTeX."
	 "\n          and of course to all authors of previous releases of WP2LaTeX"
	 "\n"
	 "\nIf you find this program useful please send me a *POSTCARD* with"
	 "\ncharacteristic image of your country."
	 "\nMy address is: Jaroslav Fojtik; Dvouramenna 13; Prague 4; Czech Republic 14000"
	 "\n"
	 "\nAuthor is not liable for any damage of your system or loose of your profit"
	 "\ncaused by using or not using this program."
	 "\n"));
}


/** Ask user to get log file. */
void GetLogFileName(string & LogFile)
{
string s;
  Heading();
  printf(_("\nLog file name [%s]: "), chk(LogFile()));
  StrGets(s);
  if(!s.isEmpty()) LogFile=s;
}


static int Filenames(void)
{
string StrName;
int p;

  Heading();

  if(latex_filename.isEmpty())
      {
      if(Interactive && (Verbosing>=1 || wpd_filename.isEmpty()))
         {
	 printf(_("\nWordPerfect-filename [%s]: "), chk(wpd_filename()));
	 StrGets(StrName);
	 if(!StrName.isEmpty()) wpd_filename=StrName;
         }

    if(wpd_filename.isEmpty())
        { 			  /* No filename entered */
	RunError(0x200);
        }

    p=length(wpd_filename);
    while(p>0)
	 {
	 if(wpd_filename[p]=='.') break;
	 if((wpd_filename[p]=='/')||(wpd_filename[p]=='\\'))
		{
		p=length(wpd_filename);
		break;
		}
	 p--;
	 }
    if(p<=0) p=length(wpd_filename); //no extension


    if(latex_filename.isEmpty())
          {
	  latex_filename=copy(wpd_filename,0,p) + ".tex";
	  }

    if(Interactive && (Verbosing >= 1 || latex_filename.isEmpty()))
       {
       printf(_("LaTeX-filename [%s]: "), chk(latex_filename()));
       StrGets(StrName);
       if(!StrName.isEmpty()) latex_filename = StrName;
       }
  }

  p=length(wpd_filename);
    while(p>0)
    	 {
         if(wpd_filename[p]=='.') break;
         if((wpd_filename[p]=='/')||(wpd_filename[p]=='\\'))
	 	{
                p=length(wpd_filename);
                break;
		}
         p--;
	 }

  strip_filename = copy(wpd_filename,0,p) + ".STR";
  table_filename = copy(wpd_filename,0,p) + ".TBL";

  return(0);
}


static void CheckOptions(void)
{
 if(LaTeX_Version<0x300)		//disable colors for LaTeX 2.09
   {
   if(colors > 1)
	fprintf(err,_("Warning: Color style is available only for LaTeX 2e !\n"));
   colors=-1;
   }
}


#if defined(SIGNALS_SUPPORTED) & !defined(DEBUG)
/** This is a main signal handler */
void sig_int(int signo)
{
static int sigcount=0;

 if(sigcount++>2) abort();
 switch(signo)
    {
    case SIGINT:RunError( 0x10, "");   break;
    case SIGSEGV:RunError(0x8B, "");   break;
    }
}

static void HookSignals(void)
{
 signal(SIGINT,sig_int);
 signal(SIGSEGV,sig_int);
}
#endif


void AskUser(void)
{
 if(!Interactive)
   {
   fprintf(err,_("\nFatal: Preventing to run defective code."));
   abort();
   }
 fprintf(err,_("\nContinue anyway? y/N "));
 if(toupper(getchar())!='Y') abort();
 getchar();			//Get rid of buffered Enter key.
}


/** This procedure checks sizes of standard variables. */
static void CheckCompiler(void)
{
char str[20];
 if((sizeof(uint8_t)!=1)||(sizeof(uint16_t)!=2)||(sizeof(uint32_t)!=4)||
   (sizeof(int8_t)!=1)||(sizeof(int16_t)!=2)||(sizeof(int32_t)!=4))
	{
	Heading();
	fprintf(err,_("\nFatal: Code was badly compiled. sizeof(uint8_t)=%d sizeof(uint16_t)=%d sizeof(uint32_t)=%d\nCheck typedfs.h !!!!!"),
           (int)sizeof(uint8_t), (int)sizeof(uint16_t), (int)sizeof(uint32_t));	
        AskUser();
	}
  sprintf(str,"%4.3f",1234.567);
  if(strcmp(str,"1234.567"))
    {
#ifdef _MSC_VER
    setlocale(LC_NUMERIC,"English"); 
    sprintf(str,"%4.3f",1234.567);
    }
  if(strcmp(str,"1234.567"))
    { 
#endif
    Heading();
    fprintf(err,_("\nFatal: Problem inside locale conversion of doubles '%s' expected '%s'!"),
       str,"1234.567");
    AskUser();
    }
 else
   {
   string s;
   s.printf("%4.3f",2345.678);
   if(s!="2345.678")
     { 
     Heading();
     fprintf(err,_("\nFatal: Printing to string does not work, obtained '%s' expected '%s'!"), s(), "2345.678");
     AskUser();
     }
   }
#if defined(POINTER_SIZE)
 if(8*sizeof(void*) != POINTER_SIZE)
 {
   Heading();
   fprintf(err,_("\nFatal: Compillation has been optimised for pointer size %ubits, pointer size is %ubits!"), POINTER_SIZE, (unsigned)sizeof(void*)*8);
   Interactive = false;	// This problem is really unpleasant, abort app.
   AskUser();
 }
#endif
#ifdef LO_ENDIAN
  int i=1;
  if(*((unsigned char *)&i) != 1)
  {
    Heading();
    fprintf(err,_("\nFatal: Compillation has been optimised for LO_ENDIAN that does not belong to this system!"));
    AskUser();
  }
#endif
}


/*---begin of PROGRAM---*/
int main(int argc, char *argv[])
{
TconvertedPass1 *cqPass1;

  latex = NULL;		/* The output Latex file */
  strip = NULL;		/* The temporary file rough conversion */
  table = NULL;		/* The temporary file with line informations */
  wpd   = NULL;		/* The input WP file */
  logg  = NULL;		/* The output log file */
  err   = stderr;	/* The output for error messages */

	/* Default initialization */
  Verbosing = 1;
  TexChars = false;
  OutCodePage = 0;	/*unknown - no 8 bit code generated*/
  WPcharset = 1;	/*common charset 1*/
  ExtendedCheck = true;	/*true*/
  FixSpaces = false;
  OptimizeSection = true;
  UnknownCharacters = UnknownObjects = CorruptedObjects = 0;
  cqPass1 = NULL;

#if defined(SIGNALS_SUPPORTED) & !defined(DEBUG)
  HookSignals();
#endif

#ifdef DEBUG
  log_filename = "default.log";
#endif
//  clrscr();
  
#ifdef __gettext__
  InitGettext("wp2latex");
#endif /* __gettext__ */

//printf("%ld",coreleft());

  CheckCompiler();
  Sys_Variable();		// Look into environment variables.
  CommandLine(argc,argv);	// Parse command line arguments.
#ifdef __gettext__
  CheckGettext(argv==NULL?NULL:*argv, "wp2latex");
#endif
  Filenames();			// Ask user to enter filename if missing.
  UpdateFigDir();
  CheckOptions();

  if(LaTeX_Version>=0x209)
    StyleOpCl = StyleOpCl3;
  else    
    StyleOpCl = StyleOpCl2;

#ifdef _REENTRANT
  InitJobs(Job4Run);
#endif

  if((wpd = fopen(wpd_filename, "rb")) == NULL)
	RunError(2,wpd_filename);

  if(!FORCE.isEmpty())
     {
     cqPass1 = GetConverter(FORCE);
     if(cqPass1==NULL)
       {
         fprintf(err,_("\nError: FORCED conversion module \"%s\" was not found!"),FORCE());
         goto NoModule;					// It makes no sense to continue, exit a program.
       }
     else fprintf(err,_("\nWarning: Conversion module %s is FORCED. No autodetection is possible. ERRORS may occur!!!"),FORCE());
     }
  else
     {
     CheckFileFormat(wpd,FilForD);
     cqPass1 = GetConverter(FilForD.Converter);
     if(cqPass1==NULL && !force.isEmpty())
	{
	cqPass1=GetConverter(force);
	if(cqPass1==NULL)
	   {
	   fprintf(err,_("\nError: forced conversion module \"%s\" was not found!"),force());
NoModule:  fprintf(err,_("\nType \"wp2latex -v\" to see a list of available modules."));
	   RunError(-2);			   // It makes no sense to continue, exit a program.
	   }
	else
	   {
	   fprintf(err,_("\nWarning: Conversion module %s is forced. No autodetection is possible. ERRORS may occur!!!"),force());
	   ExtendedCheck = true;	/* It would be better to switch safe mode on. */
	   }
	}
     }
#ifdef _has_MemStreams
  char *bp_strip=NULL,*bp_table=NULL;
  size_t size_strip,size_table;
  if(UseMemStream)
       {
       if((strip=open_memstream(&bp_strip, &size_strip)) == NULL)
           RunError(4,"memstream");
       if((table=open_memstream(&bp_table, &size_table)) == NULL)
           RunError(4,"memstream");
       }
  else
#endif  
       {
       if((strip=OpenWrChk(strip_filename, "w",err)) == NULL)
	 RunError(4,strip_filename);
       if((table=OpenWrChk(table_filename, "w+b",err)) == NULL)
	 RunError(4,table_filename);
       }    	    
       
  logg = NULL;
  if(!log_filename.isEmpty())
    {
    if(wpd_filename == log_filename)
      {
      if(err)
        fprintf(err,_("\nError: Log filename equals document filename. This could erase original document!"));
      log_filename.erase();
      }
    else
      {
      if((logg = OpenWrChk(log_filename, "w", err)) == NULL)
	{
        if(err)
	  fprintf(err,_("\nWarning: Cannot open log file %s ..."),log_filename());
	}
      else fprintf(logg,_("%% log file for converted file %s, %s ver %u.%u\n"
			  "%% conversion program WP2LaTeX v. %s from %s.\n"),
			   wpd_filename(), chk(FilForD.DocumentType), FilForD.DocVersion>>8, FilForD.DocVersion & 0xFF,
                           VersionWP2L, VersionDate);
      }
    }

  if(cqPass1!=NULL)
	{
	if(Verbosing >= 1) printf(_("\nConverting ...\n"));
	cqPass1->InitMe(wpd, table, strip, logg, err);
	if(cqPass1->Convert_first_pass()<=0)
	   {
	   if(Verbosing >= 1) printf(_("\nInput file is empty\n"));
	   goto EmptyInput;
	   }
	if(Verbosing >= 1) putchar('\n');
	delete cqPass1;
	cqPass1=NULL;
	}
  else RunError(0x202,"",&FilForD);  /* unsupported document version */

  if(wpd != NULL)
          {
          fclose(wpd);
          wpd = NULL;
          }	  
  if(strip != NULL)
          {
          if(fflush(strip)) RunError(0x20,""); //The RunError procedure will erase strip in this case
	  if(fclose(strip)) {strip = NULL;RunError(0x20,"");}
          strip = NULL;
          }
	  		 
  if(table != NULL)
         {
         if(fflush(table)) RunError(0x20,""); //The RunError procedure will erase table in this case
         if(fclose(table)) {table = NULL;RunError(0x20,"");}
         table = NULL;
         }
		 
  if(logg!=NULL) fprintf(logg,_("\n%% pass1 finished going to pass2\n\n"));

	/* Prepare files for pass2 */
#ifdef _has_MemStreams  
  if(UseMemStream)
       {
       if((strip=fmemopen(bp_strip, size_strip, "r")) == NULL)
	 RunError(2,strip_filename);
       if((table=fmemopen(bp_table, size_table, "r+b")) == NULL)
	 RunError(2,table_filename);
       }	  
  else       
#endif
       {
       if((strip=fopen(strip_filename, "r")) == NULL)
	 RunError(2,strip_filename);
       if((table=fopen(table_filename, "r+b")) == NULL)
	 RunError(2,table_filename);
       }	   
	
  if(latex_filename == '-') latex=stdout;
      else if ((latex=OpenWrChk(latex_filename, "w", err)) == NULL)
		 RunError(4,latex_filename);
	
	
  if(Verbosing >= 1) putchar('\n');
  Convert_second_pass(strip, table, latex, logg, err);
  if(Verbosing >= 1) putchar('\n');

EmptyInput:
  if(strip != NULL) fclose(strip);   strip = NULL;
  if(table != NULL) fclose(table);   table = NULL;
  if(latex_filename != '-')
    if(latex != NULL)
      {
      if(fclose(latex)) {latex = NULL;RunError(0x20,"");}
      }
  latex = NULL;
  if(logg != NULL)
    {
    fprintf(logg,_("\n%% pass2 finished\n"
	              "%%  There were %ld unconverted characters.\n"
		      "%%  There were %ld unrecognized/ignored objects.\n"),UnknownCharacters,UnknownObjects);
    if(CorruptedObjects>0)
	    fprintf(logg,_("%%  There were %ld corrupted objects.\n"),CorruptedObjects);
    if(fclose(logg))
    fprintf(err,_("\nError: Log file is not completely written."));
    }
  logg = NULL;

	/* Delete auxillary files */
#ifdef _has_MemStreams  
  if(bp_strip!=NULL) {free(bp_strip);bp_strip=NULL;}
  if(bp_table!=NULL) {free(bp_table);bp_table=NULL;}
  if(!UseMemStream) 
#endif  
    if(EraseStrip)
      {
#ifndef DEBUG
      unlink(strip_filename);
      unlink(table_filename);
#endif
      }

#ifdef _REENTRANT
  if(JobBase::JobCount>0)
  {
    if(Verbosing >= 1)
    {
      printf(_("Note: There are some asynchronous jobs that are still running."));
      printf("--------");
    }
    int SecCounter=0;
    while(JobBase::JobCount>0)
    {
      if(Verbosing >= 1)
          printf("\b\b\b\b\b\b\b\b%2dj%4ds", JobBase::JobCount, SecCounter++);
      FinishJobs(1000);	// Wait to finish them.
    }
    if(Verbosing >= 1)
        printf(_("\nNote: All jobs finished now."));
  }
  EndJobs();
#endif

  //printf("%ld",coreleft());
  return(0);
}
