File: wp2latex.cc

package info (click to toggle)
wp2latex 3.112%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,916 kB
  • sloc: cpp: 49,708; ansic: 9,318; asm: 5,429; makefile: 542; sh: 22
file content (894 lines) | stat: -rw-r--r-- 27,044 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/********************************************************************************
 * 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 wpd_filename, 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 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)
{
  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-2022\n"),
	    VersionWP2L);
}


static char StyleUsed(SBYTE 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 FOJTIK@PENGUIN.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-2022 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(__u8)!=1)||(sizeof(__u16)!=2)||(sizeof(__u32)!=4)||
   (sizeof(__s8)!=1)||(sizeof(__s16)!=2)||(sizeof(__s32)!=4))
	{
	Heading();
	fprintf(err,_("\nFatal: Code was badly compiled. sizeof(__u8)=%d sizeof(__u16)=%d sizeof(__u32)=%d\nCheck typedfs.h !!!!!"),
           (int)sizeof(__u8), (int)sizeof(__u16), (int)sizeof(__u32));	
        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)
    {
    printf(_("Note: There are some asynchronous jobs that are still running."));
    printf("--------");
    int SecCounter=0;
    while(JobBase::JobCount>0)
    {
      printf("\b\b\b\b\b\b\b\b%2dj%4ds", JobBase::JobCount, SecCounter++);
      FinishJobs(1000);	// Wait to finish them.
    }
    printf(_("\nNote: All jobs finished now."));
    }
  EndJobs();
#endif

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