File: dddoc_html.py

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


# Number of warnings.
WARNING_COUNT = 0
OUT_PATH = 'html'

################################################################################

def createDocs(path, buildfull, indexonly, include_dirs):
    global globalDocsPath
    globalDocsPath = path

    global globalBuildFull
    globalBuildFull = buildfull

    global includeDirs
    includeDirs = include_dirs
    
    if not os.access(path, os.F_OK): 
        os.mkdir(path)
    copyFile(path, "dddoc_html.css")
    copyFile(path, "seqan_logo.gif")
    copyFile(path, "dddoc_empty.gif")
    copyFile(path, "dddoc_plus.gif")
    copyFile(path, "dddoc_minus.gif")
    copyFile(path, "dddoc.js")

    gatherGlossary()
        
    if buildfull or indexonly:
        createIndexes(path)
        createSearchfile(path)

    if not indexonly:
        createPages(path)

################################################################################

def createIndexes(path):
    cats = dddoc.DATA["globals.indexes"].keys()
    for cat in cats:
        print 'Indexes for ' + cat,
        
        entries = collectIndexEntries(cat)
        
        subcats = entries.keys()
        subcats.sort()
        for subcat in subcats:
            subcat_entries = entries[subcat]
            filename = os.path.join(path, getIndexname(cat, subcat))
            fl = file(filename, "w")
            print '.',
            pageIndex(fl, path, cat, subcat, entries, subcats)
            fl.close()
 
            
        filename = os.path.join(path, getIndexpage(cat))
        fl = file(filename, "w")
        print '.',
        pageIndexpage(fl, cat)
        fl.close()
        print


################################################################################

def createPages(path):
    cats = dddoc.DATA["globals.categories"].keys()
    for cat in cats:
        print 'Pages for ' + cat,
        
        entries = dddoc.DATA[cat]
        for key in entries.keys():
            data = entries[key]
            filename = os.path.join(path, getFilename(data.name(0), data.name(1)))
            fl = file(filename, "w")
            print '.',
            pageContent(fl, data)
            warningPage(cat, key, data)
            fl.close()
            
        print



################################################################################

def copyFile(path, filename):
    out_path = os.path.join(path, filename)
    if not os.access(out_path, os.F_OK):
        in_fl = file(filename, "rb")
        out_fl = file(out_path, "wb")
        out_fl.write(in_fl.read())
        in_fl.close()
        out_fl.close()
            
#######################################################################

def escapeFiles(text):
    text = text.replace("_", "__")

    ret = ""
    for i in range(len(text)):
    	if (text[i] >= 'A') and (text[i] <= 'Z'):
    		ret += "_"
    	ret += text[i]

    ret = ret.replace("\t", "_09")
    ret = ret.replace("\n", "_0a")
    ret = ret.replace("!", "_21")
    ret = ret.replace("\"", "_22")
    ret = ret.replace("#", "_23")
    ret = ret.replace("$", "_24")
    ret = ret.replace("%", "_25")
    ret = ret.replace("&", "_26")
    ret = ret.replace("'", "_27")
    ret = ret.replace("(", "_28")
    ret = ret.replace(")", "_29")
    ret = ret.replace("*", "_2a")
    ret = ret.replace("+", "_2b")
    ret = ret.replace("/", "_2f")
    ret = ret.replace(":", "_3a")
    ret = ret.replace(",", "_2c")
    ret = ret.replace("<", "_3c")
    ret = ret.replace(">", "_3e")
    ret = ret.replace("?", "_3f")
    ret = ret.replace("\\", "_5c")
    ret = ret.replace("|", "_7c")
    ret = ret.replace(" ", "+")
    
    if (len(ret) == 0) or (ret[0] == '_'): return ret
    else: return '.'+ret

################################################################################

def escapeHTML(text):
    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    text = text.replace(">", "&gt;")
    
    if (text.find("\\") >= 0):
        text = text.replace("\\\\", "&backslash;")
    	text = dddoc_html_trans.translate(text);
        text = text.replace("&backslash;", "\\")

    return text

################################################################################

def escapeJavaScript(text):
    text = text.replace("\\", "\\\\")
    text = text.replace("'", "\\'")
    text = text.replace("\n", " ")
    text = text.replace("\r", "")

    return text

################################################################################

def getFilename(cat, item):
    return cat.upper() + escapeFiles(item) + ".html"

def getIndexpage(cat):
    s = dddoc.DATA["globals.project.indexcategory"].text()
    
    if (s[0:(len(cat))] == cat): 
    	return "index.html"
    else:
    	return "INDEXPAGE" + escapeFiles(cat) + ".html"

def getIndexname(cat, subcat = ""):
    if len(subcat) == 0: return "INDEX" + escapeFiles(cat) + ".html"
    else: return "INDEX" + escapeFiles(cat) + escapeFiles(subcat) + ".html"

def getIndexnameLink(cat, item, subcat = ""):
    if len(subcat) == 0: return "INDEX" + escapeFiles(cat) + ".html#" + item
    else: return "INDEX" + escapeFiles(cat) + escapeFiles(subcat) + ".html#" + item

def getDemoFilename(sourcefile):
    return "DEMO" + escapeFiles(sourcefile) + ".html"

    
################################################################################
    
def translateText(text, line=None):
    ret = ''
    str = ''
    in_code = False
    in_link = False
    in_escaped = False
    pos = 0
    while (pos < len(text)):
        c = text[pos]
        if in_escaped:
            str += c;
            in_escaped = False;
        elif in_code:
            if c == '$':
                if str != '': 
                    ret += translateCode(str)
                    str = ''
                else:
                     str = '$'
                in_code = False
            else: str += c
        elif in_link:
            if c == '@': 
                ret += translateLink(str, line=line)
                str = ''
                in_link = False
            else: str += c
        else:
            if c == '$': 
                if str != '' or pos == 0: 
                    ret += escapeHTML(str)
                    str = ''
                else:
                    str = '$'
                in_code = True
            elif c == '@':
                ret += escapeHTML(str)
                str = ''
                in_link = True
#            elif c == '\\':
#                in_escaped = True
            else:
                str += c;
                
        pos += 1
                
    if str != '':
        ret += escapeHTML(str)

    return ret
    
################################################################################
    
def translateCode(text):
    text = text.strip(" \n\r")
    text = escapeHTML(text)
    text = text.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
    text = text.replace(" ", "&nbsp;")
    text = text.replace("\n", "<br >")
    return '<span class=code><nobr>' + text + '</nobr></span>'
    
################################################################################
    
def translateTooltip(text):
    text = text.replace("\t", " ")
    text = text.replace("\n", " ")
    text = text.replace("$", "")
    text = text.replace("@", "")
    text = text.replace("\"", "&quot;")
    text = text.replace("<", "&lt;")
    text = text.replace("<", "&gt;")
    return text

################################################################################

def brokenLinkText(text):
    """Returns the HTML for a broken link.

    Args:
      text  String to format.

    Returns:
      String, formatted as broken link in HTML.
    """
    return '<span class="broken_link">' + text + '</span>'


def brokenLink(text, line=None):
    """Format the given text as a broken link and print warning.

    If line is not None then the warning includes the source of the
    line to help debugging.

    Args:
      text  String, text to format as broken link.
      line  dddoc.Line object to use as the source.

    Returns:
      String with the HTML for the broken link.
    """
    global WARNING_COUNT
    WARNING_COUNT += 1
    print
    print '!!  WARNING: broken link "' + text + '"'
    if line:
        print '        Location: %s:%d' % (line.file_name, line.line_no)
    # The following is here to debug the source of broken link tags.
    # If you get a broken link message without a source, uncomment the
    # following two lines and add enough "line" parameters to the code
    # so these errors are printed with source the next time.
    #import traceback
    #traceback.print_stack()
    return brokenLinkText(text)


################################################################################

