summaryrefslogtreecommitdiffstats
path: root/filters/kword/mswrite/libmswrite.cpp
blob: 268e75a729801867b66ce77b982e0a7e78b03b9e (plain)
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
/* This file is part of the LibMSWrite Library
   Copyright (C) 2001-2003 Clarence Dang <clarencedang@users.sourceforge.net>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License Version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License Version 2 for more details.

   You should have received a copy of the GNU Library General Public License
   Version 2 along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.

   LibMSWrite Project Website:
   http://sourceforge.net/projects/libmswrite/
*/

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "libmswrite.h"

namespace MSWrite
{
	FormatInfo::FormatInfo () : m_nextChar (0),
											m_leftMargin (0xFFFF), m_rightMargin (0xFFFF),
											m_fontTable (NULL)
	{
		// m_type =
	}

	FormatInfo::~FormatInfo ()
	{
	}

	bool FormatInfo::readFromDevice (void)
	{
	CHECK_DEVICE;

	#ifdef DEBUG_FORMATINFO
		if (m_type == ParaType)
			m_device->debug ("\n<<<< libmswrite.cpp::FormatInfo::readFromDevice (ParaType) >>>>\n");
		else	// if (m_type == CharType)
			m_device->debug ("\n<<<< libmswrite.cpp::FormatInfo::readFromDevice (CharType) >>>>\n");
	#endif

		int formatInfoPageNum;
		if (m_type == ParaType)
			formatInfoPageNum = m_header->getNumPageParaInfo ();
		else	// if (m_type == CharType)
			formatInfoPageNum = m_header->getNumPageCharInfo ();


	#ifdef DEBUG_FORMATINFO
		m_device->debug ("numpages format info=", formatInfoPageNum);
	#endif

		// you have to have information pages that cover the _entire_ document (if it's not empty that is)
		if (m_header->getNumCharBytes () && formatInfoPageNum == 0)
		{
			if (m_type == ParaType)
			{
				ErrorAndQuit (Error::InvalidFormat, "no paragraph formatting information page\n");
			}
			else	// if (m_type == CharType)
			{
				ErrorAndQuit (Error::InvalidFormat, "no character formatting information page\n");
			}
		}

		// seek to start of info pages
		if (!m_device->seek (((m_type == ParaType) ?
										m_header->getPageParaInfo () : m_header->getPageCharInfo ()) * 128, SEEK_SET))
			return false;

		//
		// read in every info page
		// (this eats up all your memory...)
		//
		// The reason this is done is because infoPages (formatting information) are required
		// in between reads of text and on most devices, continually seeking back and forth
		// between the text pages and information pages is inconvenient and inefficient to say
		// the least.
		//
		// Generally speaking there is more text than formatting information some it is probably
		// cheaper (memory-wise) to cache the formatting in memory, rather than the text.
		//
		// A few more good reasons for caching formatting information:
		//
		// * we don't actually expand the formatting pages into the full FormatPointers
		//   and FormatProperty's (until begin()/next() are called) so we save quite a bit of
		//   memory
		// * some filters need to know information like the number of objects in advance
		//   so an extra parse of the formatting information (already cached :)) is required
		//
		for (int i = 0; i < formatInfoPageNum; i++)
		{
			if (!m_formatInfoPageList.addToBack ())
				ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for an information page\n");

			FormatInfoPage &fip = *m_formatInfoPageList.begin (false);
			if (m_device->bad ()) return false;

			fip.setHeader (m_header);
			fip.setDevice (m_device);
			fip.setType (m_type);
			
			if (m_type == ParaType)
				fip.setMargins (m_leftMargin, m_rightMargin);
			else	// if (m_type == CharType)
				fip.setFontTable (m_fontTable);

			if (!fip.readFromDevice ())
				return false;
		}

		return true;
	}

