summaryrefslogtreecommitdiffstats
path: root/filters/kword/abiword/abiwordimport.cc
blob: bd6ea1e38839b9f8e47f83f6d114a29704aae18c (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
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
/* This file is part of the KDE project
   Copyright 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   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 for more details.

   You should have received a copy of the GNU Library General Public License
   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.
*/

#include <config.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <tqmap.h>
#include <tqbuffer.h>
#include <tqpicture.h>
#include <tqxml.h>
#include <tqdom.h>
#include <tqdatetime.h>

#include <kdebug.h>
#include <kmdcodec.h>
#include <kfilterdev.h>
#include <kgenericfactory.h>
#include <tdemessagebox.h>

#include <KoPageLayout.h>
#include <KoStore.h>
#include <KoFilterChain.h>

#include "ImportHelpers.h"
#include "ImportFormatting.h"
#include "ImportStyle.h"
#include "ImportField.h"

#include "abiwordimport.h"

class ABIWORDImportFactory : KGenericFactory<ABIWORDImport, KoFilter>
{
public:
    ABIWORDImportFactory(void) : KGenericFactory<ABIWORDImport, KoFilter> ("kwordabiwordimport")
    {}
protected:
    virtual void setupTranslations( void )
    {
        TDEGlobal::locale()->insertCatalogue( "kofficefilters" );
    }
};

K_EXPORT_COMPONENT_FACTORY( libabiwordimport, ABIWORDImportFactory() )

// *Note for the reader of this code*
// Tags in lower case (e.g. <c>) are AbiWord's ones.
// Tags in upper case (e.g. <TEXT>) are KWord's ones.

// enum StackItemElementType is now in the file ImportFormatting.h

class StructureParser : public TQXmlDefaultHandler
{
public:
    StructureParser(KoFilterChain* chain)
        :  m_chain(chain), m_pictureNumber(0), m_pictureFrameNumber(0), m_tableGroupNumber(0),
        m_timepoint(TQDateTime::currentDateTime(Qt::UTC)), m_fatalerror(false)
    {
        createDocument();
        structureStack.setAutoDelete(true);
        StackItem *stackItem=new(StackItem);
        stackItem->elementType=ElementTypeBottom;
        stackItem->m_frameset=mainFramesetElement; // The default frame set.
        stackItem->stackElementText=mainFramesetElement; // This is more for DEBUG
        structureStack.push(stackItem); //Security item (not to empty the stack)
    }
    virtual ~StructureParser()
    {
        structureStack.clear();
    }
public:
    virtual bool startDocument(void);
    virtual bool endDocument(void);
    virtual bool startElement( const TQString&, const TQString&, const TQString& name, const TQXmlAttributes& attributes);
    virtual bool endElement( const TQString&, const TQString& , const TQString& qName);
    virtual bool characters ( const TQString & ch );
    virtual bool warning(const TQXmlParseException& exception);
    virtual bool error(const TQXmlParseException& exception);
    virtual bool fatalError(const TQXmlParseException& exception);
public:
    inline TQDomDocument getDocInfo(void) const { return m_info; }
    inline TQDomDocument getDocument(void) const { return mainDocument; }
    inline bool wasFatalError(void) const { return m_fatalerror; }
protected:
    bool clearStackUntilParagraph(StackItemStack& auxilaryStack);
    bool complexForcedPageBreak(StackItem* stackItem);
private:
    // The methods that would need too much parameters are private instead of being static outside the class
    bool StartElementC(StackItem* stackItem, StackItem* stackCurrent,
        const TQXmlAttributes& attributes);
    bool StartElementA(StackItem* stackItem, StackItem* stackCurrent,
        const TQXmlAttributes& attributes);
    bool StartElementImage(StackItem* stackItem, StackItem* stackCurrent,
        const TQXmlAttributes& attributes);
    bool EndElementD (StackItem* stackItem);
    bool EndElementM (StackItem* stackItem);
    bool StartElementSection(StackItem* stackItem, StackItem* stackCurrent,
        const TQXmlAttributes& attributes);
    bool StartElementFoot(StackItem* stackItem, StackItem* stackCurrent,
        const TQXmlAttributes& attributes);
    bool StartElementTable(StackItem* stackItem, StackItem* stackCurrent, const TQXmlAttributes& attributes);
    bool StartElementCell(StackItem* stackItem, StackItem* stackCurrent,const TQXmlAttributes& attributes);
private:
    void createDocument(void);
    void createDocInfo(void);
    TQString indent; //DEBUG
    StackItemStack structureStack;
    TQDomDocument mainDocument;
    TQDomDocument m_info;
    TQDomElement framesetsPluralElement; // <FRAMESETS>
    TQDomElement mainFramesetElement;    // The main <FRAMESET> where the body text will be under.
    TQDomElement m_picturesElement;      // <PICTURES>
    TQDomElement m_paperElement;         // <PAPER>
    TQDomElement m_paperBordersElement;  // <PAPERBORDER>
    TQDomElement m_ignoreWordsElement;    // <SPELLCHECKIGNORELIST>
    StyleDataMap styleDataMap;
    KoFilterChain* m_chain;
    uint m_pictureNumber;                   // unique: increment *before* use
    uint m_pictureFrameNumber;              // unique: increment *before* use
    uint m_tableGroupNumber;                // unique: increment *before* use
    TQMap<TQString,TQString> m_metadataMap;    // Map for <m> elements
    TQDateTime m_timepoint;              // Date/time (for pictures)
    bool m_fatalerror;                  // Did a XML parsing fatal error happened?
};

// Element <c>

bool StructureParser::StartElementC(StackItem* stackItem, StackItem* stackCurrent, const TQXmlAttributes& attributes)
{
    // <c> elements can be nested in <p> elements, in <a> elements or in other <c> elements
    // AbiWord does not nest <c> elements in other <c> elements, but explicitly allows external programs to do it!

    // <p> or <c> (not child of <a>)
    if ((stackCurrent->elementType==ElementTypeParagraph)||(stackCurrent->elementType==ElementTypeContent))
    {
        // Contents can have styles, however KWord cannot have character style.
        // Therefore we use the style if it exist, but we do not create it if not.
        TQString strStyleProps;
        TQString strStyleName=attributes.value("style").stripWhiteSpace();
        if (!strStyleName.isEmpty())
        {
            StyleDataMap::Iterator it=styleDataMap.find(strStyleName);
            if (it!=styleDataMap.end())
            {
                strStyleProps=it.data().m_props;
            }
        }

        AbiPropsMap abiPropsMap;
        PopulateProperties(stackItem,strStyleProps,attributes,abiPropsMap,true);

        stackItem->elementType=ElementTypeContent;
        stackItem->stackElementParagraph=stackCurrent->stackElementParagraph;   // <PARAGRAPH>
        stackItem->stackElementText=stackCurrent->stackElementText;   // <TEXT>
        stackItem->stackElementFormatsPlural=stackCurrent->stackElementFormatsPlural; // <FORMATS>
        stackItem->pos=stackCurrent->pos; //Propagate the position
    }
    // <a> or <c> when child of <a>
    else if ((stackCurrent->elementType==ElementTypeAnchor)||(stackCurrent->elementType==ElementTypeAnchorContent))
    {
        stackItem->elementType=ElementTypeAnchorContent;
    }
    else
    {//we are not nested correctly, so consider it a parse error!
        kdError(30506) << "parse error <c> tag nested neither in <p> nor in <c> nor in <a> but in "
            << stackCurrent->itemName << endl;
        return false;
    }
    return true;
}

bool charactersElementC (StackItem* stackItem, TQDomDocument& mainDocument, const TQString & ch)
{
    if  (stackItem->elementType==ElementTypeContent)
    {   // Normal <c>
        TQDomElement elementText=stackItem->stackElementText;
        TQDomElement elementFormatsPlural=stackItem->stackElementFormatsPlural;
        elementText.appendChild(mainDocument.createTextNode(ch));

        TQDomElement formatElementOut=mainDocument.createElement("FORMAT");
        formatElementOut.setAttribute("id",1); // Normal text!
        formatElementOut.setAttribute("pos",stackItem->pos); // Start position
        formatElementOut.setAttribute("len",ch.length()); // Start position
        elementFormatsPlural.appendChild(formatElementOut); //Append to <FORMATS>
        stackItem->pos+=ch.length(); // Adapt new starting position

        AddFormat(formatElementOut, stackItem, mainDocument);
    }
    else if (stackItem->elementType==ElementTypeAnchorContent)
    {
        // Add characters to the link name
        stackItem->strTemp2+=ch;
        // TODO: how can we care about the text format?
    }
    else
    {
        kdError(30506) << "Internal error (in charactersElementC)" << endl;
    }

	return true;
}

bool EndElementC (StackItem* stackItem, StackItem* stackCurrent)
{
    if (stackItem->elementType==ElementTypeContent)
    {
        stackItem->stackElementText.normalize();
        stackCurrent->pos=stackItem->pos; //Propagate the position back to the parent element
    }
    else if (stackItem->elementType==ElementTypeAnchorContent)
    {
        stackCurrent->strTemp2+=stackItem->strTemp2; //Propagate the link name back to the parent element
    }
    else
    {
        kdError(30506) << "Wrong element type!! Aborting! (</c> in StructureParser::endElement)" << endl;
        return false;
    }
    return true;
}

// Element <a>
bool StructureParser::StartElementA(StackItem* stackItem, StackItem* stackCurrent, const TQXmlAttributes& attributes)
{
    // <a> elements can be nested in <p> elements
    if (stackCurrent->elementType==ElementTypeParagraph)
    {

        //AbiPropsMap abiPropsMap;
        //PopulateProperties(stackItem,TQString(),attributes,abiPropsMap,true);

        stackItem->elementType=ElementTypeAnchor;
        stackItem->stackElementParagraph=stackCurrent->stackElementParagraph;   // <PARAGRAPH>
        stackItem->stackElementText=stackCurrent->stackElementText;   // <TEXT>
        stackItem->stackElementFormatsPlural=stackCurrent->stackElementFormatsPlural; // <FORMATS>
        stackItem->pos=stackCurrent->pos; //Propagate the position
        stackItem->strTemp1=attributes.value("xlink:href").stripWhiteSpace(); // link reference
        stackItem->strTemp2=TQString(); // link name

        // We must be careful: AbiWord permits anchors to bookmarks.
        //  However, KWord does not know what a bookmark is.
        if (stackItem->strTemp1[0]=='#')
        {
            kdWarning(30506) << "Anchor <a> to bookmark: " << stackItem->strTemp1 << endl
                << " Processing <a> like <c>" << endl;
            // We have a reference to a bookmark. Therefore treat it as a normal content <c>
            return StartElementC(stackItem, stackCurrent, attributes);
        }
    }
    else
    {//we are not nested correctly, so consider it a parse error!
        kdError(30506) << "parse error <a> tag not a child of <p> but of "
            << stackCurrent->itemName << endl;
        return false;
    }
    return true;
}

static bool charactersElementA (StackItem* stackItem, const TQString & ch)
{
    // Add characters to the link name
    stackItem->strTemp2+=ch;
	return true;
}

static bool EndElementA (StackItem* stackItem, StackItem* stackCurrent, TQDomDocument& mainDocument)
{
    if (!stackItem->elementType==ElementTypeAnchor)
    {
        kdError(30506) << "Wrong element type!! Aborting! (</a> in StructureParser::endElement)" << endl;
        return false;
    }

    TQDomElement elementText=stackItem->stackElementText;
    elementText.appendChild(mainDocument.createTextNode("#"));

    TQDomElement formatElement=mainDocument.createElement("FORMAT");
    formatElement.setAttribute("id",4); // Variable
    formatElement.setAttribute("pos",stackItem->pos); // Start position
    formatElement.setAttribute("len",1); // Start position

    TQDomElement variableElement=mainDocument.createElement("VARIABLE");
    formatElement.appendChild(variableElement);

    TQDomElement typeElement=mainDocument.createElement("TYPE");
    typeElement.setAttribute("key","STRING");
    typeElement.setAttribute("type",9); // link
    typeElement.setAttribute("text",stackItem->strTemp2);
    variableElement.appendChild(typeElement); //Append to <VARIABLE>

    TQDomElement linkElement=mainDocument.createElement("LINK");
    linkElement.setAttribute("hrefName",stackItem->strTemp1);
    linkElement.setAttribute("linkName",stackItem->strTemp2);
    variableElement.appendChild(linkElement); //Append to <VARIABLE>

    // Now work on stackCurrent
    stackCurrent->stackElementFormatsPlural.appendChild(formatElement);
    stackCurrent->pos++; //Propagate the position back to the parent element

    return true;
}

// Element <p>

bool StartElementP(StackItem* stackItem, StackItem* stackCurrent,
    TQDomDocument& mainDocument,
    StyleDataMap& styleDataMap, const TQXmlAttributes& attributes)
{
    // We must prepare the style
    TQString strStyle=attributes.value("style");
    if (strStyle.isEmpty())
    {
        strStyle="Normal";
    }
    StyleDataMap::ConstIterator it=styleDataMap.useOrCreateStyle(strStyle);

    TQString strLevel=attributes.value("level");
    int level;
    if (strLevel.isEmpty())
    {
        // We have not "level" attribute, so we must use the style's level.
        level=it.data().m_level;
    }
    else
    {
        // We have a "level" attribute, so it overrides the style's level.
        level=strStyle.toInt();
    }

    TQDomElement elementText=stackCurrent->stackElementText;
    TQDomElement paragraphElementOut=mainDocument.createElement("PARAGRAPH");
    stackCurrent->m_frameset.appendChild(paragraphElementOut);

    TQDomElement textElementOut=mainDocument.createElement("TEXT");
    paragraphElementOut.appendChild(textElementOut);
    TQDomElement formatsPluralElementOut=mainDocument.createElement("FORMATS");
    paragraphElementOut.appendChild(formatsPluralElementOut);

    AbiPropsMap abiPropsMap;
    PopulateProperties(stackItem,it.data().m_props,attributes,abiPropsMap,false);

    stackItem->elementType=ElementTypeParagraph;
    stackItem->stackElementParagraph=paragraphElementOut; // <PARAGRAPH>
    stackItem->stackElementText=textElementOut; // <TEXT>
    stackItem->stackElementFormatsPlural=formatsPluralElementOut; // <FORMATS>
    stackItem->pos=0; // No text characters yet

    // Now we populate the layout
    TQDomElement layoutElement=mainDocument.createElement("LAYOUT");
    paragraphElementOut.appendChild(layoutElement);

    AddLayout(strStyle,layoutElement, stackItem, mainDocument, abiPropsMap, level, false);

    return true;
}

bool charactersElementP (StackItem* stackItem, TQDomDocument& mainDocument, const TQString & ch)
{
    TQDomElement elementText=stackItem->stackElementText;

    elementText.appendChild(mainDocument.createTextNode(ch));

    stackItem->pos+=ch.length(); // Adapt new starting position

    return true;
}

bool EndElementP (StackItem* stackItem)
{
    if (!stackItem->elementType==ElementTypeParagraph)
    {
        kdError(30506) << "Wrong element type!! Aborting! (in endElementP)" << endl;
        return false;
    }
    stackItem->stackElementText.normalize();
    return true;
}

static bool StartElementField(StackItem* stackItem, StackItem* stackCurrent,
    TQDomDocument& mainDocument, const TQXmlAttributes& attributes)
{
    // <field> element elements can be nested in <p>
    if (stackCurrent->elementType==ElementTypeParagraph)
    {
        TQString strType=attributes.value("type").stripWhiteSpace();
        kdDebug(30506)<<"<field> type:"<<strType<<endl;

        AbiPropsMap abiPropsMap;
        PopulateProperties(stackItem,TQString(),attributes,abiPropsMap,true);

        stackItem->elementType=ElementTypeEmpty;

        // We create a format element
        TQDomElement variableElement=mainDocument.createElement("VARIABLE");

        if (!ProcessField(mainDocument, variableElement, strType, attributes))
        {
            // The field type was not recognised,
            //   therefore write the field type in red as normal text
            kdWarning(30506) << "Unknown <field> type: " << strType << endl;
            TQDomElement formatElement=mainDocument.createElement("FORMAT");
            formatElement.setAttribute("id",1); // Variable
            formatElement.setAttribute("pos",stackItem->pos); // Start position
            formatElement.setAttribute("len",strType.length());

            formatElement.appendChild(variableElement);

            // Now work on stackCurrent
            stackCurrent->stackElementFormatsPlural.appendChild(formatElement);
            stackCurrent->stackElementText.appendChild(mainDocument.createTextNode(strType));
            stackCurrent->pos+=strType.length(); // Adjust position

            // Add formating (use stackItem)
            stackItem->fgColor.setRgb(255,0,0);
            AddFormat(formatElement, stackItem, mainDocument);
            return true;
        }

        // We create a format element
        TQDomElement formatElement=mainDocument.createElement("FORMAT");
        formatElement.setAttribute("id",4); // Variable
        formatElement.setAttribute("pos",stackItem->pos); // Start position
        formatElement.setAttribute("len",1);

        formatElement.appendChild(variableElement);

        // Now work on stackCurrent
        stackCurrent->stackElementFormatsPlural.appendChild(formatElement);
        stackCurrent->stackElementText.appendChild(mainDocument.createTextNode("#"));
        stackCurrent->pos++; // Adjust position

        // Add formating (use stackItem)
        AddFormat(formatElement, stackItem, mainDocument);

    }
    else
    {//we are not nested correctly, so consider it a parse error!
        kdError(30506) << "parse error <field> tag not nested in <p> but in "
            << stackCurrent->itemName << endl;
        return false;
    }
    return true;
}

// <s> (style)
static bool StartElementS(StackItem* stackItem, StackItem* /*stackCurrent*/,
    const TQXmlAttributes& attributes, StyleDataMap& styleDataMap)
{
    // We do not assume when we are called.
    // We also do not care if a style is defined multiple times.
    stackItem->elementType=ElementTypeEmpty;

    TQString strStyleName=attributes.value("name").stripWhiteSpace();

    if (strStyleName.isEmpty())
    {
        kdWarning(30506) << "Style has no name!" << endl;
    }
    else
    {
        TQString strLevel=attributes.value("level");
        int level;
        if (strLevel.isEmpty())
            level=-1; //TODO/FIXME: might be wrong if the style is based on another
        else
            level=strLevel.toInt();
        TQString strBasedOn=attributes.value("basedon").simplifyWhiteSpace();
        styleDataMap.defineNewStyleFromOld(strStyleName,strBasedOn,level,attributes.value("props"));
        kdDebug(30506) << " Style name: " << strStyleName << endl
            << " Based on: " << strBasedOn  << endl
            << " Level: " << level << endl
            << " Props: " << attributes.value("props") << endl;
    }

    return true;
}

// <image>
bool StructureParser::StartElementImage(StackItem* stackItem, StackItem* stackCurrent,
    const TQXmlAttributes& attributes)
{
    // <image> elements can be nested in <p> or <c> elements
    if ((stackCurrent->elementType!=ElementTypeParagraph) && (stackCurrent->elementType!=ElementTypeContent))
    {//we are not nested correctly, so consider it a parse error!
        kdError(30506) << "parse error <image> tag nested neither in <p> nor in <c> but in "
            << stackCurrent->itemName << endl;
        return false;
    }
    stackItem->elementType=ElementTypeEmpty;

    TQString strDataId=attributes.value("dataid").stripWhiteSpace();

    AbiPropsMap abiPropsMap;
    abiPropsMap.splitAndAddAbiProps(attributes.value("props"));

    double height=ValueWithLengthUnit(abiPropsMap["height"].getValue());
    double width =ValueWithLengthUnit(abiPropsMap["width" ].getValue());

    kdDebug(30506) << "Image: " << strDataId << " height: " << height << " width: " << width << endl;

    // TODO: image properties

    if (strDataId.isEmpty())
    {
        kdWarning(30506) << "Image has no data id!" << endl;
    }
    else
    {
        kdDebug(30506) << "Image: " << strDataId << endl;
    }

    TQString strPictureFrameName(i18n("Frameset name","Picture %1").arg(++m_pictureFrameNumber));

    // Create the frame set of the image

    TQDomElement framesetElement=mainDocument.createElement("FRAMESET");
    framesetElement.setAttribute("frameType",2);
    framesetElement.setAttribute("frameInfo",0);
    framesetElement.setAttribute("visible",1);
    framesetElement.setAttribute("name",strPictureFrameName);
    framesetsPluralElement.appendChild(framesetElement);

    TQDomElement frameElementOut=mainDocument.createElement("FRAME");
    frameElementOut.setAttribute("left",0);
    frameElementOut.setAttribute("top",0);
    frameElementOut.setAttribute("bottom",height);
    frameElementOut.setAttribute("right" ,width );
    frameElementOut.setAttribute("runaround",1);
    // TODO: a few attributes are missing
    framesetElement.appendChild(frameElementOut);

    TQDomElement element=mainDocument.createElement("PICTURE");
    element.setAttribute("keepAspectRatio","true");
    framesetElement.setAttribute("frameType",2); // Picture
    framesetElement.appendChild(element);

    TQDomElement key=mainDocument.createElement("KEY");
    key.setAttribute("filename",strDataId);
    key.setAttribute("year",m_timepoint.date().year());
    key.setAttribute("month",m_timepoint.date().month());
    key.setAttribute("day",m_timepoint.date().day());
    key.setAttribute("hour",m_timepoint.time().hour());
    key.setAttribute("minute",m_timepoint.time().minute());
    key.setAttribute("second",m_timepoint.time().second());
    key.setAttribute("msec",m_timepoint.time().msec());
    element.appendChild(key);

    // Now use the image's frame set
    TQDomElement elementText=stackItem->stackElementText;
    TQDomElement elementFormatsPlural=stackItem->stackElementFormatsPlural;
    elementText.appendChild(mainDocument.createTextNode("#"));

    TQDomElement formatElementOut=mainDocument.createElement("FORMAT");
    formatElementOut.setAttribute("id",6); // Normal text!
    formatElementOut.setAttribute("pos",stackItem->pos); // Start position
    formatElementOut.setAttribute("len",1); // Start position
    elementFormatsPlural.appendChild(formatElementOut); //Append to <FORMATS>

    // WARNING: we must change the position in stackCurrent!
    stackCurrent->pos++; // Adapt new starting position

    TQDomElement anchor=mainDocument.createElement("ANCHOR");
    // No name attribute!
    anchor.setAttribute("type","frameset");
    anchor.setAttribute("instance",strPictureFrameName);
    formatElementOut.appendChild(anchor);

    return true;
}

// <d>
static bool StartElementD(StackItem* stackItem, StackItem* /*stackCurrent*/,
    const TQXmlAttributes& attributes)
{
    // We do not assume when we are called or if we are or not a child of <data>
    // However, we assume that we are after all <image> elements
    stackItem->elementType=ElementTypeRealData;

    TQString strName=attributes.value("name").stripWhiteSpace();
    kdDebug(30506) << "Data: " << strName << endl;

    TQString strBase64=attributes.value("base64").stripWhiteSpace();
    TQString strMime=attributes.value("mime").stripWhiteSpace();

    if (strName.isEmpty())
    {
        kdWarning(30506) << "Data has no name!" << endl;
        stackItem->elementType=ElementTypeEmpty;
        return true;
    }

    if (strMime.isEmpty())
    {
        // Old AbiWord files had no mime types for images but the data were base64-coded PNG
        strMime="image/png";
        strBase64="yes";
    }

    stackItem->fontName=strName;        // Store the data name as font name.
    stackItem->bold=(strBase64=="yes"); // Store base64-coded as bold
    stackItem->strTemp1=strMime;        // Mime type
    stackItem->strTemp2=TQString();  // Image data

    return true;
}

static bool CharactersElementD (StackItem* stackItem, TQDomDocument& /*mainDocument*/, const TQString & ch)
{
    // As we have no guarantee to have the whole stream in one call, we must store the data.
    stackItem->strTemp2+=ch;
    return true;
}

bool StructureParser::EndElementD (StackItem* stackItem)
{
    if (!stackItem->elementType==ElementTypeRealData)
    {
        kdError(30506) << "Wrong element type!! Aborting! (in endElementD)" << endl;
        return false;
    }
    if (!m_chain)
    {
        kdError(30506) << "No filter chain! Aborting! (in endElementD)" << endl;
        return false;
    }

    bool isSvg=false;  // SVG ?

    TQString extension;

    // stackItem->strTemp1 contains the mime type
    if (stackItem->strTemp1=="image/png")
    {
        extension=".png";
    }
    else if (stackItem->strTemp1=="image/jpeg") // ### FIXME: in fact it does not exist in AbiWord
    {
        extension=".jpeg";
    }
    else if (stackItem->strTemp1=="image/svg-xml") //Yes it is - not +
    {
        extension=".svg";
        isSvg=true;
    }
    else
    {
        kdWarning(30506) << "Unknown or unsupported mime type: "
            << stackItem->strTemp1 << endl;
        return true;
    }

    TQString strStoreName;
    strStoreName="pictures/picture";
    strStoreName+=TQString::number(++m_pictureNumber);
    strStoreName+=extension;

    TQString strDataId=stackItem->fontName;  // AbiWord's data id
    TQDomElement key=mainDocument.createElement("KEY");
    key.setAttribute("filename",strDataId);
    key.setAttribute("year",m_timepoint.date().year());
    key.setAttribute("month",m_timepoint.date().month());
    key.setAttribute("day",m_timepoint.date().day());
    key.setAttribute("hour",m_timepoint.time().hour());
    key.setAttribute("minute",m_timepoint.time().minute());
    key.setAttribute("second",m_timepoint.time().second());
    key.setAttribute("msec",m_timepoint.time().msec());
    key.setAttribute("name",strStoreName);
    m_picturesElement.appendChild(key);

    KoStoreDevice* out=m_chain->storageFile(strStoreName, KoStore::Write);
    if(!out)
    {
        kdError(30506) << "Unable to open output file for: " << stackItem->fontName << " Storage: " << strStoreName << endl;
        return false;
    }

    if (stackItem->bold) // Is base64-coded?
    {
        kdDebug(30506) << "Decode and write base64 stream: " << stackItem->fontName << endl;
        // We need to decode the base64 stream
        // However KCodecs has no TQString to TQByteArray decoder!
        TQByteArray base64Stream=stackItem->strTemp2.utf8(); // Use utf8 to avoid corruption of data
        TQByteArray binaryStream;
        KCodecs::base64Decode(base64Stream, binaryStream);
        out->writeBlock(binaryStream, binaryStream.count());
    }
    else
    {
        // Unknown text format!
        kdDebug(30506) << "Write character stream: " << stackItem->fontName << endl;
        // We strip the white space in front to avoid white space before a XML declaration
        TQCString strOut=stackItem->strTemp2.stripWhiteSpace().utf8();
        out->writeBlock(strOut,strOut.length());
    }

    return true;
}

// <m>
static bool StartElementM(StackItem* stackItem, StackItem* /*stackCurrent*/,
    const TQXmlAttributes& attributes)
{
    // We do not assume when we are called or if we are or not a child of <metadata>
    stackItem->elementType=ElementTypeRealMetaData;

    TQString strKey=attributes.value("key").stripWhiteSpace();
    kdDebug(30506) << "Metadata key: " << strKey << endl;

    if (strKey.isEmpty())
    {
        kdWarning(30506) << "Metadata has no key!" << endl;
        stackItem->elementType=ElementTypeIgnore;
        return true;
    }

    stackItem->strTemp1=strKey;        // Key
    stackItem->strTemp2=TQString();  // Meta data

    return true;
}

static bool CharactersElementM (StackItem* stackItem, const TQString & ch)
{
    // As we have no guarantee to have the whole data in one call, we must store the data.
    stackItem->strTemp2+=ch;
    return true;
}

bool StructureParser::EndElementM (StackItem* stackItem)
{
    if (!stackItem->elementType==ElementTypeRealData)
    {
        kdError(30506) << "Wrong element type!! Aborting! (in endElementM)" << endl;
        return false;
    }

    if (stackItem->strTemp1.isEmpty())
    {
        // Probably an internal error!
        kdError(30506) << "Key name was erased! Aborting! (in endElementM)" << endl;
        return false;
    }

    // Just add it to the metadata map, we do not do something special with the values.
    m_metadataMap[stackItem->strTemp1]=stackItem->strTemp2;

    return true;
}

// <br> (forced line break)
static bool StartElementBR(StackItem* stackItem, StackItem* stackCurrent,
    TQDomDocument& mainDocument)
{
    // <br> elements are mostly in <c> but can also be in <p>
    if ((stackCurrent->elementType==ElementTypeParagraph)
        || (stackCurrent->elementType==ElementTypeContent))
    {
        stackItem->elementType=ElementTypeEmpty;

        // Now work on stackCurrent

        if  (stackCurrent->elementType==ElementTypeContent)
        {
            // Child <c>, so we have to add formating of <c>
            TQDomElement formatElement=mainDocument.createElement("FORMAT");
            formatElement.setAttribute("id",1); // Normal text!
            formatElement.setAttribute("pos",stackCurrent->pos); // Start position
            formatElement.setAttribute("len",1);
            AddFormat(formatElement, stackCurrent, mainDocument); // Add the format of the parent <c>
            stackCurrent->stackElementFormatsPlural.appendChild(formatElement); //Append to <FORMATS>
        }

        stackCurrent->stackElementText.appendChild(mainDocument.createTextNode(TQChar(10))); // Add a LINE FEED
        stackCurrent->pos++; // Adjust position

    }
    else
    {//we are not nested correctly, so consider it a parse error!
        kdError(30506) << "parse error <br> tag not nested in <p> or <c> but in "
            << stackCurrent->itemName << endl;
        return false;
    }
    return true;
}

// <cbr> (forced column break, not supported)
// <pbr> (forced page break)
static bool StartElementPBR(StackItem* /*stackItem*/, StackItem* stackCurrent,
    TQDomDocument& mainDocument)
{
    // We are sure to be the child of a <p> element

    // The following code is similar to the one in StartElementP
    // We use mainFramesetElement here not to be dependant that <section> has happened before
    TQDomElement paragraphElementOut=mainDocument.createElement("PARAGRAPH");
    stackCurrent->m_frameset.appendChild(paragraphElementOut);
    TQDomElement textElementOut=mainDocument.createElement("TEXT");
    paragraphElementOut.appendChild(textElementOut);
    TQDomElement formatsPluralElementOut=mainDocument.createElement("FORMATS");
    paragraphElementOut.appendChild(formatsPluralElementOut);

    // We must now copy/clone the layout of elementText.

    TQDomNodeList nodeList=stackCurrent->stackElementParagraph.elementsByTagName("LAYOUT");

    if (!nodeList.count())
    {
        kdError(30506) << "Unable to find <LAYOUT> element! Aborting! (in StartElementPBR)" <<endl;
        return false;
    }

    // Now clone it
    TQDomNode newNode=nodeList.item(0).cloneNode(true); // We make a deep cloning of the first element/node
    if (newNode.isNull())
    {
        kdError(30506) << "Unable to clone <LAYOUT> element! Aborting! (in StartElementPBR)" <<endl;
        return false;
    }
    paragraphElementOut.appendChild(newNode);

    // We need a page break!
    TQDomElement oldLayoutElement=nodeList.item(0).toElement();
    if (oldLayoutElement.isNull())
    {
        kdError(30506) << "Cannot find old <LAYOUT> element! Aborting! (in StartElementPBR)" <<endl;
        return false;
    }
    // We have now to add a element <PAGEBREAKING>
    // TODO/FIXME: what if there is already one?
    TQDomElement pagebreakingElement=mainDocument.createElement("PAGEBREAKING");
    pagebreakingElement.setAttribute("linesTogether","false");
    pagebreakingElement.setAttribute("hardFrameBreak","false");
    pagebreakingElement.setAttribute("hardFrameBreakAfter","true");
    oldLayoutElement.appendChild(pagebreakingElement);

    // Now that we have done with the old paragraph,
    //  we can write stackCurrent with the data of the new one!
    // NOTE: The following code is similar to the one in StartElementP but we are working on stackCurrent!
    stackCurrent->elementType=ElementTypeParagraph;
    stackCurrent->stackElementParagraph=paragraphElementOut; // <PARAGRAPH>
    stackCurrent->stackElementText=textElementOut; // <TEXT>
    stackCurrent->stackElementFormatsPlural=formatsPluralElementOut; // <FORMATS>
    stackCurrent->pos=0; // No text character yet

    return true;
}

// <pagesize>
static bool StartElementPageSize(TQDomElement& paperElement, const TQXmlAttributes& attributes)
{
    if (attributes.value("page-scale").toDouble()!=1.0)
    {
        kdWarning(30506) << "Ignoring unsupported page scale: " << attributes.value("page-scale") << endl;
    }

    int kwordOrientation;
    TQString strOrientation=attributes.value("orientation").stripWhiteSpace();

    if (strOrientation=="portrait")
    {
        kwordOrientation=0;
    }
    else if (strOrientation=="landscape")
    {
        kwordOrientation=1;
    }
    else
    {
        kdWarning(30506) << "Unknown page orientation: " << strOrientation << "! Ignoring! " << endl;
        kwordOrientation=0;
    }

    double kwordHeight;
    double kwordWidth;

    TQString strPageType=attributes.value("pagetype").stripWhiteSpace();

    // Do we know the page size or do we need to measure?
    // For page formats that KWord knows, use our own values in case the values in the file would be wrong.

    KoFormat kwordFormat = KoPageFormat::formatFromString(strPageType);

    if (kwordFormat==PG_CUSTOM)
    {
        kdDebug(30506) << "Custom or other page format found: " << strPageType << endl;

        double height = attributes.value("height").toDouble();
        double width  = attributes.value("width" ).toDouble();

        TQString strUnits = attributes.value("units").stripWhiteSpace();

        kdDebug(30506) << "Explicit page size: "
         << height << " " << strUnits << " x " << width << " " << strUnits
         << endl;

        if (strUnits=="cm")
        {
            kwordHeight = CentimetresToPoints(height);
            kwordWidth  = CentimetresToPoints(width);
        }
        else if (strUnits=="inch")
        {
            kwordHeight = InchesToPoints(height);
            kwordWidth  = InchesToPoints(width);
        }
        else if (strUnits=="mm")
        {
            kwordHeight = MillimetresToPoints(height);
            kwordWidth  = MillimetresToPoints(width);
        }
        else
        {
            kwordHeight = 0.0;
            kwordWidth  = 0.0;
            kdWarning(30506) << "Unknown unit type: " << strUnits << endl;
        }
    }
    else
    {
        // We have a format known by KOffice, so use KOffice's functions
        kwordHeight = MillimetresToPoints(KoPageFormat::height(kwordFormat,PG_PORTRAIT));
        kwordWidth  = MillimetresToPoints(KoPageFormat::width (kwordFormat,PG_PORTRAIT));
    }

    if ((kwordHeight <= 1.0) || (kwordWidth <= 1.0))
        // At least one of the two values is ridiculous
    {
        kdWarning(30506) << "Page width or height is too small: "
         << kwordHeight << "x" << kwordWidth << endl;
        // As we have no correct page size, we assume we have A4
        kwordFormat = PG_DIN_A4;
        kwordHeight = CentimetresToPoints(29.7);
        kwordWidth  = CentimetresToPoints(21.0);
    }

    // Now that we have gathered all the page size data, put it in the right element!

    if (paperElement.isNull())
    {
        kdError(30506) << "<PAPER> element cannot be accessed! Aborting!" << endl;
        return false;
    }

    paperElement.setAttribute("format",kwordFormat);
    paperElement.setAttribute("width",kwordWidth);
    paperElement.setAttribute("height",kwordHeight);
    paperElement.setAttribute("orientation",kwordOrientation);

    return true;
}


bool StructureParser::complexForcedPageBreak(StackItem* stackItem)
{
    // We are not a child of a <p> element, so we cannot use StartElementPBR directly

    StackItemStack auxilaryStack;

    if (!clearStackUntilParagraph(auxilaryStack))
    {
        kdError(30506) << "Could not clear stack until a paragraph!" << endl;
        return false;
    }

    // Now we are a child of a <p> element!

    bool success=StartElementPBR(stackItem,structureStack.current(),mainDocument);

    // Now restore the stack

    StackItem* stackCurrent=structureStack.current();
    StackItem* item;
    while (auxilaryStack.count()>0)
    {
        item=auxilaryStack.pop();
        // We cannot put back the item on the stack like that.
        // We must set a few values for each item.
        item->pos=0; // Start at position 0
        item->stackElementParagraph=stackCurrent->stackElementParagraph; // new <PARAGRAPH>
        item->stackElementText=stackCurrent->stackElementText; // new <TEXT>
        item->stackElementFormatsPlural=stackCurrent->stackElementFormatsPlural; // new <FORMATS>
        structureStack.push(item);
    }

    return success;
}


// <section>
bool StructureParser::StartElementSection(StackItem* stackItem, StackItem* /*stackCurrent*/,
    const TQXmlAttributes& attributes)
{
    //TODO: non main text sections (e.g. footers)
    stackItem->elementType=ElementTypeSection;

    AbiPropsMap abiPropsMap;
    // Treat the props attributes in the two available flavors: lower case and upper case.
    kdDebug(30506)<< "========== props=\"" << attributes.value("props") << "\"" << endl;
    abiPropsMap.splitAndAddAbiProps(attributes.value("props"));
    abiPropsMap.splitAndAddAbiProps(attributes.value("PROPS")); // PROPS is deprecated

    // TODO: only the first main text section should change the page margins
    // TODO;   (as KWord does not allow different page sizes/margins for the same document)
    if (true && (!m_paperBordersElement.isNull()))
    {
        TQString str;
        str=abiPropsMap["page-margin-top"].getValue();
        if (!str.isEmpty())
        {
            m_paperBordersElement.setAttribute("top",ValueWithLengthUnit(str));
        }
        str=abiPropsMap["page-margin-left"].getValue();
        if (!str.isEmpty())
        {
            m_paperBordersElement.setAttribute("left",ValueWithLengthUnit(str));
        }
        str=abiPropsMap["page-margin-bottom"].getValue();
        if (!str.isEmpty())
        {
            m_paperBordersElement.setAttribute("bottom",ValueWithLengthUnit(str));
        }
        str=abiPropsMap["page-margin-right"].getValue();
        if (!str.isEmpty())
        {
            m_paperBordersElement.setAttribute("right",ValueWithLengthUnit(str));
        }
    }
    return true;
}

// <iw>

static bool EndElementIW(StackItem* stackItem, StackItem* /*stackCurrent*/,
    TQDomDocument& mainDocument, TQDomElement& m_ignoreWordsElement)
{
    if (!stackItem->elementType==ElementTypeIgnoreWord)
    {
        kdError(30506) << "Wrong element type!! Aborting! (in endElementIW)" << endl;
        return false;
    }
    TQDomElement wordElement=mainDocument.createElement("SPELLCHECKIGNOREWORD");
    wordElement.setAttribute("word",stackItem->strTemp2.stripWhiteSpace());
    m_ignoreWordsElement.appendChild(wordElement);
    return true;
}

// <foot>
bool StructureParser::StartElementFoot(StackItem* stackItem, StackItem* /*stackCurrent*/,
    const TQXmlAttributes& /*attributes*/)
{
#if 0
    stackItem->elementType=ElementTypeFoot;

    const TQString id(attributes.value("endnote-id").stripWhiteSpace());
    kdDebug(30506) << "Foot note id: " << id << endl;

    if (id.isEmpty())
    {
        kdWarning(30506) << "Footnote has no id!" << endl;
        stackItem->elementType=ElementTypeIgnore;
        return true;
    }

    // We need to create a frameset for the foot note.
    TQDomElement framesetElement(mainDocument.createElement("FRAMESET"));
    framesetElement.setAttribute("frameType",1);
    framesetElement.setAttribute("frameInfo",7);
    framesetElement.setAttribute("visible",1);
    framesetElement.setAttribute("name",getFootnoteFramesetName(id));
    framesetsPluralElement.appendChild(framesetElement);

    TQDomElement frameElementOut(mainDocument.createElement("FRAME"));
    //frameElementOut.setAttribute("left",28);
    //frameElementOut.setAttribute("top",42);
    //frameElementOut.setAttribute("bottom",566);
    //frameElementOut.setAttribute("right",798);
    frameElementOut.setAttribute("runaround",1);
    // ### TODO: a few attributes are missing
    framesetElement.appendChild(frameElementOut);

    stackItem->m_frameset=framesetElement;
#else
    stackItem->elementType=ElementTypeIgnore;
#endif
    return true;
}

// Element <table>
bool StructureParser::StartElementTable(StackItem* stackItem, StackItem* stackCurrent,
    const TQXmlAttributes& attributes)
{
#if 1
    // In KWord, inline tables are inside a paragraph.
    // In AbiWord, tables are outside any paragraph.

    TQStringList widthList;
    widthList.split('/', attributes.value("table-column-props"), false);
    const uint columns = widthList.size();
    stackItem->m_doubleArray.detach(); // Be sure not to modify parents
    stackItem->m_doubleArray.resize(columns+1); // All left positions but the last right one
    stackItem->m_doubleArray[0] = 0.0;
    TQStringList::ConstIterator it;
    uint i;
    for ( i=0, it=widthList.begin(); i<columns; ++i, ++it )
    {
        kdDebug(30506) << "Column width: " << (*it) << " cooked " << ValueWithLengthUnit(*it) << endl;
        stackItem->m_doubleArray[i+1] = ValueWithLengthUnit(*it) + stackItem->m_doubleArray[i];
    }
    // ### TODO: in case of automatic column widths, we have not any width given by AbiWord

    const uint tableNumber(++m_tableGroupNumber);
    const TQString tableName(i18n("Table %1").arg(tableNumber));

    TQDomElement elementText=stackCurrent->stackElementText;
    TQDomElement paragraphElementOut=mainDocument.createElement("PARAGRAPH");
    stackCurrent->m_frameset.appendChild(paragraphElementOut);

    TQDomElement textElementOut(mainDocument.createElement("TEXT"));
    textElementOut.appendChild(mainDocument.createTextNode("#"));
    paragraphElementOut.appendChild(textElementOut);

    TQDomElement formatsPluralElementOut=mainDocument.createElement("FORMATS");
    paragraphElementOut.appendChild(formatsPluralElementOut);

    TQDomElement elementFormat(mainDocument.createElement("FORMAT"));
    elementFormat.setAttribute("id",6);
    elementFormat.setAttribute("pos",0);
    elementFormat.setAttribute("len",1);
    formatsPluralElementOut.appendChild(elementFormat);

    TQDomElement elementAnchor(mainDocument.createElement("ANCHOR"));
    elementAnchor.setAttribute("type","frameset");
    elementAnchor.setAttribute("instance",tableName);
    elementFormat.appendChild(elementAnchor);

    stackItem->elementType=ElementTypeTable;
    stackItem->stackElementParagraph=paragraphElementOut; // <PARAGRAPH>
    stackItem->stackElementText=textElementOut; // <TEXT>
    stackItem->stackElementFormatsPlural=formatsPluralElementOut; // <FORMATS>
    stackItem->strTemp1=tableName;
    stackItem->strTemp2=TQString::number(tableNumber); // needed as I18N does not allow adding phrases
    stackItem->pos=1; // Just #

    // Now we populate the layout
    TQDomElement layoutElement=mainDocument.createElement("LAYOUT");
    paragraphElementOut.appendChild(layoutElement);

    AbiPropsMap abiPropsMap;
    styleDataMap.useOrCreateStyle("Normal"); // We might have to create the "Normal" style.
    AddLayout("Normal", layoutElement, stackItem, mainDocument, abiPropsMap, 0, false);
#else
    stackItem->elementType=ElementTypeIgnore;
#endif
    return true;
}

// <cell>
bool StructureParser::StartElementCell(StackItem* stackItem, StackItem* stackCurrent,
    const TQXmlAttributes& attributes)
{
#if 1
    if (stackCurrent->elementType!=ElementTypeTable)
    {
        kdError(30506) << "Wrong element type!! Aborting! (in StructureParser::endElementCell)" << endl;
        return false;
    }

    stackItem->elementType=ElementTypeCell;

    const TQString tableName(stackCurrent->strTemp1);
    kdDebug(30506) << "Table name: " << tableName << endl;

    if (tableName.isEmpty())
    {
        kdError(30506) << "Table name is empty! Aborting!" << endl;
        return false;
    }

    AbiPropsMap abiPropsMap;
    abiPropsMap.splitAndAddAbiProps(attributes.value("props")); // Do not check PROPS

    // We abuse the attach number to know the row and col numbers.
    const uint row=abiPropsMap["top-attach"].getValue().toUInt();
    const uint col=abiPropsMap["left-attach"].getValue().toUInt();

    if ( col >= stackItem->m_doubleArray.size() )
    {
        // We do not know the right position of this column, so improvise. (### TODO)
        // We play on the fact that TQByteArray uses shallow copies by default.
        //  (We do want that the change is known at <table> level)
        stackItem->m_doubleArray.resize( stackItem->m_doubleArray.size() + 1, TQGArray::SpeedOptim );
        stackItem->m_doubleArray[col+1] = stackItem->m_doubleArray[col] + 72; // Try 1 inch
    }

    const TQString frameName(i18n("Frameset name","Table %3, row %1, column %2")
        .arg(row).arg(col).arg(stackCurrent->strTemp2)); // As the stack could be wrong, be careful and use the string as last!

    // We need to create a frameset for the cell
    TQDomElement framesetElement(mainDocument.createElement("FRAMESET"));
    framesetElement.setAttribute("frameType",1);
    framesetElement.setAttribute("frameInfo",0);
    framesetElement.setAttribute("visible",1);
    framesetElement.setAttribute("name",frameName);
    framesetElement.setAttribute("row",row);
    framesetElement.setAttribute("col",col);
    framesetElement.setAttribute("rows",1); // ### TODO: rowspan
    framesetElement.setAttribute("cols",1); // ### TODO: colspan
    framesetElement.setAttribute("grpMgr",tableName);
    framesetsPluralElement.appendChild(framesetElement);

    TQDomElement frameElementOut(mainDocument.createElement("FRAME"));
    frameElementOut.setAttribute( "left", stackItem->m_doubleArray[col] );
    frameElementOut.setAttribute( "right", stackItem->m_doubleArray[col+1] );
    frameElementOut.setAttribute("top",0);
    frameElementOut.setAttribute("bottom",0);
    frameElementOut.setAttribute("runaround",1);
    frameElementOut.setAttribute("autoCreateNewFrame",0); // Very important for cell growing!
    // ### TODO: a few attributes are missing
    framesetElement.appendChild(frameElementOut);

    stackItem->m_frameset=framesetElement;
    TQDomElement nullDummy;
    stackItem->stackElementParagraph=nullDummy; // <PARAGRAPH>
    stackItem->stackElementText=nullDummy; // <TEXT>
    stackItem->stackElementFormatsPlural=nullDummy; // <FORMATS>

#else
    stackItem->elementType=ElementTypeIgnore;
#endif
    return true;
}

// Parser for SAX2

bool StructureParser :: startElement( const TQString&, const TQString&, const TQString& name, const TQXmlAttributes& attributes)
{
    //Warning: be careful that some element names can be lower case or upper case (not very XML)
    kdDebug(30506) << indent << " <" << name << ">" << endl; //DEBUG
    indent += "*"; //DEBUG

    if (structureStack.isEmpty())
    {
        kdError(30506) << "Stack is empty!! Aborting! (in StructureParser::startElement)" << endl;
        return false;
    }

    // Create a new stack element copying the top of the stack.
    StackItem *stackItem=new StackItem(*structureStack.current());

    if (!stackItem)
    {
        kdError(30506) << "Could not create Stack Item! Aborting! (in StructureParser::startElement)" << endl;
        return false;
    }

    stackItem->itemName=name;

    bool success=false;

    if ((name=="c")||(name=="C"))
    {
        success=StartElementC(stackItem,structureStack.current(),attributes);
    }
    else if ((name=="p")||(name=="P"))
    {
        success=StartElementP(stackItem,structureStack.current(),mainDocument,
            styleDataMap,attributes);
    }
    else if ((name=="section")||(name=="SECTION"))
    {
        success=StartElementSection(stackItem,structureStack.current(),attributes);
    }
    else if (name=="a")
    {
        success=StartElementA(stackItem,structureStack.current(),attributes);
    }
    else if (name=="br") // NOTE: Not sure if it only exists in lower case!
    {
        // We have a forced line break
        StackItem* stackCurrent=structureStack.current();
        success=StartElementBR(stackItem,stackCurrent,mainDocument);
    }
    else if (name=="cbr") // NOTE: Not sure if it only exists in lower case!
    {
        // We have a forced column break (not supported by KWord)
        stackItem->elementType=ElementTypeEmpty;
        StackItem* stackCurrent=structureStack.current();
        if (stackCurrent->elementType==ElementTypeContent)
        {
            kdWarning(30506) << "Forced column break found! Transforming to forced page break" << endl;
            success=complexForcedPageBreak(stackItem);
        }
        else if (stackCurrent->elementType==ElementTypeParagraph)
        {
            kdWarning(30506) << "Forced column break found! Transforming to forced page break" << endl;
            success=StartElementPBR(stackItem,stackCurrent,mainDocument);
        }
        else
        {
            kdError(30506) << "Forced column break found out of turn! Aborting! Parent: "
                << stackCurrent->itemName <<endl;
            success=false;
        }
    }
    else if (name=="pbr") // NOTE: Not sure if it only exists in lower case!
    {
        // We have a forced page break
        stackItem->elementType=ElementTypeEmpty;
        StackItem* stackCurrent=structureStack.current();
        if (stackCurrent->elementType==ElementTypeContent)
        {
            success=complexForcedPageBreak(stackItem);
        }
        else if (stackCurrent->elementType==ElementTypeParagraph)
        {
            success=StartElementPBR(stackItem,stackCurrent,mainDocument);
        }
        else
        {
            kdError(30506) << "Forced page break found out of turn! Aborting! Parent: "
                << stackCurrent->itemName <<endl;
            success=false;
        }
    }
    else if (name=="pagesize")
        // Does only exist as lower case tag!
    {
        stackItem->elementType=ElementTypeEmpty;
        stackItem->stackElementText=structureStack.current()->stackElementText; // TODO: reason?
        success=StartElementPageSize(m_paperElement,attributes);
    }
    else if ((name=="field") //TODO: upper-case?
        || (name=="f")) // old deprecated name for <field>
    {
        success=StartElementField(stackItem,structureStack.current(),mainDocument,attributes);
    }
    else if (name=="s") // Seems only to exist as lower case
    {
        success=StartElementS(stackItem,structureStack.current(),attributes,styleDataMap);
    }
    else if ((name=="image") //TODO: upper-case?
        || (name=="i")) // old deprecated name for <image>
    {
        success=StartElementImage(stackItem,structureStack.current(),attributes);
    }
    else if (name=="d") // TODO: upper-case?
    {
        success=StartElementD(stackItem,structureStack.current(),attributes);
    }
    else if (name=="iw") // No upper-case
    {
        stackItem->elementType=ElementTypeIgnoreWord;
        success=true;
    }
    else if (name=="m") // No upper-case
    {
        success=StartElementM(stackItem,structureStack.current(),attributes);
    }
    else if (name=="foot") // No upper-case
    {
        success=StartElementFoot(stackItem,structureStack.current(),attributes);
    }
    else if (name=="table") // No upper-case
    {
        success=StartElementTable(stackItem,structureStack.current(), attributes);
    }
    else if (name=="cell") // No upper-case
    {
        success=StartElementCell(stackItem,structureStack.current(),attributes);
    }
    else
    {
        stackItem->elementType=ElementTypeUnknown;
        stackItem->stackElementText=structureStack.current()->stackElementText; // TODO: reason?
        success=true;
    }
    if (success)
    {
        structureStack.push(stackItem);
    }
    else
    {   // We have a problem so destroy our resources.
        delete stackItem;
    }
    return success;
}

bool StructureParser :: endElement( const TQString&, const TQString& , const TQString& name)
{
    indent.remove( 0, 1 ); // DEBUG
    kdDebug(30506) << indent << " </" << name << ">" << endl;

    if (structureStack.isEmpty())
    {
        kdError(30506) << "Stack is empty!! Aborting! (in StructureParser::endElement)" << endl;
        return false;
    }

    bool success=false;

    StackItem *stackItem=structureStack.pop();
    if ((name=="c")||(name=="C"))
    {
        success=EndElementC(stackItem,structureStack.current());
    }
    else if ((name=="p")||(name=="P"))
    {
        success=EndElementP(stackItem);
    }
    else if (name=="a")
    {
        if (stackItem->elementType==ElementTypeContent)
        {
            // Anchor to a bookmark (not supported by KWord))
            success=EndElementC(stackItem,structureStack.current());
        }
        else
        {
            // Normal anchor
            success=EndElementA(stackItem,structureStack.current(), mainDocument);
        }
    }
    else if (name=="d")
    {
        success=EndElementD(stackItem);
    }
    else if (name=="iw") // No upper-case
    {
        success=EndElementIW(stackItem,structureStack.current(), mainDocument, m_ignoreWordsElement);
    }
    else if (name=="m") // No upper-case
    {
        success=EndElementM(stackItem);
    }
    else
    {
        success=true; // No problem, so authorisation to continue parsing
    }
    if (!success)
    {
        // If we have no success, then it was surely a tag mismatch. Help debugging!
        kdError(30506) << "Found tag name: " << name
            << " expected: " << stackItem->itemName << endl;
    }
    delete stackItem;
    return success;
}

bool StructureParser :: characters ( const TQString & ch )
{
    // DEBUG start
    if (ch=="\n")
    {
        kdDebug(30506) << indent << " (LINEFEED)" << endl;
    }
    else if (ch.length()> 40)
    {   // 40 characters are enough (especially for image data)
        kdDebug(30506) << indent << " :" << ch.left(40) << "..." << endl;
    }
    else
    {
        kdDebug(30506) << indent << " :" << ch << ":" << endl;
    }
    // DEBUG end
    if (structureStack.isEmpty())
    {
        kdError(30506) << "Stack is empty!! Aborting! (in StructureParser::characters)" << endl;
        return false;
    }

    bool success=false;

    StackItem *stackItem=structureStack.current();

    if ((stackItem->elementType==ElementTypeContent)
        || (stackItem->elementType==ElementTypeAnchorContent))
    { // <c>
        success=charactersElementC(stackItem,mainDocument,ch);
    }
    else if (stackItem->elementType==ElementTypeParagraph)
    { // <p>
        success=charactersElementP(stackItem,mainDocument,ch);
    }
    else if (stackItem->elementType==ElementTypeAnchor)
    { // <a>
        success=charactersElementA(stackItem,ch);
    }
    else if (stackItem->elementType==ElementTypeEmpty)
    {
        success=ch.stripWhiteSpace().isEmpty();
        if (!success)
        {
            // We have a parsing error, so abort!
            kdError(30506) << "Empty element "<< stackItem->itemName
                <<" is not empty! Aborting! (in StructureParser::characters)" << endl;
        }
    }
    else if (stackItem->elementType==ElementTypeRealData)
    {
        success=CharactersElementD(stackItem,mainDocument,ch);
    }
    else if (stackItem->elementType==ElementTypeIgnoreWord)
    {
        stackItem->strTemp2+=ch; // Just collect the data
        success=true;
    }
    else if (stackItem->elementType==ElementTypeRealMetaData)
    {
        success=CharactersElementM(stackItem,ch);
    }
    else
    {
        success=true;
    }

    return success;
}

bool StructureParser::startDocument(void)
{
    indent = TQString();  //DEBUG
    styleDataMap.defineDefaultStyles();
    return true;
}

void StructureParser::createDocInfo(void)
{
    TQDomImplementation implementation;
    TQDomDocument doc(implementation.createDocumentType("document-info",
        "-//KDE//DTD document-info 1.2//EN", "http://www.koffice.org/DTD/document-info-1.2.dtd"));

    m_info=doc;

    m_info.appendChild(
        mainDocument.createProcessingInstruction(
        "xml","version=\"1.0\" encoding=\"UTF-8\""));

    TQDomElement elementDoc(mainDocument.createElement("document-info"));
    elementDoc.setAttribute("xmlns","http://www.koffice.org/DTD/document-info");
    m_info.appendChild(elementDoc);

    TQDomElement about(mainDocument.createElement("about"));
    elementDoc.appendChild(about);

    TQDomElement abstract(mainDocument.createElement("abstract"));
    about.appendChild(abstract);
    abstract.appendChild(mainDocument.createTextNode(m_metadataMap["dc.description"]));

    TQDomElement title(mainDocument.createElement("title"));
    about.appendChild(title);
    title.appendChild(mainDocument.createTextNode(m_metadataMap["dc.title"]));

    TQDomElement keyword(mainDocument.createElement("keyword"));
    about.appendChild(keyword);
    keyword.appendChild(mainDocument.createTextNode(m_metadataMap["abiword.keywords"]));

    TQDomElement subject(mainDocument.createElement("subject"));
    about.appendChild(subject);
    subject.appendChild(mainDocument.createTextNode(m_metadataMap["dc.subject"]));
}

bool StructureParser::endDocument(void)
{
    TQDomElement stylesPluralElement=mainDocument.createElement("STYLES");
    // insert before <PICTURES>, as <PICTURES> must remain last.
    mainDocument.documentElement().insertBefore(stylesPluralElement,m_picturesElement);

    kdDebug(30506) << "###### Start Style List ######" << endl;
    StyleDataMap::ConstIterator it;

    // At first, we put the Normal style
    it=styleDataMap.find("Normal");
    if (it!=styleDataMap.end())
    {
        kdDebug(30506) << "\"" << it.key() << "\" => " << it.data().m_props << endl;
        TQDomElement styleElement=mainDocument.createElement("STYLE");
        stylesPluralElement.appendChild(styleElement);
        AddStyle(styleElement, it.key(),it.data(),mainDocument);
    }
    else
        kdWarning(30506) << "No 'Normal' style" << endl;

    for (it=styleDataMap.begin();it!=styleDataMap.end();++it)
    {
        if (it.key()=="Normal")
            continue;

        kdDebug(30506) << "\"" << it.key() << "\" => " << it.data().m_props << endl;

        TQDomElement styleElement=mainDocument.createElement("STYLE");
        stylesPluralElement.appendChild(styleElement);

        AddStyle(styleElement, it.key(),it.data(),mainDocument);
    }
    kdDebug(30506) << "######  End Style List  ######" << endl;

    createDocInfo();

    return true;
}

bool StructureParser::warning(const TQXmlParseException& exception)
{
    kdWarning(30506) << "XML parsing warning: line " << exception.lineNumber()
        << " col " << exception.columnNumber() << " message: " << exception.message() << endl;
    return true;
}

bool StructureParser::error(const TQXmlParseException& exception)
{
    // A XML error is recoverable, so it is only a KDE warning
    kdWarning(30506) << "XML parsing error: line " << exception.lineNumber()
        << " col " << exception.columnNumber() << " message: " << exception.message() << endl;
    return true;
}

bool StructureParser::fatalError (const TQXmlParseException& exception)
{
    kdError(30506) << "XML parsing fatal error: line " << exception.lineNumber()
        << " col " << exception.columnNumber() << " message: " << exception.message() << endl;
    m_fatalerror=true;
    KMessageBox::error(NULL, i18n("An error has occurred while parsing the AbiWord file.\nAt line: %1, column %2\nError message: %3")
        .arg(exception.lineNumber()).arg(exception.columnNumber())
        .arg( i18n( "TQXml", exception.message().utf8() ) ),
        i18n("AbiWord Import Filter"),0);
    return false; // Stop parsing now, we do not need further errors.
}

void StructureParser :: createDocument(void)
{
    TQDomImplementation implementation;
    TQDomDocument doc(implementation.createDocumentType("DOC",
        "-//KDE//DTD kword 1.2//EN", "http://www.koffice.org/DTD/kword-1.2.dtd"));

    mainDocument=doc;

    mainDocument.appendChild(
        mainDocument.createProcessingInstruction(
        "xml","version=\"1.0\" encoding=\"UTF-8\""));

    TQDomElement elementDoc;
    elementDoc=mainDocument.createElement("DOC");
    elementDoc.setAttribute("xmlns","http://www.koffice.org/DTD/kword");
    elementDoc.setAttribute("editor","AbiWord Import Filter");
    elementDoc.setAttribute("mime","application/x-kword");
    elementDoc.setAttribute( "syntaxVersion", 3 );
    mainDocument.appendChild(elementDoc);

    TQDomElement element;
    element=mainDocument.createElement("ATTRIBUTES");
    element.setAttribute("processing",0);
    element.setAttribute("standardpage",1);
    element.setAttribute("hasHeader",0);
    element.setAttribute("hasFooter",0);
    //element.setAttribute("unit","mm"); // use KWord default instead
    element.setAttribute("tabStopValue",36); // AbiWord has a default of 0.5 inch tab stops
    elementDoc.appendChild(element);

    // <PAPER> will be partialy changed by an AbiWord <pagesize> element.
    // Default paper format of AbiWord is "Letter"
    m_paperElement=mainDocument.createElement("PAPER");
    m_paperElement.setAttribute("format",PG_US_LETTER);
    m_paperElement.setAttribute("width",MillimetresToPoints(KoPageFormat::width (PG_US_LETTER,PG_PORTRAIT)));
    m_paperElement.setAttribute("height",MillimetresToPoints(KoPageFormat::height(PG_US_LETTER,PG_PORTRAIT)));
    m_paperElement.setAttribute("orientation",PG_PORTRAIT);
    m_paperElement.setAttribute("columns",1);
    m_paperElement.setAttribute("columnspacing",2);
    m_paperElement.setAttribute("hType",0);
    m_paperElement.setAttribute("fType",0);
    m_paperElement.setAttribute("spHeadBody",9);
    m_paperElement.setAttribute("spFootBody",9);
    m_paperElement.setAttribute("zoom",100);
    elementDoc.appendChild(m_paperElement);

    m_paperBordersElement=mainDocument.createElement("PAPERBORDERS");
    m_paperBordersElement.setAttribute("left",28);
    m_paperBordersElement.setAttribute("top",42);
    m_paperBordersElement.setAttribute("right",28);
    m_paperBordersElement.setAttribute("bottom",42);
    m_paperElement.appendChild(m_paperBordersElement);

    framesetsPluralElement=mainDocument.createElement("FRAMESETS");
    mainDocument.documentElement().appendChild(framesetsPluralElement);

    mainFramesetElement=mainDocument.createElement("FRAMESET");
    mainFramesetElement.setAttribute("frameType",1);
    mainFramesetElement.setAttribute("frameInfo",0);
    mainFramesetElement.setAttribute("visible",1);
    mainFramesetElement.setAttribute("name",i18n("Frameset name","Main Text Frameset"));
    framesetsPluralElement.appendChild(mainFramesetElement);

    TQDomElement frameElementOut=mainDocument.createElement("FRAME");
    frameElementOut.setAttribute("left",28);
    frameElementOut.setAttribute("top",42);
    frameElementOut.setAttribute("bottom",566);
    frameElementOut.setAttribute("right",798);
    frameElementOut.setAttribute("runaround",1);
    // TODO: a few attributes are missing
    mainFramesetElement.appendChild(frameElementOut);

    // As we are manipulating the document, create a few particular elements
    m_ignoreWordsElement=mainDocument.createElement("SPELLCHECKIGNORELIST");
    mainDocument.documentElement().appendChild(m_ignoreWordsElement);
    m_picturesElement=mainDocument.createElement("PICTURES");
    mainDocument.documentElement().appendChild(m_picturesElement);
}

bool StructureParser::clearStackUntilParagraph(StackItemStack& auxilaryStack)
{
    for (;;)
    {
        StackItem* item=structureStack.pop();
        switch (item->elementType)
        {
        case ElementTypeContent:
            {
                // Push the item on the auxilary stack
                auxilaryStack.push(item);
                break;
            }
        case ElementTypeParagraph:
            {
                // Push back the item on this stack and then stop loop
                structureStack.push(item);
                return true;
            }
        default:
            {
                // Something has gone wrong!
                kdError(30506) << "Cannot clear this element: "
                    << item->itemName << endl;
                return false;
            }
        }
    }
}

ABIWORDImport::ABIWORDImport(KoFilter */*parent*/, const char */*name*/, const TQStringList &) :
                     KoFilter() {
}

KoFilter::ConversionStatus ABIWORDImport::convert( const TQCString& from, const TQCString& to )
{
    if ((to != "application/x-kword") || (from != "application/x-abiword"))
        return KoFilter::NotImplemented;

    kdDebug(30506)<<"AbiWord to KWord Import filter"<<endl;

    StructureParser handler(m_chain);

    //We arbitrarily decide that TQt can handle the encoding in which the file was written!!
    TQXmlSimpleReader reader;
    reader.setContentHandler( &handler );
    reader.setErrorHandler( &handler );

    //Find the last extension
    TQString strExt;
    TQString fileIn = m_chain->inputFile();
    const int result=fileIn.findRev('.');
    if (result>=0)
    {
        strExt=fileIn.mid(result);
    }

    kdDebug(30506) << "File extension: -" << strExt << "-" << endl;

    TQString strMime; // Mime type of the compressor (default: unknown)

    if ((strExt==".gz")||(strExt==".GZ")        //in case of .abw.gz (logical extension)
        ||(strExt==".zabw")||(strExt==".ZABW")) //in case of .zabw (extension used prioritary with AbiWord)
    {
        // Compressed with gzip
        strMime="application/x-gzip";
        kdDebug(30506) << "Compression: gzip" << endl;
    }
    else if ((strExt==".bz2")||(strExt==".BZ2") //in case of .abw.bz2 (logical extension)
        ||(strExt==".bzabw")||(strExt==".BZABW")) //in case of .bzabw (extension used prioritary with AbiWord)
    {
        // Compressed with bzip2
        strMime="application/x-bzip2";
        kdDebug(30506) << "Compression: bzip2" << endl;
    }

    TQIODevice* in = KFilterDev::deviceForFile(fileIn,strMime);

    if ( !in )
    {
        kdError(30506) << "Cannot create device for uncompressing! Aborting!" << endl;
        return KoFilter::FileNotFound; // ### TODO: better error?
    }

    if (!in->open(IO_ReadOnly))
    {
        kdError(30506) << "Cannot open file for uncompressing! Aborting!" << endl;
        delete in;
        return KoFilter::FileNotFound;
    }

    TQXmlInputSource source(in); // Read the file

    in->close();

    if (!reader.parse( source ))
    {
        kdError(30506) << "Import: Parsing unsuccessful. Aborting!" << endl;
        delete in;
        if (!handler.wasFatalError())
        {
            // As the parsing was stopped for something else than a fatal error, we have not yet get an error message. (Can it really happen?)
            KMessageBox::error(NULL, i18n("An error occurred during the load of the AbiWord file: %1").arg(from.data()),
                i18n("AbiWord Import Filter"),0);
        }
        return KoFilter::ParsingError;
    }
    delete in;

    TQCString strOut;
    KoStoreDevice* out;

    kdDebug(30506) << "Creating documentinfo.xml" << endl;
    out=m_chain->storageFile( "documentinfo.xml", KoStore::Write );
    if(!out)
    {
        kdError(30506) << "AbiWord Import unable to open output file! (Documentinfo)" << endl;
        KMessageBox::error(NULL, i18n("Unable to save document information."),i18n("AbiWord Import Filter"),0);
        return KoFilter::StorageCreationError;
    }

    //Write the document information!
    strOut=handler.getDocInfo().toCString(); // UTF-8
    // WARNING: we cannot use KoStore::write(const TQByteArray&) because it writes an extra NULL character at the end.
    out->writeBlock(strOut,strOut.length());

    kdDebug(30506) << "Creating maindoc.xml" << endl;
    out=m_chain->storageFile( "root", KoStore::Write );
    if(!out)
    {
        kdError(30506) << "AbiWord Import unable to open output file! (Root)" << endl;
        KMessageBox::error(NULL, i18n("Unable to save main document."),i18n("AbiWord Import Filter"),0);
        return KoFilter::StorageCreationError;
    }

    //Write the document!
    strOut=handler.getDocument().toCString(); // UTF-8
    // WARNING: we cannot use KoStore::write(const TQByteArray&) because it writes an extra NULL character at the end.
    out->writeBlock(strOut,strOut.length());

#if 0
    kdDebug(30506) << documentOut.toString();
#endif

    kdDebug(30506) << "Now importing to KWord!" << endl;

    return KoFilter::OK;
}

#include "abiwordimport.moc"