def findGlossary(text):
    global globalGlossary
    
    if globalGlossary.has_key(text):
        return globalGlossary[text][0]
       
    text2 = text.lower() 
    for key in globalGlossary.keys():
        key2 = key.lower()
        if text2.find(key2) == 0:
            return globalGlossary[key][0]
            
    return False
    
################################################################################

def translateLinkDisplaytext(text):
    pos = text.find(':')
    if pos >= 0: 
        protocol = text[:pos]
        rest = text[pos+1:]
    else: 
        protocol = ""
        rest = text

    if (protocol == 'http') or (protocol == 'ftp'):
        arr = dddoc.splitUrl(text)
        return arr[len(arr) - 1]
        
    if (protocol == 'glos'):
        arr = dddoc.splitName(rest)
        if len(arr) == 0: return brokenLinkText(text)
        glos = findGlossary(arr[0])
        if not glos: return brokenLinkText(text)
        if len(arr) == 1: return arr[0]
        return arr[1]
        
    if (protocol == 'nolink'):
        return translateID(rest)

    arr = dddoc.splitName(text)
    if len(arr) == 0: return brokenLinkText(text)

    if (dddoc.DATA["globals.categories"][arr[0]].empty()): return brokenLinkText(text)

    if text.find('.') < 0: #Link to indexpage
        if (dddoc.DATA["globals.indexes"][arr[0]].empty()): return brokenLinkText(text)
        if len(arr) == 1: return getCategoryTitle(arr[0])
        else: return arr[1] 

    if (len(arr) < 2): return brokenLinkText(text)
    
    return translateID(arr[len(arr) - 1])

################################################################################


def translateLink(text, attribs = "", line=None, cat=False):
    global globalDocsPath
    
    pos = text.find(':')
    if pos >= 0: 
        protocol = text[:pos]
        rest = text[pos+1:]
    else: 
        protocol = ""
        rest = text

    #external Link
    if (protocol == 'http') or (protocol == 'ftp'): 
        arr = dddoc.splitUrl(text)
        return '<a href="' + arr[0] + '" ' + attribs + '>' + arr[len(arr) - 1] + '</a>'

    #Glossary Link
    if protocol == 'glos':
        arr = dddoc.splitName(rest)
        if len(arr) == 0: return brokenLink(text, line=line)
        glos = findGlossary(arr[0])
        if not glos: return brokenLink(text, line=line)
        if len(arr) == 1: t = arr[0]
        else: t = arr[1]
        return '<a class=glossary_link ' + glos[2] + t + '</a>'

    #no link    
    if (protocol == 'nolink'):
        return translateID(rest, cat=cat)

    arr = dddoc.splitName(text)
    if len(arr) == 0: return brokenLink(text, line=line)
    
    if (dddoc.DATA["globals.categories"][arr[0]].empty()): return brokenLink(text, line=line)
    
    #Link to Indexpage
    if text.find('.') < 0:
        if (dddoc.DATA["globals.indexes"][arr[0]].empty()): return brokenLink(text, line=line)
        if len(arr) == 1: t = getCategoryTitle(arr[0])
        else: t = arr[1]
        return '<a href="' + getIndexpage(arr[0]) + '" ' + attribs + '>' + t + '</a>'


    #Link to Page
    if (len(arr) < 2): return brokenLink(text, line=line)

    href = getFilename(arr[0], arr[1])

    obj = dddoc.DATA[arr[0]][arr[1]];
    if obj.empty():
        #test existing file
        doc_path = os.path.join(globalDocsPath, href)
        if not os.access(doc_path, os.F_OK): 
            return brokenLink(text, line=line)
        summary = '';
    else:
        summary = translateTooltip(obj["summary"].text());
        
    if len(summary) > 0:
        summary = 'title="' + summary + '"'
    
    return '<a href="' + href + '" ' + summary + ' ' + attribs + '>' + translateID(arr[len(arr) - 1], cat=cat) + '</a>'


################################################################################
    
def translateImage(text):
    in_path = 'img/' + text + '.png'
    global OUT_PATH
    out_path = OUT_PATH + '/' + text + '.png'
    
    if os.access(in_path, os.F_OK):
        in_fl = file(in_path, "rb")
        out_fl = file(out_path, "wb")
        out_fl.write(in_fl.read())
        in_fl.close()
        out_fl.close()
    else:
        global WARNING_COUNT
        WARNING_COUNT += 1
        print
        print "\n!!  WARNING: image not found: \"" + text + ".png\""

    text = escapeHTML(text)
    text = text.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
    text = text.replace(" ", "&nbsp;")
    text = text.replace("\n", "<br >")
    return '<img class=image src="./' + text + '.png" border=0 />'


################################################################################
    
def translateID(text, line=None, cat=False):
    i = text.find('#');
    if (i >= 0):
        if cat:
            text = '%s (%s)' % (text[i + 1:], text[:i])
        else:
            text = text[i + 1:]
    i = text.find('|');
    if (i >= 0):
        text = text[i + 1:]
    return translateText(text, line)

################################################################################
         
def sortingKey(data, key):
    if data["order"].empty():
        return translateID(key)
    
    return data["order"].text();

 
################################################################################

def getBeforeColon(text):
    pos = text.find(':')
    if pos < 0: return text
    else: return text[0: pos]

################################################################################

def getAfterColon(text):
	return text[text.find(':') + 1:len(text)]

################################################################################

def getPageTitle(data):
	s = data["title"].text()
	if not s:
		return translateID(data.name(1))
	else:
		return s
	
################################################################################
	
def getCategoryTitle(cat, show_cat=False):
	s = dddoc.DATA["Indexpage"][cat]["title"].text()
	if (s == ''): 
		return translateID(dddoc.DATA["globals.indexes"][cat].text(), cat=show_cat)
	else:
		return s


################################################################################

def addCollectIndexEntry(data, cat, subcat, key, entries):
    subcat2 = subcat
    while subcat2 != '':
        if not entries.has_key(subcat2): entries[subcat2] = {}
        pos = subcat2.rfind('.')
        if pos < 0: break
        subcat2 = subcat2[:pos]
        
    key4sorting = sortingKey(data, key)
    if not entries[subcat].has_key(key4sorting): entries[subcat][key4sorting] = []
    entries[subcat][key4sorting].append(cat + "." +key)

################################################################################

def collectIndexEntries(cat):
    entries = {}
    entries[''] = {}
    data = dddoc.DATA[cat]
    for key in data.keys():
        entry = data[key]
        if not entry["hidefromindex"].empty(): continue
        if entry["cat"].empty(): addCollectIndexEntry(entry, cat, '', key, entries)
        else:
            for subcat_line in entry["cat"].lines:
                subcat = subcat_line.text()
                addCollectIndexEntry(entry, cat, subcat, key, entries)
                
    return entries

################################################################################

def pageIndexPrintMembers(fl, data):
    # Note that data is not a dddoc.Data object!
    entrs = data.keys()
    entrs.sort()
    for entr in entrs:
        links = data[entr]
        for link in links:
            fl.write('<div class=index_item>' + translateLink(link, "target=_top", cat=True) + '</div>')

################################################################################