	bool FormatInfo::writeToDevice (const void *defaultProperty)
	{
	CHECK_DEVICE;

	#ifdef DEBUG_FORMATINFO
		if (m_type == ParaType)
			m_device->debug ("\n<<<< libmswrite.cpp::FormatInfo::writeToDevice (ParaType) >>>>\n");
		else	// if (m_type == CharType)
			m_device->debug ("\n<<<< libmswrite.cpp::FormatInfo::writeToDevice (CharType) >>>>\n");
	#endif

		// set page number of formatting info in header
		if (m_type == ParaType)
			m_header->setPageParaInfo (m_device->tellInternal () / 128);
		else	// if (m_type == CharType)
		{
			// ms programmers were so space conservative that they didn't
			// store charInfo page
			//m_header->setPageCharInfo (m_device->tellInternal () / 128);
		}

		//
		// No formatting table?
		//
		// Mimick what Write does and make one.
		// It seems that only a fontTable is mandatory but this is conveniently
		// updated when adding to a character formatting page.
		//
		if (!m_formatInfoPageList.getNumElements ())
		{
		#ifdef DEBUG_FORMATINFO
			m_device->debug ("\tno formatting information pages, creating one\n");
		#endif
		
			// --- but we should only get in here if numCharBytes = 0 ---
			
			if (m_header->getNumCharBytes ())
			{
				if (m_type == ParaType)
					m_device->error (Error::Warn, "data but no paragraph formatting info\n");
				else	// if (m_type == CharType)
					m_device->error (Error::Warn, "data but no character formatting info\n");
			}
	
			long currentOffset = m_device->tellInternal ();
				if (!m_device->seekInternal (128 + m_header->getNumCharBytes (), SEEK_SET)) return false;
				if (!add (defaultProperty, true/* force */)) return false;
			if (!m_device->seekInternal (currentOffset, SEEK_SET)) return false;
		}

		List <FormatInfoPage>::Iterator it;
		for (it = m_formatInfoPageList.begin (); it != m_formatInfoPageList.end (); ++it)
		{
			FormatInfoPage &fip = *it;

			// OPT: should already have done in add but we have to handle the impexp case
			fip.setHeader (m_header);
			fip.setDevice (m_device);
			fip.setType (m_type);
			
			if (m_type == ParaType)
				fip.setMargins (m_leftMargin, m_rightMargin);
			else	// if (m_type == CharType)
				fip.setFontTable (m_fontTable);

			if (!fip.writeToDevice ())
				return false;
		}

		return true;
	}

	void *FormatInfo::begin (void)
	{
		m_nextChar = 0;

		m_formatInfoPageIterator = m_formatInfoPageList.begin ();

		if (m_formatInfoPageIterator == m_formatInfoPageList.end ())
			return NULL;

		void *ret = (*m_formatInfoPageIterator).begin ();

		if (ret)
		{
			if (m_type == ParaType)
				m_nextChar = ((FormatParaProperty *) ret)->getAfterEndCharByte ();
			else	// if (m_type == CharType)
				m_nextChar = ((FormatCharProperty *) ret)->getAfterEndCharByte ();
		}

		return ret;
	}

	void *FormatInfo::next (void)
	{
	#ifdef CHECK_INTERNAL
		if (!m_device)
		{
			CHECK_DEVICE_ERROR;
			return NULL;
		}
	#endif

		void *ret = NULL;
		if ((*m_formatInfoPageIterator).end ())
		{
			m_formatInfoPageIterator++;

			// out of pages?
			if (m_formatInfoPageIterator == m_formatInfoPageList.end ())
				return NULL;

			if ((*m_formatInfoPageIterator).getFirstCharByte () != m_nextChar)
				m_device->error (Error::Warn, "FormatInfoPage::firstCharByte does not flow on from nextChar\n");

			ret = (*m_formatInfoPageIterator).begin ();
		}

		if (!ret)
			ret = (*m_formatInfoPageIterator).next ();

		if (ret)
		{
			if (m_type == ParaType)
				m_nextChar = ((FormatParaProperty *) ret)->getAfterEndCharByte ();
			else	// if (m_type == CharType)
				m_nextChar = ((FormatCharProperty *) ret)->getAfterEndCharByte ();
		}

		return ret;
	}

	bool FormatInfo::end (void) /*const*/
	{
		return m_formatInfoPageIterator == m_formatInfoPageList.end ();
	}

	bool FormatInfo::add (const void *property, const bool force)
	{
	CHECK_DEVICE;

	#ifdef DEBUG_FORMATINFO
		m_device->debug (">>>> FormatInfo::add <<<<\n");
	#endif
	
		DWord currentChar = m_device->tellInternal () - 128;
		
		// so that export filter writers can be lazy...
		if (m_nextChar == currentChar && !force)
		{
		#ifdef DEBUG_FORMATINFO
			m_device->debug ("\tEmpty FormatProperty, ignoring\n");
		#endif
			return true;
		}

		bool needToAllocate = false;

		if (m_formatInfoPageList.getNumElements ())
		{
			FormatInfoPage &fip = *m_formatInfoPageList.begin (false);
			if (!fip.add (property))
			{
				// a real error
				if (m_device->bad ())
					return false;

				needToAllocate = true;
			}
		}
		else
			needToAllocate = true;

		if (needToAllocate)
		{
			#ifdef DEBUG_FORMATINFO
				m_device->debug ("\tneedToAllocate=yes, FormatInfoPage::firstCharByte=", m_nextChar);
			#endif
				
			if (!m_formatInfoPageList.addToBack ())
				ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for new formatInfoPage\n");
			
			FormatInfoPage &fip = *m_formatInfoPageList.begin (false);
			fip.setDevice (m_device);
			fip.setFirstCharByte (m_nextChar);
			fip.setType (m_type);
			
			if (m_type == ParaType)
				fip.setMargins (m_leftMargin, m_rightMargin);
			else	// if (m_type == CharType)
			{
				assert (m_fontTable);
				fip.setFontTable (m_fontTable);
			}
			
			if (!fip.add (property))
				return false;
		}

		m_nextChar = currentChar;
		return true;
	}