def pageIndex(fl, path, cat, subcat, entries, subcats):
    fl.write('<html>')
    fl.write('<head>')
    fl.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8">');
    fl.write('<link rel="stylesheet" href="dddoc_html.css" type="text/css" />')
    fl.write('</head>\n')
    fl.write('<script src="searchfile.js"></script>\n') 
    fl.write('<script src="dddoc.js"></script>\n') 
    fl.write('<body id=index_body>')
    
    lines = dddoc.DATA["globals.indexes"]
    for cat2 in lines.keys_by_occ():
        if cat2 == cat:
            fl.write('<div class=index_section_high>')
        else:
            fl.write('<div class=index_section>')
        fl.write('<div class=index_cat><a class=index_link target=_top href="' + getIndexpage(cat2) + '">' + lines[cat2].text() + '</a></div>')
        if cat2 == cat:
            
            # print subfolder
            this_reached = False
            members_printed = False
            for subcat2 in subcats:
                is_this = (subcat2 == subcat)
                is_sub = ((subcat2.find(subcat) == 0) and (((len(subcat2) > len(subcat)) and (subcat2[len(subcat)] == '.')) or (len(subcat) == 0)))
                is_child = (is_sub and (subcat2.find('.', len(subcat)+1) < 0))
                is_super = (subcat.find(subcat2) == 0)
                has_depth_greater_2 = (subcat2.find('.') >= 0)
                is_sister = not has_depth_greater_2 or (subcat.find(subcat2[0:subcat2.rfind('.')]) == 0)
                
                if not members_printed and this_reached and not is_sub:
                    pageIndexPrintMembers(fl, entries[subcat])
                    members_printed = True
                    
                if is_this:
                    this_reached = True
                
                if (subcat2 != "") and (is_child or is_super or is_sister or is_this):
                    #print out folder
                    indent = ''
                    display_text = subcat2
                    while True:
                        pos = display_text.find('.')
                        if pos < 0: break
                        indent += '&nbsp;&nbsp;'
                        display_text = display_text[pos+1:]
                        
                    if is_super: image = 'dddoc_minus.gif'
                    else: image = 'dddoc_plus.gif'
                        
                    fl.write('<div class=index_subcat>' + indent + '<img src="' + image + '" border=0><a class=index_link href="' + getIndexname(cat, subcat2) + '">' + display_text + '</a></div>')
                    
            if not members_printed:
                pageIndexPrintMembers(fl, entries[subcat]) 
                    
        fl.write('</div>') #index_section or index_section_high
        
    printSearchmask(fl)
    fl.write('</body>')
    fl.write('</html>')

################################################################################

def printSearchmask(fl):
    fl.write('<div id=searchmask>')
    fl.write('<div id=searchtitle>Searching</div>')
    fl.write('<input id=search name=search onKeyUp="updateSearch(this.value);" onBlur="updateSearch(this.value);" autocomplete="off">')
    fl.write('<div id=result></div>')
    fl.write('</div>')

################################################################################

def pageIndexpage(fl, cat):
    fl.write('<html>')
    fl.write('<head>')
    fl.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8">');
    fl.write('<link rel="stylesheet" href="dddoc_html.css" type="text/css" />')
    fl.write('<title>' + getCategoryTitle(cat) + '</title>')
    fl.write('</head>')
    fl.write('<body>')
    fl.write('<table id=main_table cellspacing=0 cellpadding=0>')
    fl.write('<tr><td valign=top>')
    fl.write('<iframe frameborder=0 id=navigation src="' + getIndexname(cat) + '"></iframe>')
    fl.write('</td><td valign=top>')
    fl.write('<div id=content>')

    #s = dddoc.DATA["globals.indexes"][cat].text()
    fl.write('<div class=indexpage_title>' + getCategoryTitle(cat) + '</div>')

    data = dddoc.DATA["Indexpage"][cat]

    printSummary(fl, data, "summary")

    for line in data.at_level(0).lines:
        s = translateText(line.text())
        if (s): fl.write('<div class=text>' + s + '</div>')

    printTextblock(fl, data, "description")
    printTextblock(fl, data, "remarks")
    printIndexpageMembers(fl, dddoc.DATA[cat])
    printTextblock(fl, data, "example")
    printLink(fl, data, "demo")
    printLink(fl, data, "see")

    pageEnd(fl, data)
    fl.write('</div>')
    fl.write('</td></tr>')
    fl.write('</table>')
    fl.write('<p style="font-size:50%%; color: #909090">Page built @%s</p>' %
             datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
    fl.write('</body>')
    fl.write('</html>')

################################################################################

def addIndexPageMembers(data, key, entries, subcat):
    if not entries.has_key(subcat): 
        entries[subcat] = {}
        
    s = '<tr><td class=value_key valign=top><nobr>'
    s += '<a href="' + getFilename(data.name(0), key) + '">' + translateID(key, cat=True) + '</a>'
    s += '</nobr></td><td class=value_text valign=top>'

    summary = translateText(data[key]["summary"].text())
    if summary: s += summary
    else: s += '&nbsp;'
    
    s += '</td></tr>'
    
    key4sorting = sortingKey(data[key], key)
    if not entries[subcat].has_key(key4sorting): entries[subcat][key4sorting] = ''
    entries[subcat][key4sorting] += s

################################################################################

def printIndexpageMembers(fl, data):
    keys = data.keys()
    if len(keys) > 0:

        entries = {}
        for key in keys:
            if not data[key]["hidefromindex"].empty():
                continue

            linelist = data[key]["cat"].lines
            if (linelist == []):
                addIndexPageMembers(data, key, entries, "")
            else:
                for line in linelist:
                    addIndexPageMembers(data, key, entries, line.text())
                           
        keys2 = entries.keys();
        keys2.sort();

        for key in keys2:
            fl.write('<div class=section>')
            
            if key != "":
                s = key.replace('.', ': ')
                fl.write('<div class=section_headline>' + s + '</div>')
            else:
                s = dddoc.DATA["globals.indexes"][data.name(0)].text()
                if s: fl.write('<div class=section_headline>' + s + '</div>')
                
            fl.write('<table class=indexpage_members_tab cellspacing=0 cellpadding=0>')
            
            entry_keys = entries[key].keys();
            entry_keys.sort();
            for entry in entry_keys:
                fl.write(entries[key][entry])
            fl.write('</table>')
        
            fl.write('</div>')

################################################################################

def pageContent(fl, data):
    pageBegin(fl, data)
    fl.write('<table id=main_table cellspacing=0 cellpadding=0>')
    fl.write('<tr><td valign=top>')
    
    cat = "Class"
    item = ""
    if ((data.name(0) == 'Memfunc') or (data.name(0) == 'Memvar') or (data.name(0) == 'Typedef')):
        arr = dddoc.splitName(data["class"].text())
        if (len(arr) > 2): item = arr[1]
#    elif data.name(0) == 'Spec':
#        arr = dddoc.splitName(data["general"].text())
#        if (len(arr) > 2): item = arr[1]
    else:
        cat = data.name(0)
        item = data.name(1)
    
    subcats = dddoc.DATA[cat][item]["cat"].lines
    subcat = ""
    if (len(subcats) > 0): subcat = subcats[0].text()
    
    fl.write('<iframe frameborder=0 id=navigation src="' + getIndexnameLink(cat, item, subcat) + '"></iframe>')
    fl.write('</td><td valign=top>')
    fl.write('<div id=content>')
    writePage(fl, data)
    pageEnd(fl, data)
    fl.write('</div>')
    fl.write('</td></tr>')
    fl.write('</table>')
    fl.write('<p style="font-size:50%%; color: #909090">Page built @%s</p>' %
             datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
    fl.write('</body>')
    fl.write('</html>')

################################################################################

def pageBegin(fl, data):
    fl.write('<html>')
    fl.write('<head>')
    fl.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8">');
    fl.write('<link rel="stylesheet" href="dddoc_html.css" type="text/css" />')
    fl.write('<title>' + getPageTitle(data) + '</title>')
    fl.write('</head>')
    fl.write('<body>')

################################################################################

def pageEnd(fl, data):
    s = dddoc.DATA["globals.project.footline"].text()
    fl.write('<div class=page_footline>' + s + '</div>')
    fl.write('<div id=page_widthblock>&nbsp;</div>')
    
################################################################################

def writePage(fl, data):
    printTitle(fl, data)
    printSummary(fl, data, "summary")
    
    for line in data.at_level(0).lines:
        s = translateText(line.text())
        if (s): fl.write('<div class=text>' + s + '</div>')
           
    printTextblock(fl, data, "description")
    printGlossary(fl, data, "glossary")
    
    printTree(fl, data)

    printConcept(fl, data)

    printSignature(fl, data, "signature")
    printList(fl, data, "include")
    printTable(fl, data, "param")
    printTextblock(fl, data, "remarks")
    printTextblock(fl, data, "status")
    printTextblock(fl, data, "returns")
    printLink(fl, data, "class")
    printLink(fl, data, "general")
    printShortcutfor(fl, data, "shortcutfor")
    printLinkRek(fl, data, "implements")

    printMemberRek(fl, data, "conceptimplements")
    printLinkRek(fl, data, "conceptusedbymeta")
    printLinkRek(fl, data, "conceptusedbyfunc")

    printMember(fl, data, "spec")
    printMemberRek(fl, data, "type")
    printMemberRek(fl, data, "typedef")
    printMemberRek(fl, data, "memvar")
    printMemberRek(fl, data, "memfunc")
    printMemberRek(fl, data, "function")
    
    printTable(fl, data, "value")
    printTable(fl, data, "tag")

    printMember(fl, data, "shortcut")

    printTextblock(fl, data, "example")
    printLinkRek(fl, data, "demo")
    printFile(fl, data, "file")
    printSnippet(fl, data, "snippet")
    printTextblock(fl, data, "output")
    
    printLink(fl, data, "concept")
    printLink(fl, data, "demofor")
    printLink(fl, data, "see")

################################################################################

def printConcept(fl, data):
    
    if data["baseconcept"].empty() and data["childconcept"].empty() and data["conceptmetafunc"].empty() and data["conceptmemvar"].empty() and data["conceptmemfunc"].empty() and data["conceptfunc"].empty() and data["concepttypedef"].empty(): return
    
    fl.write('<div id=define_concept>')
    
    s = dddoc.DATA["globals.sections.conceptdefinition"].text()
    if s: fl.write('<div class=define_concept_headline>' + s + '</div>')
    
    printLink(fl, data, "baseconcept")
    printMemberRek(fl, data, "conceptmetafunc")
    printMemberRek(fl, data, "concepttypedef")
    printMemberRek(fl, data, "conceptmemvar")
    printMemberRek(fl, data, "conceptmemfunc")
    printMemberRek(fl, data, "conceptfunc")
    printMember(fl, data, "childconcept")
    
    fl.write('</div>')
    
################################################################################

def printTitle(fl, data):
    s = dddoc.DATA["globals.categories"][data.name(0)].text()
    if s: fl.write('<div class=page_category>' + s + '</div>')
    fl.write('<div class=page_title>' + getPageTitle(data) + '</div>')


################################################################################

def printText(fl, data, category):
    lines = data[category]
    if not lines.empty():
        for line in lines.lines:
            s = translateText(line.text())
            if s: fl.write('<div class=text>' + s + '</div>')
   

################################################################################

def printSummary(fl, data, category):
    fl.write('<div id=summary>')
    printText(fl, data, category)
    fl.write('</div>')


################################################################################

def printSignature(fl, data, category):
    lines = data[category]
    if not lines.empty():
        fl.write('<div class=section id=' + category + '>')
        
        for line in lines.lines:
            s = translateCode(line.text())
            if s: fl.write('<div class=signature_block><nobr>' + s + '</nobr></div>')

        fl.write('</div>');


################################################################################

def printTableContent(fl, data, category):
    lines = data[category]
    if not lines.empty():
        
        keys = lines.keys_by_occ()
        if len(keys) > 0:         
            fl.write('<table class=value_tab cellspacing=0 cellpadding=0>')
    
            for key in keys:
                fl.write('<tr><td class=value_key valign=top><nobr>' + key + '</nobr></td><td class=value_text valign=top>')
                subprintText(fl, lines[key])
                fl.write('</td></tr>')
            fl.write('</table>')
            
################################################################################


def printTable(fl, data, category, showheadline = True):
    lines = data[category]
    if not lines.empty():
        fl.write('<div class=section id=' + category + '>')
        
        if showheadline:
            s = dddoc.DATA["globals.sections"][category].text()
            if s: fl.write('<div class=section_headline>' + s + '</div>')
        
        s = translateText(lines.text())
        if s: fl.write('<div class=text_block>' + s + '</div>')
    
        printTableContent(fl, data, category)

        fl.write('</div>');
  
################################################################################

def findDataRek(data, field, lines, map):
    highlight = False
    
    lines.extend(data[field].lines)

    for line in lines:
        map[line.text()] = ''
        
    follows = dddoc.DATA["globals.inherit"][field]
    for follow in follows.keys():
        follow_field = follows[follow].text()
        if follow_field.strip() == "": follow_field = field
        
        followups = data[follow].lines
        for followup in followups:
            dataup = dddoc.DATA[followup.text()]
            
            submap = {}
            findDataRek(dataup, follow_field, lines, submap)
            
            for key in submap.keys():
                if not map.has_key(key): 
                    origin = submap[key]
                    if origin == '': origin = followup.text()
                    map[key] = origin
                    highlight = True
        
    return highlight
      
################################################################################

def printMemberOut(fl, data, category, lines, derivedfrom, highlight, showheadline = True):
    if len(lines) > 0:
        fl.write('<div class="section" id="' + category + '">')

        if showheadline:
            s = dddoc.DATA["globals.sections"][category].text()
            if s: fl.write('<div class="section_headline">' + s + '</div>')
        
        fl.write('<table class="value_tab" cellspacing="0" cellpadding="0">')

        # Sort lines by their display link text and iterate over them.
        keyed_lines = dict([(translateLinkDisplaytext(line.text()).lower(), line) for line in lines])
        for key in sorted(keyed_lines.keys()):
            line = keyed_lines[key]
            text = line.text()
            origin = ''
            do_highlight = highlight
            if derivedfrom.has_key(text) and len(derivedfrom[text]) > 0: 
                origin = ' (' + translateLink(derivedfrom[text], line=line) + ')'
                do_highlight = False
                
            if do_highlight: tag_class = 'value_key_high'
            else: tag_class = 'value_key'

            link = translateLink(text, line=line)
            fl.write('<tr><td class="' + tag_class + '" valign="top"><nobr>' + link + '</nobr></td><td class="value_text" valign="top">')
                
            summary = translateText(dddoc.DATA[text]["summary"].text()) + origin
            if summary: fl.write(summary)
            else: fl.write('&nbsp;')
            
            fl.write('</td></tr>')
                
        fl.write('</table>')
            
        fl.write('</div>');

################################################################################

def printMember(fl, data, category, showheadline = True):
    lines = data[category].lines
    printMemberOut(fl, data, category, lines, {}, False, showheadline)

################################################################################

def printMemberRek(fl, data, category, showheadline = True):
    lines = []
    map = {}
    highlight = findDataRek(data, category, lines, map)
    
    printMemberOut(fl, data, category, lines, map, highlight, showheadline)
    

################################################################################

def printLinkOut(fl, data, category, lines, derivedfrom, highlight, showheadline = True):
    if not lines:
        return  # Nothing to do if no lines are given.
    fl.write('<div class="section" id="%s">' % category)

    if showheadline:
        s = dddoc.DATA["globals.sections"][category].text()
        if s: fl.write('<div class="section_headline">' + s + '</div>')

    my_dict = dict([(translateLinkDisplaytext(line.text()).lower(), line) for line in lines])
    str = ''
    for key, line in my_dict.iteritems():
        link = line.text()
        if (link == ''): continue
        origin = ''
        do_highlight = highlight
        if derivedfrom.has_key(link) and len(derivedfrom[link]) > 0: 
            origin = ' (' + translateLink(derivedfrom[link], line=line) + ')'
            do_highlight = False

        if do_highlight: tag_class = 'link_text_high'
        else: tag_class = 'link_text'

        s = translateLink(link, line=line)
        if s:
            if (str != ''): str += ', '
            str += '<span class="' + tag_class + '">' + s + '</span>'

    if (str != ''):
        fl.write('<div class="text_block">' + str + '</div>')

    fl.write('</div>')

################################################################################

def printLink(fl, data, category, showheadline = True):
    lines = data[category].at_level().lines
    printLinkOut(fl, data, category, lines, {}, False, showheadline)

################################################################################

def printLinkRek(fl, data, category, showheadline = True):
    lines = []
    map = {}
    highlight = findDataRek(data, category, lines, map)
    
    printLinkOut(fl, data, category, lines, map, highlight, showheadline)


################################################################################

def printList(fl, data, category, showheadline = True):
    lines = data[category]
    if not lines.empty():
        fl.write('<div class=section id=' + category + '>')

        if showheadline:
            s = dddoc.DATA["globals.sections"][category].text()
            if s: fl.write('<div class=section_headline>' + s + '</div>')

        map = {}
        for line in lines.lines:
            map[line.text()] = 1
        
        str = ''
        texts = map.keys()
        texts.sort()
        for text in texts:
            if (str != ''): str += ', '
            str += text
                
        if (str != ''):
            fl.write('<div class=text_block>' + str + '</div>');

        fl.write('</div>');

################################################################################

def printShortcutfor(fl, data, category, showheadline = True):
    printLink(fl, data, category, showheadline)
    printSignature(fl, data[category], "signature")

################################################################################

def printTextblock(fl, data, category, showheadline = True):
    lines = data[category]
    if not lines.empty():
        fl.write('<div class=section id=' + category + '>')
        
        if showheadline:
            s = dddoc.DATA["globals.sections"][category].text()
            if s: fl.write('<div class=section_headline>' + s + '</div>')
        
        fl.write('<div class=text_block>')
        subprintText(fl, lines)
        fl.write('</div>')
            
        fl.write('</div>');


################################################################################

def printGlossary(fl, data, category):
    lines = data[category]
    if not lines.empty():
        fl.write('<div class=section id=' + category + '>')
        
        keys = lines.keys()
        if len(keys) > 0:         
            for key in keys:
                fl.write('<div class=glossary_entry>')
                fl.write('<a name="GLOSSARY' + escapeFiles(key) + '"></a>')
                fl.write('<div class=glossary_title>' + translateText(key) + '</div>')
                fl.write('<div class=glossary_content>')
                subprintText(fl, lines[key])
                fl.write('</div>')
                fl.write('</div>')

        fl.write('</div>');


################################################################################

def printFile(fl=None, data=None, category=None, text=None):
    # Note: This somehow works on the demos page.
    global globalDocsPath
    global includeDirs

    if fl is not None:
        filename = data[category].text()
    else:
        filename = text

    filename = filename.replace("\n", "")
    filename = filename.replace("\\", "/")

    # Return if the file name is empty.
    if not filename:
        return

    # Try to build the file name from the include dirs.
    for prefix in ['.'] + includeDirs:
        filenameCandidate = os.path.join(prefix, filename)
        if os.access(filenameCandidate, F_OK):
            filename = filenameCandidate
            break

    # Return if we cannot open the file.
    if (not os.access(filename, F_OK)):
        global WARNING_COUNT
        WARNING_COUNT += 1
        print
        print '!!  WARNING: unknown file "' + filename + '"'
        return

    # Read in file...
    f = open(filename)
    lines = f.readlines()
    f.close()

    linenumber = 0  # Of code, non-comment.
    codemode = False

    pos = filename.rfind("/")
    if (pos >= 0): 
        s = filename[pos+1:]
    else: 
        s = filename

    #copy file
    f_out = open(os.path.join(globalDocsPath, s), "w")

    fl_none = False
    if fl is None:
        fl_none = True
        fl = StringIO.StringIO()

    fl.write('<div class=section_headline>File "<a href="' + s + '">' + s + '</a>"</div>')

    fl.write('<div class=codefile >')
    line_no = 0  # Absolute in file.
    for line in lines:
        line_no += 1
        is_comment = (line[0:3] == '///')

        if is_comment:
            if codemode:
                fl.write('</table><div class=comment>')    
                codemode = False
            line_obj = dddoc.Line([], line, filename, line_no)
            fl.write(translateText(line[3:], line_obj))

        else:
            if not codemode:
                if (len(line) <= 1): continue
                if linenumber: fl.write('</div>')
                fl.write('<table cellspacing=0 cellpadding=0 class=codefiletab>')
                codemode = True

            linenumber += 1

            fl.write('<tr>')
            fl.write('<td align=right class=linenumber>')
            fl.write(str(linenumber))
            fl.write('</td>')

            text = escapeHTML(line)
            text = text.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
            text = text.replace(" ", "&nbsp;")
            text = text.replace("\n", "<br >")
            fl.write('<td class=content><nobr>')
            fl.write(text)
            fl.write('</nobr></td>')        

            fl.write('</tr>')

            f_out.write(line)

    if codemode:
        fl.write('</table>')
    else:
        fl.write('</div>')

    fl.write('</div>')    

    f_out.close

    if fl_none:
        return fl.getvalue()

################################################################################

def _loadSnippet(path, snippet_key):
    result = []
    current_key = None
    current_lines = []
    with open(path, 'rb') as f:
        fcontents = f.read()
    for line in fcontents.splitlines():
        line = line.rstrip()  # Strip line ending and trailing whitespace.
        if line.strip().startswith('//![') and line.strip().endswith(']'):
            key = line.strip()[4:-1].strip()
            if key == current_key:
                if key == snippet_key:
                    result = current_lines
                current_lines = []
                current_key = None
            else:
                current_key = key
        elif current_key:
            current_lines.append(line)
    return result

def printSnippet(fl=None, data=None, category=None, text=None):
    # Note: This somehow works on the demos page.
    global globalDocsPath
    global includeDirs

    if text is None:
        filename = data[category].text()
    else:
        filename = text

    filename = filename.replace("\n", "")
    filename = filename.replace("\\", "/")

    # Return if the file name is empty.
    if not filename:
        return
    #import pdb; pdb.set_trace()

    snippet_id = '<none>'
    if '|' in filename:
        filename, snippet_id = filename.split('|', 1)

    # Try to build the file name from the include dirs.
    for prefix in ['.'] + includeDirs:
        filenameCandidate = os.path.join(prefix, filename)
        if os.access(filenameCandidate, F_OK):
            filename = filenameCandidate
            break

    # Return if we cannot open the file.
    if (not os.access(filename, F_OK)):
        global WARNING_COUNT
        WARNING_COUNT += 1
        print
        print '!!  WARNING: unknown file "' + filename + '"'
        return

    # Read in file...
    lines = _loadSnippet(filename, snippet_id)

    if not lines:
        print
        print '!!  WARNING: unknown snippet "' + snippet_id + '" in "' + filename + '"'
        return

    linenumber = 0  # Of code, non-comment.
    codemode = False

    pos = filename.rfind("/")
    if (pos >= 0): 
        s = filename[pos+1:]
    else: 
        s = filename

    #copy file
    with open(os.path.join(globalDocsPath, s), "w") as f_out:
        with open(filename, 'rb') as f2:
            f_out.write(f2.read())

    fl_none = False
    if fl is None:
        fl_none = True
        fl = StringIO.StringIO()
            
    fl.write('<div class=codefile >')
    line_no = 0  # Absolute in file.
    for line in lines:
        line_no += 1
        is_comment = (line[0:3] == '///')

        if is_comment:
            if codemode:
                fl.write('</table><div class=comment>')    
                codemode = False
            line_obj = dddoc.Line([], line, filename, line_no)
            fl.write(translateText(line[3:], line_obj))

        else:
            if not codemode:
                if (len(line) <= 1): continue
                if linenumber: fl.write('</div>')
                fl.write('<table cellspacing=0 cellpadding=0 class=codefiletab>')
                codemode = True

            linenumber += 1

            fl.write('<tr>')
            fl.write('<td align=right class=linenumber>')
            fl.write(str(linenumber))
            fl.write('</td>')

            text = escapeHTML(line)
            text = text.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
            text = text.replace(" ", "&nbsp;")
            text = text.replace("\n", "<br >")
            fl.write('<td class=content><nobr>')
            fl.write(text)
            fl.write('</nobr></td>')        

            fl.write('</tr>')

    if codemode:
        fl.write('</table>')
    else:
        fl.write('</div>')

    fl.write('</div>')    
    fl.write('<div class=section_headline>Snippet from "<a href="' + s + '">' + s + '</a>"</div>')

    if fl_none:
        return fl.getvalue()


################################################################################

def subprintText(fl, data, subcategory = False):
    if data.empty():
        return
        
    headline = ''
    if subcategory:
        s = dddoc.DATA["globals.subsections"][subcategory].text()
        if s: headline = '<span class=section_sub_headline>' + s + '</span>'
    
    subprintText(fl, data["summary"])    

    for line in data.at_level(0).lines:
        s = translateText(line.text())
        if s: 
            fl.write('<div class=text_sub_block>' + headline + ' ' + s + '</div>')
            headline = ''
            
    in_table = False
#    in_ol = False
            
    section_cout = 0
    subsection_cout = 0
    
    for line in data.at_level(1).by_occ().lines:
        name = line.name(data.level)
        
        if (name == 'table') or (name == 'tableheader'):
            if not in_table:
                fl.write('<table class=table_explicite cellspacing=0 cellpadding=0>')
            subprintTableLine(fl, line.text(), (name == 'tableheader'), line)
            in_table = True
        else:
            if in_table:
                fl.write('</table>')
            in_table = False

#        if name == 'enumerate':
#            if not in_ol:
#                fl.write('<ol>')
#            fl.write('<li>' + translateText(line.text()))
#            in_ol = True
#        else:
#            if in_ol:
#                fl.write('</ol>')
#            in_ol = False
            
        if name == 'contents':
            subprintContents(fl, data)
            
        elif name == 'section': 
            section_cout += 1
            subsection_cout = 0
            t = translateSection(line.text(), section_cout)
            fl.write('<div class=section_headline_explicite><a name="' + t + '"></a>' + t + '</div>')
            headline = ''
            
        elif name == 'subsection': 
            subsection_cout += 1
            t = translateSubsection(line.text(), section_cout, subsection_cout)
            fl.write('<div class=section_sub_headline_explicite><a name="' + t + '"></a>' + t + '</div>')
            headline = ''
            
        elif name == 'text': 
            s = translateText(line.text(), line=line)
            fl.write('<div class=text_sub_block>' + headline + ' ' + s + '</div>')
            headline = ''
            
        elif name == 'code': 
            s = translateCode(line.text())
            fl.write('<div class=code_sub_block>' + s + '</div>')
            
        elif name == 'snippet':
            s = printSnippet(text=line.text())
            if s:
                fl.write(s)
            
        elif name == 'file':
            s = printFile(text=line.text())
            if s:
                fl.write(s)
            
        elif name == 'output':
            s = translateCode(line.text())
            fl.write('<div class=output_sub_block>' + s + '</div>')
            
        elif name == 'image': 
            subprintImage(fl, line.text())
            
        elif name == 'note':
            s = dddoc.DATA["globals.subsections.note"].text()
            s = '<span class=section_sub_headline>' + s + '</span> '
            s += translateText(line.text())
            fl.write('<div class=note_sub_block>' + s + '</div>')
            
        elif name == 'field':
            subprintField(fl, line.text())

            
    if in_table:
        fl.write('</table>')
       
    subprintLink(fl, data["metafunction"], "metafunction")
    subprintConceptAndType(fl, data)
    subprintText(fl, data["value"], "value")
    subprintText(fl, data["default"], "default")
    printTableContent(fl, data, "param")
    subprintText(fl, data["remarks"], "remarks")    
    subprintLink(fl, data["see"], "see")


################################################################################

def translateSection(text, section_count):
    i = text.find('#')
    if (i >= 0):
        text = text[:i] + str(section_count) + text[i+1:]
    return translateText(text);

################################################################################

def translateSubsection(text, section_count, subsection_count):
    text = translateText(text)
    i = text.find('#')
    if (i >= 0):
        j = text.find('#', i+1)
        if (j >= 0):
            text = text[:i] + str(section_count) + text[i+1:j] + str(subsection_count) + text[j+1:]
        else:
            text = text[:i] + str(subsection_count) + text[i+1:]
    return translateText(text);

################################################################################

def getLinkList(data_lines, not_name_types = {}):
    pairs = [(translateLinkDisplaytext(line.text()).lower(), line) for line in data_lines]
    
    str = ''
    
    for key, line in sorted(pairs):
        link = line.text()
        if not_name_types.has_key(link): continue
        s = translateLink(link, line=line)
        if s:
            if (str != ''): str += ', '
            str += s
            
    return str

################################################################################

def subprintLink(fl, data, subcategory):                         
    if data.empty():
        return
        
    headline = ''
    if subcategory:
        s = dddoc.DATA["globals.subsections"][subcategory].text()
        if s: headline = '<span class=section_sub_headline>' + s + '</span>'
        
    str = getLinkList(data.lines)
            
    if (str != ''):
        fl.write('<div class=text_sub_block>' + headline + ' ' + str + '</div>')

################################################################################


def subprintConceptAndType(fl, data):    
    not_name_types = {}
    type_title = ''

    #display concepts
    c_data = data["concept"]
    t_data = data["type"]
    
    if not c_data.empty():
        if len(c_data.lines) + len(t_data.lines) == 1: tag = 'span'
        else: tag = 'div'
        
        fl.write('<div class=text_sub_block id=concept_block>');

        title = dddoc.DATA["globals.subsections.concept"].text()
        if title: fl.write('<' + tag + ' class=section_sub_headline>' + title + '</' + tag + '> ')
        
        pairs = [(translateLinkDisplaytext(line.text()).lower(), line) for line in c_data.lines]
        for key, line in sorted(pairs):
            link = line.text()
            str_concept = translateLink(link, line=line)
            if str_concept:
                lines = []
                findDataRek(dddoc.DATA[link], "conceptimplements", lines, {})
                str_types = getLinkList(lines)
                if (str_types != ''): str_types = ': ' + str_types
                fl.write('<' + tag + ' class=text_sub_block>' + str_concept + str_types + '</' + tag + '>')
                
                for lin in lines:
                    not_name_types[lin.text()] = 1
                
        subprintType(fl, t_data, '', not_name_types)
        
        fl.write('</div>')
        
    else:
        s = dddoc.DATA["globals.subsections.type"].text()
        if s: type_title = '<span class=section_sub_headline>' + s + '</span> '
        
        subprintType(fl, t_data, type_title, not_name_types)


################################################################################

def subprintType(fl, data, headline, not_name_types):                         
    if data.empty():
        return
        
    str = getLinkList(data.lines, not_name_types)
            
    if (str != ''):
        fl.write('<div class=text_sub_block>' + headline + ' ' + str + '</div>')


################################################################################

def subprintTableLine(fl, text, is_header, line=None):
    fl.write('<tr>')

    t = ''

    while len(text) > 0:
        i = text.find('|');
        j = text.find('@');

        if (j >= 0) and (j < i):
            j2 = text.find('@', j+1)
            if (j2 >= 0):
                t += text[:j2+1]
                text = text[j2+1:]
                continue;

        if (i >= 0):
            t += text[:i]
            text = text[i+1:]
        else:
            t += text
            text = ''
        
        if len(t) > 0: 
            t = translateText(t, line=line)
        else: 
            t = '&nbsp;'

        if is_header:
            fl.write('<td class=table_header_explicite valign=top><center>' + t + '</center></td>')
        else:
            fl.write('<td class=table_cell_explicite valign=top>' + t + '</td>')
        
        t = ''
        
    fl.write('</tr>')

################################################################################

def subprintImage(fl, text):
    t = ''
    s1 = ''
    s2 = ''
    is_image = True
    
    while len(text) > 0:
        i = text.find('|');
        j = text.find('@');
        
        if (j >= 0) and (j < i):
            j2 = text.find('@', j+1)
            if (j2 >= 0):
                t += text[:j2+1]
                text = text[j2+1:]
                continue;
        
        if i >= 0:
            t += text[:i]
            text = text[i+1:]
        else:
            t += text
            text = ''
        
        if len(t) > 0:
            if is_image:
                s1 += '<td>' + translateImage(t) + '</td>'
            else:
                s2 += '<td valign=top align=left class=image_sub_block_caption>' + translateText(t) + '</td>'
        else:
            if is_image:
                s1 += '<td>&nbsp;</td>'
            else:
                s2 += '<td>&nbsp;</td>'
        
        t = ''
        is_image = not is_image
        
    s = '<center><table cellspacing=0 cellpadding=0 border=0><tr>' + s1 + '</tr><tr>' + s2 + '</tr></table></center>'
    fl.write('<div class=image_sub_block>' + s + '</div>')

################################################################################

def subprintContents(fl, data):
    s = ''
    
    section_cout = 0
    subsection_cout = 0
    
    for line in data.at_level(1).by_occ().lines:
        name = line.name(data.level)
        
        if name == 'section':
            section_cout += 1
            subsection_cout = 0
            t = translateSection(line.text(), section_cout)
            s += '<div class=contents_section><a href="#' + t + '">' + t + '</a></div>'
            headline = ''
            
        if name == 'subsection': 
            subsection_cout += 1
            t = translateSubsection(line.text(), section_cout, subsection_cout)
            s += '<div class=contents_subsection><a href="#' + t + '">' + t + '</a></div>'
            headline = ''
    
    
    t = dddoc.DATA["globals.subsections.contents"].text()
    if t: s = '<div class=contents_headline><center>' + t + '</center></div>' + s
    
    fl.write('<div class=contents>' + s + '</div>');

################################################################################

def subprintField(fl, text):
    i = text.rfind('.')
    entry = text[:i]
    field = text[i+1:]

    data = dddoc.DATA[entry]

    if   (field == "description"): printTextblock(fl, data, "description", False)
    elif (field == "signature"): printSignature(fl, data, "signature")
    elif (field == "param"): printTable(fl, data, "param", False)
    elif (field == "returns"): printTextblock(fl, data, "returns", False)
    elif (field == "class"): printLink(fl, data, "class", False)
    elif (field == "general"): printLink(fl, data, "general", False)
    elif (field == "shortcutfor"): printShortcutfor(fl, data, "shortcutfor", False)
    elif (field == "implements"): printLinkRek(fl, data, "implements", False)
    elif (field == "baseconcept"): printLink(fl, data, "baseconcept", False)

    elif (field == "spec"): printMember(fl, data, "spec", False)
    elif (field == "shortcut"): printMember(fl, data, "shortcut", False)
    elif (field == "type"): printMemberRek(fl, data, "type", False)
    elif (field == "typedef"): printMemberRek(fl, data, "typedef", False)
    elif (field == "memvar"): printMemberRek(fl, data, "memvar", False)
    elif (field == "memfunc"): printMemberRek(fl, data, "memfunc", False)
    elif (field == "function"): printMemberRek(fl, data, "function", False)
    
    elif (field == "childconcept"): printMember(fl, data, "childconcept", False)
    elif (field == "conceptimplements"): printMemberRek(fl, data, "conceptimplements", False)
    elif (field == "conceptmetafunc"): printMemberRek(fl, data, "conceptmetafunc", False)
    elif (field == "concepttypedef"): printMemberRek(fl, data, "concepttypedef", False)
    elif (field == "conceptmemvar"): printMemberRek(fl, data, "conceptmemvar", False)
    elif (field == "conceptmemfunc"): printMemberRek(fl, data, "conceptmemfunc", False)
    elif (field == "conceptfunc"): printMemberRek(fl, data, "conceptfunc", False)
    
    elif (field == "value"): printTable(fl, data, "value", False)

    elif (field == "conceptusedbymeta"): printLinkRek(fl, data, "conceptusedbymeta", False)
    elif (field == "conceptusedbyfunc"): printLinkRek(fl, data, "conceptusedbyfunc", False)

    elif (field == "remarks"): printTextblock(fl, data, "remarks", False)
    elif (field == "example"): printTextblock(fl, data, "example", False)
    elif (field == "demo"): printLinkRek(fl, data, "demo", False)
    elif (field == "file"): printFile(fl, data, "file")
    elif (field == "snippet"): printSnippet(fl, data, "snippet")
    
    elif (field == "concept"): printLink(fl, data, "concept", False)
    elif (field == "status"): printTextblock(fl, data, "status", False)
    elif (field == "include"): printList(fl, data, "include", False)
    elif (field == "demofor"): printLink(fl, data, "demofor", False)
    elif (field == "see"): printLink(fl, data, "see", False)


        

################################################################################

def gatherGlossary():
    global globalGlossary 
    
    globalGlossary = {}
    got_it = {}
    
    print "Gather Glossary:",
    
    lines = dddoc.DATA.lines;
    for line in lines:
        key = line.name(3)
        if (line.name(2) == 'glossary') and (key != '(unknown)'):
            fname = line.name(0) + '.' + line.name(1) + '.glossary.' + key
            if not got_it.has_key(fname):
                got_it[fname] = 1
                print ".",
               
                href = getFilename(line.name(0), line.name(1)) + '#GLOSSARY' + escapeFiles(key)
                link = 'href="' + href + '" title="' + escapeJavaScript(dddoc.DATA[fname].text()) + '">'
                
                if not globalGlossary.has_key(key):  globalGlossary[key] = []
                globalGlossary[key].append([key, '(Glossary)', link])
                
    print

################################################################################

def createSearchfile(path):
    print 'Create Searchfile'
    
    global globalGlossary
    
    db = globalGlossary
    
    cats = dddoc.DATA["globals.categories"].keys()
    for cat in cats:
        entries = dddoc.DATA[cat]
        title = getCategoryTitle(cat).lower()
        pushSearchResult(db, title, cat, "")
       
        for key in entries.keys():
            data = entries[key]
            title = getPageTitle(data).lower()
            pushSearchResult(db, title, cat, key)

    searchfile = os.path.join(path, "searchfile.js")
    fl = file(searchfile, "w")
    
    fl.write('var DB = [\n')

    keys = db.keys()
    keys.sort()
    for key in keys:
        if len(key) > 0:
            for entry in db[key]:
                fl.write('[\'' + escapeJavaScript(entry[0]) + '\', \'' + escapeJavaScript(entry[1]) + '\', \'' + escapeJavaScript(entry[2]) + '\'],\n')
            
    fl.write('false];\n')
    fl.close()

################################################################################

def pushSearchResult(db, title, cat, name):
    if (len(name) == 0):
        link = '<a target=_parent href="' + getIndexpage(cat) + '">'
        key = getCategoryTitle(cat)
        text = ''
        
    else:
        obj = dddoc.DATA[cat][name]
        href = getFilename(cat, name)
        if obj.empty(): 
            summary = '';
        else:
            summary = translateTooltip(obj["summary"].text())
        if len(summary) > 0:
            summary = 'title="' + summary + '"'
        
        link = 'href="' + href + '" ' + summary + '>'
        key = translateID(name, cat=True)
        text =  '(' + cat + ')'

    if not db.has_key(title): db[title] = []
    db[title].append([key, text, link])

################################################################################

def warningPage(cat, key, data):
    # Warning for multiple or no summary field.
    global globalBuildFull
    global WARNING_COUNT
    if globalBuildFull: # only if full documentation is built
        desc = data["summary"]
        if desc.empty():
            WARNING_COUNT += 1
            print
            print "\n!!  WARNING: no summary field for \"" + cat + "." + key + "\""
            print '        Location: %s:%d' % (data.lines[0].file_name, data.lines[0].line_no)
        elif len(desc.lines) > 1:
            WARNING_COUNT += 1
            print
            print "\n!!  WARNING: multiple summary fields for \"" + cat + "." + key + "\""
            for line in desc.lines:
                print '        Location: %s:%d' % (line.file_name, line.line_no)

    # Warning for break of naming convention.
    convention = dddoc.DATA["globals.namingconventions"][cat].text()
    title = getPageTitle(data)
    
    if (convention == 'bigsmall' and ((title[0] < 'A') or (title[0] > 'Z'))):
        # Ugly hack: Allowing to violate bigsmall convention for tag groups that
        # have the substring ' Tags'
        if ' Tags' not in title:
            WARNING_COUNT += 1
            print
            print "\n!!  WARNING: \"" + title + "\" breaks naming convention: " + cat + " must start with capital letter."
            print '        Location: %s:%d' % (data.lines[0].file_name, data.lines[0].line_no)
    elif (convention == 'smallbig' and ((title[0] < 'a') or (title[0] > 'z'))):
        WARNING_COUNT += 1
        print
        print "\n!!  WARNING: \"" + title + "\" breaks naming convention: " + cat + " must start with lower case."
        print '        Location: %s:%d' % (data.lines[0].file_name, data.lines[0].line_no)
    elif (title[len(title)-1] == '_'):
        WARNING_COUNT += 1
        print
        print "\n!!  WARNING: \"" + title + "\" breaks naming convention: public identifiers must not end with \"_\"." # and private identifiers should not be documented
        print '        Location: %s:%d' % (data.lines[0].file_name, data.lines[0].line_no)


    #warning for unknown params
    sigs = data["signature"].text()
    sigs = sigs.strip(" \n")
    if len(sigs) > 0:
        params = data["param"]
        if params.empty():
            return
        keys = params.keys_by_occ()
        for k in keys:
            if sigs.find(k) < 0:
                # Maybe ignore the "unknown param" warning for this parameter
                # if the "nowarn" child includes "unknown param".
                if "unknown param" in data["param.%s.nowarn" % k].text():
                    continue
                WARNING_COUNT += 1
                print
                print "\n!!  WARNING: unknown param \"" + k + "\" in \"" + cat + "." + key + "\""
                line = params.find(k).lines[0]
                print '        Location: %s:%d' % (line.file_name, line.line_no)
                        
                        
################################################################################

def printTree(fl, data):
    MAX_NUMBER_OF_NODES = 6

    cat = data.name(0)
    treedown_fields = dddoc.DATA["globals.treedown"][cat]
    treeup_fields= dddoc.DATA["globals.treeup"][cat]
    
    if treedown_fields.empty() and treeup_fields.empty(): return
    
    treedown = followTree(data, treedown_fields)
    treeup = followTree(data, treeup_fields)

    if len(treedown) + len(treeup) == 0: return;
    fl.write("<div class=tree><center><table cellspacing=0 cellpadding=0>")
    if len(treeup) > 0:
        fl.write("<tr><td class=tree_td_subtree colspan=2 align=middle>" + translateTree(treeup, False, MAX_NUMBER_OF_NODES) + "</td></tr>")
        fl.write("<tr><td class=tree_td_line><img src=dddoc_empty.gif border=0 /></td><td class=tree_td_none><img src=dddoc_empty.gif border=0 /></td></tr>")

    fl.write("<tr><td class=tree_td_central colspan=2><center><div class=tree_central id=\"tree_node_" + cat + "\">")
    fl.write(getPageTitle(data))
    fl.write("</div></center></td></tr>")
    
    if len(treedown) > 0:
        fl.write("<tr><td class=tree_td_line><img src=dddoc_empty.gif border=0 /></td><td class=tree_td_none><img src=dddoc_empty.gif border=0 /></td></tr>")
        fl.write("<tr><td class=tree_td_subtree colspan=2 align=middle>" + translateTree(treedown, True, MAX_NUMBER_OF_NODES) + "</td></tr>")
        
        
    fl.write("</table></center></div>")

################################################################################

def followTree(data, follow_fields):
    tree = {}
    if data.empty(): return tree
    
    for field_line in follow_fields.lines:
        field = field_line.text()
        children = data[field]
        if not children.empty():
            for child_line in children.lines:
                child = child_line.text()
                if not tree.has_key(child):
                    tree[child] = followTree(dddoc.DATA[child], follow_fields)
                    
    return tree

################################################################################

def translateTree(tree, print_down, max_num_of_nodes):
    
    tr1 = ''
    tr2 = ''
    tr3 = ''
    tr4 = ''
    multiblock = ''
    i = 0

    keys = tree.keys()
    keys.sort()
    
    new_max_num_of_nodes = round((max_num_of_nodes + len(keys) - 1)/ len(keys))
    
    if print_down: valign = "valign=top"
    else: valign = "valign=bottom"

    for key in keys:
        if (i > 0) and (i % max_num_of_nodes == 0):
            separator_colspan = (2 *max_num_of_nodes).__str__()
            if print_down: 
                multiblock = multiblock + '<tr><td class=tree_td_connector rowspan = 5><img src=dddoc_empty.gif border=0 /></td>' + tr1 + '</tr><tr>' + tr2 + '</tr><tr>' + tr3 + '</tr><tr>' + tr4 + '</tr><tr><td colspan=' + separator_colspan + '><img id=tree_block_separator src=dddoc_empty.gif border=0/></td></tr>'
            else: 
                multiblock = '<tr><td class=tree_td_connector rowspan = 5><img src=dddoc_empty.gif border=0 /></td><td colspan=' + separator_colspan + '><img id=tree_block_separator src=dddoc_empty.gif border=0/></td></tr><tr>' + tr4 + '</tr><tr>' + tr3 + '</tr><tr>' + tr2 + '</tr><tr>' + tr1 + '</tr>' + multiblock
            tr1 = ''
            tr2 = ''
            tr3 = ''
            tr4 = ''
            
        i += 1

        if len(tree) > 1:
            if (i % max_num_of_nodes == 1): left_class = "tree_td_first"
            else: left_class = "tree_td_left"
            if (i % max_num_of_nodes == 0) or (i == len(tree)): right_class = "tree_td_last"
            else: right_class = "tree_td_right"
            tr1 += "<td class=" + left_class + "><img src=dddoc_empty.gif border=0 /></td><td class=" + right_class + "><img src=dddoc_empty.gif border=0 /></td>"

        
        pos = key.find('.')
        if pos > 0: node_cat = key[:pos]
        else: node_cat = key
        tr2 += "<td class=tree_td_node colspan=2><nobr><center><span class=tree_node id=\"tree_node_" + node_cat + "\">"
        tr2 += translateLink(key)
        tr2 += "</span></center></nobr></td>"
        
        subtree = tree[key]
        if len(subtree) == 0: 
            tr3 += "<td class=tree_td_none></td><td class=tree_td_none></td>"
            tr4 += "<td class=tree_td_subtree colspan=2 align=middle></td>"
        else: 
            tr3 += "<td class=tree_td_line><img src=dddoc_empty.gif border=0 /></td><td class=tree_td_none><img src=dddoc_empty.gif border=0 /></td>"
            tr4 += "<td class=tree_td_subtree colspan=2 align=middle " + valign + ">" + translateTree(subtree, print_down, new_max_num_of_nodes) + "</td>"
            

    if multiblock: connector = '<td class=tree_td_connector_end rowspan=4><img src=dddoc_empty.gif border=0 /></td>'
    else: connector = ''
               
    if print_down: 
        str = '<table class=tree_table_down cellspacing=0 cellpadding=0>'
        str += multiblock + '<tr>' + connector + tr1 + '</tr><tr>' + tr2 + '</tr><tr>' + tr3 + '</tr><tr>' + tr4 + '</tr>'
        str += '</table>'
    else: 
        str = '<table class=tree_table_up cellspacing=0 cellpadding=0>'
        str += '<tr>' + connector + tr4 + '</tr><tr>' + tr3 + '</tr><tr>' + tr2 + '</tr><tr>' + tr1 + '</tr>' + multiblock
        str += '</table>'
        
    if multiblock: return "<div id=tree_multiblock>" + str + "</div>"
    else:return str