	Generator::Generator ()
	{
	}

	Generator::~Generator ()
	{
	}

	bool Generator::processText (const Byte *string, bool willReachEndOfParagraph)
	{
		//
		// Look out for characters in the string and emit signals as appropriate:
		//
		//	1	pageNumber
		//	10	newLine
		//	13	carriageReturn
		//	12	pageBreak
		//	31	optionalHyphen
		//	?	text
		//

		const int outBufferMaxLen = 1024;
		Byte outBuffer [outBufferMaxLen];
		DWord outBufferLen = 0;

		for (; *string; string++)
		{
			// buffer full?
			if (outBufferLen >= outBufferMaxLen - 1)
			{
				// flush
				outBuffer [outBufferMaxLen - 1] = '\0';
				if (!writeText (outBuffer)) return false;
				outBufferLen = 0;
			}
		
			switch (*string)
			{
			// write text, generate signals for special characters, write more text...
			case 1:		// pageNumber anchor
			case 12:		// pageBreak (some silly document might have this in the middle of a paragraph!)
			case 13:
			case 10:		// newLine (some silly document _does_ have a newline in the middle of a paragraph!)
			case 31:    // optionalHyphen (aka "soft hyphen" an invisible hyphen, unless at end of line)
				// output text before this character
				if (outBufferLen)
				{
					outBuffer [outBufferLen] = 0;	// null terminate
					if (!writeText (outBuffer)) return false;
					outBufferLen = 0;
				}

				// generate signal
				switch (*string)
				{
				case 1:	if (!writePageNumber ()) return false;	break;
				case 12:	if (!writePageBreak ()) return false;	break;
				case 10:	if (!writeNewLine (willReachEndOfParagraph && string [1] == 0)) return false;	break;
				case 13:	if (!writeCarriageReturn ()) return false;	break;
				case 31: if (!writeOptionalHyphen ()) return false; break;
				}

				break;

			// normal text character
			default:
				outBuffer [outBufferLen++] = *string;
				break;
			}	// switch (*string)	{
		}	// for (; *string; string++)	{

		// flush
		if (outBufferLen)
		{
			outBuffer [outBufferLen] = 0;
			if (!writeText (outBuffer)) return false;
		}

		return true;
	}


	InternalParser::InternalParser () : m_header (NULL),
													m_sectionTable (NULL),
													m_pageLayout (NULL),
													m_pageTable (NULL),
													m_fontTable (NULL),
													m_paragraphInfo (NULL),
													m_characterInfo (NULL),
													m_image (NULL),
													m_ole (NULL)
	{
	}

	InternalParser::~InternalParser ()
	{
		delete m_ole;
		delete m_image;

		delete m_characterInfo;
		delete m_paragraphInfo;
		delete m_fontTable;
		delete m_pageTable;
		delete m_pageLayout;
		delete m_sectionTable;
		delete m_header;
	}

	// use this parser for "import" filters
	bool InternalParser::parse (void)
	{
		if (!m_device)
		{
			fprintf (stderr, "INTERNAL ERROR: InternalParser::parse() called without a device\n");
			return false;	// cannot use ErrorAndQuit() because that calls m_device->error()
		}

		if (!m_generator)
			ErrorAndQuit (Error::InternalError, "generator not passed to parser\n");

		//
		// allocate memory
		//

		m_header = new Header;
		if (!m_header)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for header\n");

		m_sectionTable = new SectionTable;
		if (!m_sectionTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for sectionTable\n");

		m_pageLayout = new PageLayout;
		if (!m_pageLayout)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for pageLayout\n");

		m_pageTable = new PageTable;
		if (!m_pageTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for pageTable\n");

		m_fontTable = new FontTable;
		if (!m_fontTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for fontTable\n");

		m_paragraphInfo = new FormatInfo;
		if (!m_paragraphInfo)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for paragraphInfo\n");

		m_characterInfo = new FormatInfo;
		if (!m_characterInfo)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for charInfo\n");

		//
		// Read everything from .WRI file
		//

		m_header->setDevice (m_device);
		if (!m_header->readFromDevice ()) return false;
		DWord numCharBytes = m_header->getNumCharBytes ();

		m_sectionTable->setHeader (m_header);
		m_sectionTable->setDevice (m_device);
		if (!m_sectionTable->readFromDevice ())
			return false;

		m_pageLayout->setHeader (m_header);
		m_pageLayout->setDevice (m_device);
		if (!m_pageLayout->readFromDevice ())
			return false;

		m_pageTable->setPageNumberStart (m_pageLayout->getPageNumberStart ());
		m_pageTable->setHeader (m_header);
		m_pageTable->setDevice (m_device);
		if (!m_pageTable->readFromDevice ())
			return false;

		m_fontTable->setHeader (m_header);
		m_fontTable->setDevice (m_device);
		if (!m_fontTable->readFromDevice ())
			return false;

		m_paragraphInfo->setHeader (m_header);
		m_paragraphInfo->setDevice (m_device);
		m_paragraphInfo->setType (ParaType);
		m_paragraphInfo->setMargins (m_pageLayout->getLeftMargin (), m_pageLayout->getRightMargin ());
		if (!m_paragraphInfo->readFromDevice ())
			return false;

		m_characterInfo->setHeader (m_header);
		m_characterInfo->setDevice (m_device);
		m_characterInfo->setType (CharType);
		m_characterInfo->setFontTable (m_fontTable);
		if (!m_characterInfo->readFromDevice ())
			return false;

#if 0
		DocumentInfo documentInfo;
		FormatParaProperty *paraProperty = (FormatParaProperty *) m_paragraphInfo->begin ();
		int numObjects = 0;
		while (paraProperty)
		{
			if (paraProperty->getIsObject ())
				numObjects++;
			if (paraProperty->getIsHeader ())
			{
				documentInfo.setHasHeader (true);
				if (paraProperty->getIsOnFirstPage ())
					documentInfo.setHasHeaderOnFirstPage (true);
			}
			if (paraProperty->getIsFooter ())
			{
				documentInfo.setHasFooter (true);
				if (paraProperty->getIsOnFirstPage ())
					documentInfo.setHasFooterOnFirstPage (true);
			}
			paraProperty = (FormatParaProperty *) m_paragraphInfo->next ();
		}
		documentInfo.setNumObjects (numObjects);
#endif

		// Get Ready!
		//

		enum Section { InNothing, InBody, InHeader, InFooter } inWhat = InNothing;

		// must call writeBody*() even if document doesn't have one
		bool wroteBody = false;

		PagePointer *pp = m_pageTable->begin ();
		if (m_device->bad ()) return false;

		//
		// Signal callbacks
		//
		#ifdef DEBUG_INTERNALPARSER
			m_device->debug ("@@@ InternalParser: start of document write\n");
		#endif

		if (!m_generator->writeDocumentBegin (m_header->getMagic (), m_pageLayout)) return false;
		m_generator->sigProgress (0);

		// start of text
		if (!m_device->seekInternal (1 * 128, SEEK_SET))
			return false;

		FormatParaProperty *paraProp = (FormatParaProperty *) m_paragraphInfo->begin ();
		if (m_device->bad ()) return false;
		FormatCharProperty *charProp = (FormatCharProperty *) m_characterInfo->begin ();
		if (m_device->bad ()) return false;
		DWord paraStartByte = 0;
		
		if (numCharBytes) while (paraProp)	// loop if not empty document
		{
		#ifdef DEBUG_INTERNALPARSER
			m_device->debug ("@@@ InternalParser: Start of loop - section write\n");
		#endif
			//
			// Section work
			//

			enum Section inWhatNext = InNothing;
			if (paraProp->getIsFooter ())
				inWhatNext = InFooter;
			else if (paraProp->getIsHeader ())
				inWhatNext = InHeader;
			else
				inWhatNext = InBody;

			// beginning of a new section?
			if (inWhatNext != inWhat)
			{
				// end last thing we were in
				switch (inWhat)
				{
				case InFooter:	if (!m_generator->writeFooterEnd ()) return false; else break;
				case InHeader:	if (!m_generator->writeHeaderEnd ()) return false; else break;
				case InBody:	if (!m_generator->writeBodyEnd ()) return false; else break;
				default:	break;	// keep compiler happy
				}

				// start next section
				switch (inWhat = inWhatNext)
				{
				case InFooter:	if (!m_generator->writeFooterBegin ()) return false; else break;
				case InHeader:	if (!m_generator->writeHeaderBegin ()) return false; else break;
				case InBody:	if (!m_generator->writeBodyBegin ()) return false;
					// if there's not pageTable, manually signal start of page for the first and last time
					if (!pp)
						if (!m_generator->writePageNew ())
							return false;

					wroteBody = true;
				default:	break;	// keep compiler happy
				}
			}


			//
			// start paragraph
			//

			bool paraIsText = paraProp->getIsText ();
			int objectType = ObjectType::NotObject;

			DWord paraEndByte, paraAfterEndByte;
			paraAfterEndByte = paraProp->getAfterEndCharByte ();
			paraEndByte = paraAfterEndByte - 1;

			if (paraIsText)
			{
			#ifdef DEBUG_INTERNALPARSER
				m_device->debug ("@@@ InternalParser: Start of paragraph write\n");
			#endif

				// signal paragraph
				if (!m_generator->writeParaInfoBegin (paraProp, NULL, NULL)) return false;
			}
			else
			{
				//
				// Determine whether the object is OLE or not
				// Yes, I know this isn't entirely clean but
				// name a cleaner and more efficient way of doing this...
				//

				Byte data [2];
				Word mappingMode;

				if (!m_device->readInternal (data, 2)) return false;
				ReadWord (mappingMode, data);
				if (!m_device->seekInternal (-2, SEEK_CUR)) return false;	// ungetc()x2

				switch (mappingMode)
				{
				case 0xE4:
					objectType = ObjectType::OLE;

					m_ole = new OLE;
					if (!m_ole)
						ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for OLE object\n");

					m_ole->setDevice (m_device);
					if (!m_ole->readFromDevice ())
						return false;

					if (!m_generator->writeParaInfoBegin (paraProp, m_ole, NULL)) return false;
					break;
				case 0xE3:	// monochrome bitmap?
					objectType = ObjectType::BMP;

					m_image = new Image;
					if (!m_image)
						ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for BMP image object\n");

					m_image->setDevice (m_device);
					if (!m_image->readFromDevice ())
						return false;

					if (!m_generator->writeParaInfoBegin (paraProp, NULL, m_image)) return false;
					break;
				default:
					objectType = ObjectType::WMF;

					m_image = new Image;
					if (!m_image)
						ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for WMF image object\n");

					m_image->setDevice (m_device);
					if (!m_image->readFromDevice ())
						return false;

					if (!m_generator->writeParaInfoBegin (paraProp, NULL, m_image)) return false;
					break;
				}

				// image: BMP/WMF
				if (objectType != ObjectType::OLE)
				{
					if (m_image->getNumHeaderBytes () + m_image->getNumDataBytes ()
							!= paraAfterEndByte - paraStartByte)
					{
						m_device->error (Error::Warn, "imageHeader: numHeaderBytes + numDataBytes != paragraph length\n");

						// we had better seek to where the paragraphs expect us to be to avoid trouble
						if (!m_device->seekInternal (paraAfterEndByte + 128, SEEK_SET)) return false;
					}
				}
			}

		#ifdef DEBUG_INTERNALPARSER
			m_device->debug ("@@@ InternalParser: Start of text write\n");
		#endif

			DWord uptoByte = paraStartByte;

			// loop until we hit end of paragraph (getting one CharProperty on every iteration)
			while (uptoByte < paraAfterEndByte)
			{
				if (charProp)
				{
					if (uptoByte >= charProp->getAfterEndCharByte ())
					{
						charProp = (FormatCharProperty *) m_characterInfo->next ();
						if (m_device->bad ()) return false;
					}

				#ifdef DEBUG_INTERNALPARSER
					m_device->debug ("@@@ InternalParser: character write\n");
				#endif

					if (!m_generator->writeCharInfoBegin (charProp)) return false;
				}

				// ultimately aim for end of CharProperty block; if that's not possible, aim for end of paragraph
				DWord aimUltimateByte = charProp->getEndCharByte () > paraEndByte ? paraEndByte : charProp->getEndCharByte ();

				while (uptoByte <= aimUltimateByte)
				{
					// flag to tell us to generate pageNewWrite/pageTable signal, after writing some normal text
					bool pageTableAck = false;

					// short-term goal (before end of CharProperty, ParaProperty or page)
					DWord aimByte = aimUltimateByte;

					// we want to efficiently send pageNewWrite signals which might be sandwhiched inside
					// a CharProperty block (note: we do NOT end and then restart a CharProperty block because of a writePageNew())
					if (pp)
					{
						if (pp->getFirstCharByte () <= aimByte)
						{
							pageTableAck = true;
							if (pp->getFirstCharByte ())
								// - 1 is because we want the PageNew signal called before the character
								aimByte = pp->getFirstCharByte () - 1;
							else
								aimByte = 0xFFFFFFFF;	// 0 - 1 :)

						#ifdef DEBUG_INTERNALPARSER
							m_device->debug ("@@@ InternalParser: writePageNew pending\n");
						#endif
						}
					}

					// write text (using buffering)
					while (uptoByte <= aimByte && aimByte != 0xFFFFFFFF)
					{
						const DWord amountToRead = aimByte - uptoByte + 1 > 1023
															? 1023 : aimByte - uptoByte + 1;

						if (paraIsText)
						{
							Byte buffer [1024];

							if (!m_device->readInternal (buffer, amountToRead)) return false;

							buffer [amountToRead] = '\0';
							if (!m_generator->processText (buffer, uptoByte + amountToRead - 1 == paraEndByte)) return false;
						}

						uptoByte += amountToRead;
					}		// while (uptoByte <= aimByte && aimByte != 0xFFFFFFFF) {

					// generate pageNewWrite/pageTable signal, if requested
					if (pageTableAck)
					{
					#ifdef DEBUG_INTERNALPARSER
						m_device->debug ("@@@ InternalParser: writePageNew\n");
					#endif

						if (!m_generator->writePageNew (pp->getPageNumber ())) return false;

						pp = m_pageTable->next ();
						if (m_device->bad ()) return false;
					}
				}		// while (uptoByte <= aimUltimateByte) {


				#ifdef DEBUG_INTERNALPARSER
					m_device->debug ("@@@ InternalParser: character end write\n");
				#endif

				// end char info
				if (charProp)
					if (!m_generator->writeCharInfoEnd (charProp, uptoByte == paraAfterEndByte))
						return false;

			}		// while (uptoByte < paraAfterEndByte) {


			//
			// ouptut object
			//

			if (!paraIsText)
			{
				if (objectType == ObjectType::OLE)
				{
					if (!m_generator->writeBinary (m_ole->getExternalObject (), m_ole->getExternalObjectSize ()))
						return false;
				}
				else	// if (objectType == ObjectType::BMP || objectType == ObjectType::WMF)
				{
					if (!m_generator->writeBinary (m_image->getExternalImage (), m_image->getExternalImageSize ()))
						return false;
				}
			}

			//
			// end paragraph
			//

			if (paraIsText)
			{
				// end paragraph
				if (!m_generator->writeParaInfoEnd (paraProp, NULL)) return false;
			}
			else
			{
				switch (objectType)
				{
				case ObjectType::OLE:
					if (!m_generator->writeParaInfoEnd (paraProp, m_ole, NULL)) return false;
					delete m_ole;
					m_ole = NULL;
					break;
				case ObjectType::BMP:
					if (!m_generator->writeParaInfoEnd (paraProp, NULL, m_image)) return false;
					delete m_image;
					m_image = NULL;
					break;
				case ObjectType::WMF:
					if (!m_generator->writeParaInfoEnd (paraProp, NULL, m_image)) return false;
					delete m_image;
					m_image = NULL;
					break;
				}
			}

			paraStartByte = paraAfterEndByte;

			// numCharBytes != 0 because we checked it before we entered the loop
			m_generator->sigProgress (paraStartByte * 100 / numCharBytes);

			// get next paragraph properties
			paraProp = (FormatParaProperty *) m_paragraphInfo->next ();
			if (m_device->bad ()) return false;
		}

		// end last thing we were in
		switch (inWhat)
		{
		case InFooter:	if (!m_generator->writeFooterEnd ()) return false; else break;
		case InHeader:	if (!m_generator->writeHeaderEnd ()) return false; else break;
		case InBody:	if (!m_generator->writeBodyEnd ()) return false; else break;
		default:	break;	// keep compiler happy
		}

		// didn't output a body (usually due to a blank document)
		if (!wroteBody)
		{
		#ifdef DEBUG_INTERNALPARSER
			m_device->debug ("@@@ InternalParser: did not write body, writing one now\n");
		#endif
		
			if (!m_generator->writeBodyBegin ()) return false;
			if (!m_generator->writeBodyEnd ()) return false;
		}

		m_generator->sigProgress (100);
		if (!m_generator->writeDocumentEnd (m_header->getMagic (), m_pageLayout)) return false;

		return true;
	}


	InternalGenerator::InternalGenerator () : m_header (NULL),
															m_sectionTable (NULL),
															m_pageLayout (NULL),
															m_pageTable (NULL),
															m_fontTable (NULL),
															m_paragraphInfo (NULL),
															m_characterInfo (NULL),
															m_image (NULL),
															m_ole (NULL)
	{
	}

	InternalGenerator::~InternalGenerator ()
	{
		delete m_ole;
		delete m_image;

		delete m_characterInfo;
		delete m_paragraphInfo;
		delete m_fontTable;
		delete m_pageTable;
		delete m_pageLayout;
		delete m_sectionTable;
		delete m_header;
	}

	bool InternalGenerator::seekNextPage (void)
	{
		return m_device->seekInternal ((m_device->tellInternal () + 127) / 128 * 128, SEEK_SET);
	}

	bool InternalGenerator::writeDocumentBegin (const Word, const PageLayout *pageLayout)
	{
		if (!m_device)
		{
			fprintf (stderr, "INTERNAL ERROR: InternalGenerator::writeDocumentBegin() called without a device\n");
			return false;	// cannot use ErrorAndQuit() because that calls m_device->error()
		}

		m_header = new Header;
		if (!m_header)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for header\n");
		m_header->setDevice (m_device);

		m_pageLayout = new PageLayout;
		if (!m_pageLayout)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for pageLayout\n");
		m_pageLayout->setDevice (m_device);

		m_sectionTable = new SectionTable;
		if (!m_sectionTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for sectionTable\n");
		m_sectionTable->setDevice (m_device);

		m_pageTable = new PageTable;
		if (!m_pageTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for pageTable\n");
		m_pageTable->setDevice (m_device);

		m_fontTable = new FontTable;
		if (!m_fontTable)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for fontTable\n");
		m_fontTable->setDevice (m_device);

		m_paragraphInfo = new FormatInfo;
		if (!m_paragraphInfo)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for paragraphInfo\n");
		m_paragraphInfo->setType (ParaType);
		m_paragraphInfo->setDevice (m_device);

		m_characterInfo = new FormatInfo;
		if (!m_characterInfo)
			ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for characterInfo\n");
		m_characterInfo->setType (CharType);
		m_characterInfo->setDevice (m_device);
		
		*m_pageLayout = *pageLayout;
		
		// get ready to output text
		if (!m_device->seekInternal (1 * 128, SEEK_SET)) return false;

		return true;
	}

	bool InternalGenerator::writeDocumentEnd (const Word format, const PageLayout *)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writeDocumentEnd\n");
	#endif

		m_header->setNumCharBytes (m_device->tellInternal () - 128);

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("before charinfo seek next page: ", m_device->tellInternal ());
	#endif
		if (!seekNextPage ()) return false;	// from text pages
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write characterInfo; page=", m_device->tellInternal () / 128);
	#endif
		FormatCharProperty defaultCharProperty;
		defaultCharProperty.setFontTable (m_fontTable);	
			Font defaultFont ((const Byte *) "Arial");	// better than "unknown", I guess
		defaultCharProperty.setFont (&defaultFont);
			
		// write characterInfo pages
		m_characterInfo->setDevice (m_device);
		m_characterInfo->setHeader (m_header);
		m_characterInfo->setFontTable (m_fontTable);
		if (!m_characterInfo->writeToDevice (&defaultCharProperty)) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("before parainfo seek next page: ", m_device->tellInternal ());
	#endif
		if (!seekNextPage ()) return false;
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write paragraphInfo; page=", m_device->tellInternal () / 128);
	#endif
		FormatParaProperty defaultParaProperty;	
		defaultParaProperty.setMargins (m_pageLayout->getLeftMargin (), m_pageLayout->getRightMargin ());
	
		// write paragraphInfo pages
		m_paragraphInfo->setDevice (m_device);
		m_paragraphInfo->setHeader (m_header);
		m_paragraphInfo->setMargins (m_pageLayout->getLeftMargin (), m_pageLayout->getRightMargin ());
		if (!m_paragraphInfo->writeToDevice (&defaultParaProperty)) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write footnoteTable\n");
	#endif

		// there's "no such thing (tm)" as a FootnoteTable
		m_header->setPageFootnoteTable ((m_device->tellInternal () + 127) / 128);

		if (!seekNextPage ()) return false;
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write pageLayout; page=", m_device->tellInternal () / 128);
	#endif
		m_pageLayout->setDevice (m_device);
		m_pageLayout->setHeader (m_header);
		if (!m_pageLayout->writeToDevice ()) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write sectionTable\n");
	#endif
		if (!seekNextPage ()) return false;
		m_sectionTable->setDevice (m_device);
		m_sectionTable->setHeader (m_header);
		if (!m_sectionTable->writeToDevice (m_pageLayout->getIsModified ())) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write pageTable\n");
	#endif
		if (!seekNextPage ()) return false;
		m_pageTable->setDevice (m_device);
		m_pageTable->setHeader (m_header);
		m_pageTable->setPageNumberStart (m_pageLayout->getPageNumberStart ());
		if (!m_pageTable->writeToDevice ()) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write fontTable\n");
	#endif
		if (!seekNextPage ()) return false;
		m_fontTable->setDevice (m_device);
		m_fontTable->setHeader (m_header);
		if (!m_fontTable->writeToDevice ()) return false;

	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: Write header\n");
	#endif
		// write header
		m_header->setFormat (format);
		m_header->setNumPages ((m_device->tellInternal () + 127) / 128);
		m_header->setDevice (m_device);
		if (!m_device->seekInternal (0 * 128, SEEK_SET)) return false;
		if (!m_header->writeToDevice ()) return false;

		// pad up to 128 (it seems that the ms programmers really did expect 128-byte pages)
		// BTW, if you look in a Write file, you can normally see some garbage after the
		// fontTable that appears to be part of an earlier part of the document
		// (or even some _other_ document!) suggesting that ms really did reuse their memory
		// and that we shouldn't be all that concerned with "unknown", "reserved" and "zero"
		// fields
		if (!m_device->seekInternal (m_header->getNumPages () * 128, SEEK_SET)) return false;

		return true;
	}

	bool InternalGenerator::writeParaInfoBegin (const FormatParaProperty * /*paraProperty*/,
																const OLE *ole,
																const Image *image)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writeParaInfoBegin\n");
	#endif

		if (ole)
		{
			m_ole = new OLE;
			if (!m_ole)
				ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for OLE\n");
			*m_ole = *ole;

			m_ole->setDevice (m_device);
			m_ole->setExternalObjectSize (ole->getExternalObjectSize ());
		}

		if (image)
		{
			m_image = new Image;
			if (!m_image)
				ErrorAndQuit (Error::OutOfMemory, "could not allocate memory for image\n");
			*m_image = *image;

			m_image->setDevice (m_device);
			m_image->setExternalImageSize (image->getExternalImageSize ());
		}

		return true;
	}

	bool InternalGenerator::writeParaInfoEnd (const FormatParaProperty *paraProperty,
															const OLE */*ole*/,
															const Image */*image*/)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writeParaInfoEnd\n");
	#endif

		if (m_ole)
		{
			if (!m_ole->writeToDevice ())
				return false;

			delete m_ole;
			m_ole = NULL;
		}
		else if (m_image)
		{
			if (!m_image->writeToDevice ())
				return false;

			delete m_image;
			m_image = NULL;
		}

		m_paragraphInfo->setMargins (m_pageLayout->getLeftMargin (), m_pageLayout->getRightMargin ());
		return m_paragraphInfo->add (paraProperty, false/* don't force */);
	}

	bool InternalGenerator::writeCharInfoBegin (const FormatCharProperty * /*charProperty*/)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writeCharInfoBegin\n");
	#endif
		
		return true;
	}

	bool InternalGenerator::writeCharInfoEnd (const FormatCharProperty *charProperty,
															const bool)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writeCharInfoEnd\n");
	#endif

		m_characterInfo->setFontTable (m_fontTable);
		return m_characterInfo->add (charProperty, false/* don't force */);
	}

	bool InternalGenerator::writeBinary (const Byte *buffer, const DWord length)
	{
		if (m_ole)
		{
			if (!m_ole->setExternalObject (buffer, length))
				return false;
		}
		else if (m_image)
		{
			if (!m_image->setExternalImage (buffer, length))
				return false;
		}
		else
			ErrorAndQuit (Error::InternalError, "attempt to write unknown type of binary data\n");

		return true;
	}

	bool InternalGenerator::writeText (const Byte *string)
	{
	#ifdef DEBUG_INTERNALGENERATOR
//		m_device->debug ("!!!! InternalGenerator: writeText> ", (const char *) string);
	#endif

		DWord length = DWord (strlen ((const char *) string));

		if (!m_device->writeInternal (string, length)) return false;

		return true;
	}

	bool InternalGenerator::writePageNew (const int pageNumberClaimed)
	{
	#ifdef DEBUG_INTERNALGENERATOR
		m_device->debug ("!!!! InternalGenerator: writePageNew() with pageNo ",
								pageNumberClaimed);
	#endif

		// is this a forced new page (as in, the signal was only generated because I put it in the spec?)
		if (pageNumberClaimed == 0)
			return true;	// no real pageTable

		PagePointer pp;
		pp.setPageNumber (pageNumberClaimed);
		pp.setFirstCharByte (m_device->tellInternal () - 128);

		return m_pageTable->add (&pp);
	}

}	// namespace MSWrite	{

// end of libmswrite.cpp