summaryrefslogtreecommitdiff
path: root/extras/tiopf/gui/tiRtfReport.pas
blob: 1041cd375fc11953482d6a52fbeba7a8434128a8 (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
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
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
{

Revision history:
  2005-07-05: First release by Marius Ellen (mariusellen@home.nl)
  2007-04-18: Ported to Free Pascal and fpGUI by Graeme Geldenhuys (graemeg@gmail.com)

Purpose:
  Create reports with RTF documents with access to dataset and framework objects.

}

{ TODO :  Better exception handling. (saw some unexpected errors while parsing) corrupting the resulting rtf. }
{ TODO :  Show errors when trying to past eof in a TtiObjectList (its now ignored) }
{ TODO :  Suppress null dates (0 date are displayed as 1899-xx-xx) }

unit tiRtfReport;

{$mode objfpc}{$H+}
{.$I tiDefines.inc}

interface

uses
  Classes, SysUtils, contnrs, TypInfo{, Jpeg},
  Db, Variants, tiObject, fpg_base;

type
  TtiRtfParser = class;
  TRtfArgument = class;
  TRtfException = class(Exception);

  TRtfClass =(RtfNothing, RtfUnknown, RtfGroup, RtfText, RtfControl,
    RtfExpression, RtfBranche, RtfParseBegin, RtfParseEnd, RtfEOF);

  TRtfToken =(etNothing, etComma, etFunction, etProcedure, etParenthesis,
    etADD, etSUB, etMUL, etDIV, etEQ, etNE, etGE, etLE, etGT, etLT, etNot,
    etAnd, etOr, etAssign, etFieldName, etVariable, etDataset, etLitString,
    etLitInt, etLitFloat, etLitDate, etLitFalse, etLitTrue);
  TRtfTokenSet = set of TRtfToken;

  TRtfPictureOption =(poMetafile, poBinary);
  TRtfPictureOptions = set of TRtfPictureOption;
  TRtfPictureBorder =(brNone, brSingle, brDouble, brThick, brShadow, brDot, brHair);

  TColor = TfpgColor;
  TPicture = TMemoryStream;  // fake it until we can implement image support


  TRtfPictureAttr = class(TObject)
  private
    FWidth: integer;
    FHeigth: integer;
    FScaleX: integer;
    FScaleY: integer;
    FWidthmm: Double;
    FHeigthmm: Double;
    FBorderWidth: integer;
    FBorderColor: TColor;
    FProportional: boolean;
    FBorderType: TRtfPictureBorder;
    procedure SetScaleX(Value: integer);
    procedure SetScaleY(Value: integer);
  public
    constructor Create(AWidth, AHeigth: word);
    //Width and height are in pixels
    property Width: integer read FWidth;
    property Heigth: integer read FHeigth;
    //Widthmm and heightmm are in milimeters
    property Widthmm: Double read FWidthmm;
    property Heigthmm: Double read FHeigthmm;
    //Scale from 1 to 100
    property ScaleX: integer read FScaleX write SetScaleX;
    property ScaleY: integer read FScaleY write SetScaleY;
    property BorderColor: TColor read FBorderColor write FBorderColor;
    property BorderWidth: integer read FBorderWidth write FBorderWidth; //in points
    property BorderType: TRtfPictureBorder read FBorderType write FBorderType;
    property Proportional: boolean read FProportional write FProportional;
  end;


  TRtfPicturePath = procedure(var AFilename: string)of object;
  TRtfFunctionExecute = procedure(AArgument: TRtfArgument)of object;
  TRtfOnPictureAttr = procedure(APictureAttr: TRtfPictureAttr)of object;
  TRtfArgumentEvent = procedure(APrevItem, AArgument, ANextItem: TRtfArgument)of object;
  TRtfOnCreateDataset = procedure(ADatabase, AAlias, ASql: string; AArgument: TRtfArgument)of object;


  //Basic Rtf control word
  TRtfItem = class(TList)
  private
    FNext: TRtfItem;
    FPrev: TRtfItem;
    FParent: TRtfItem;
    FRtfMajor: integer;
    FRtfMinor: integer;
    FRtfClass: TRtfClass;
    FRtfTextBuf: string;
    function GetItem(Index: integer): TRtfItem;
    function CheckItem(AClass: TRtfClass; Major: integer): boolean;
  protected
    procedure Notify(Ptr: pointer; Action: TListNotification); override;
  public
    procedure Assign(ASource: TRtfItem); virtual;
    property Next: TRtfItem read FNext;
    property Prev: TRtfItem read FPrev;
    property Parent: TRtfItem read FParent;
    //Weak names, but it keeps the RawRtfParser simple
    property RtfClass: TRtfClass read FRtfClass write FRtfClass;
    property RtfMajor: integer read FRtfMajor write FRtfMajor;
    property RtfMinor: integer read FRtfMinor write FRtfMinor;
    property RtfTextBuf: string read FRtfTextBuf write FRtfTextBuf;
    property Items[Index: integer]: TRtfItem read GetItem; default;
  end;


  //Old style Double linked list (but still usefull)
  TRtfItemList = class(TObject)
  private
    FHead: TRtfItem;
    FTail: TRtfItem;
    FCount: integer;
  protected
    procedure dlRemove(AItem: TRtfItem; DisposeIt: boolean);
  public
    constructor Create; virtual;
    destructor Destroy; override;

    procedure Clear;
    function Add(AItem: TRtfItem): TRtfItem;
    procedure SaveToStream(AStream: TStream; AColors: string);
    procedure Insert(AItem: TRtfItem); {-Insert element at start of list}
    procedure Delete(AItem: TRtfItem); {-Delete existing element in list, disposing of its contents}
    procedure Extract(AItem: TRtfItem); {-Extract existing element from list without disposing of it}
    procedure PlaceAfter(AItem, AAfter: TRtfItem); {-Place element P into list _after_ existing element L}
    procedure PlaceBefore(AItem, ABefore: TRtfItem); {-Place element P into list _before_ existing element L}

    property Head: TRtfItem read FHead; {-Return TRtfItem to head of list}
    property Tail: TRtfItem read FTail; {-Return TRtfItem to tail of list}
    property Count: integer read FCount;
  end;


  //Variable definition
  TRtfVariable = class(TObject)
  private
    FName: string;
    FValue: variant;
    FToken: TRtfToken;
  public
    property Name: string read FName write FName;
    property Value: variant read FValue write FValue;
    property Token: TRtfToken read FToken write FToken;
  end;


  TRtfVariableList = class(TObjectList)
  private
    function GetItem(Index: integer): TRtfVariable;
  public
    destructor Destroy; override;
    function Find(AName: string): TRtfVariable;
    function Add(AName: string; AValue: variant; AToken: TRtfToken): TRtfVariable;
    property Items[Index: integer]: TRtfVariable read GetItem; default;
  end;


  //Function definition
  TRtfFunction = class(TObject)
  private
    FMin: smallint;
    FMax: smallint;
    FName: string;
    FToken: TRtfToken;
    FOnExecute: TRtfFunctionExecute;
  public
    property Name: string read FName write FName; //Function name
    property Min: smallint read FMin write FMin; //Function minimal parameters
    property Max: smallint read FMax write FMax; //Function maximal parameters
    property Token: TRtfToken read FToken write FToken; //Function type (=weak name)
    property OnExecute: TRtfFunctionExecute read FOnExecute write FOnExecute;
  end;


  TRtfFunctionList = class(TObjectList)
  private
    function GetItem(Index: integer): TRtfFunction;
  public
    function Find(AName: string): TRtfFunction;
    function Add(ATokenType: TRtfToken; AName: string; AMin, AMax: smallint; AOnexecute: TRtfFunctionExecute): TRtfFunction;
    property Items[Index: integer]: TRtfFunction read GetItem; default;
  end;


  //Dataset defintion (Simply a wrap around the TDataset compatible and framework objects)
  TRtfDataset = class(TObjectList)
  private
    FName: string;
    FDataset: TObject;
    FParent: TRtfDataset;
    FTableIndex: integer;
    FFreeDataset: boolean;
    function GetItem(Index: integer): TRtfDataset;
    function ResolveNestedFields(ATable: TRtfDataset; AName: string; var AFieldName: string): TRtfDataset;
  protected
    procedure Notify(Ptr: pointer; Action: TListNotification); override;
  public
    destructor Destroy; override;
    function Find(AName: string): TRtfDataset; overload;
    function Find(AName: string; out AFieldName: string): TRtfDataset; overload;
    function Add(ADataset: TObject; AName: string; AFreeDataset: boolean = false): TRtfDataset;
    property Items[Index: integer]: TRtfDataset read GetItem; default;

    procedure Open;
    procedure Next;
    procedure Prior;
    procedure First;
    procedure Last;
    function Eof: boolean;
    function Bof: boolean;
    function IsEmpty: boolean;
    function RecordCount: integer;

    property Parent: TRtfDataset read FParent;
    property Name: string read FName write FName; //TableName
    property FreeDataset: boolean read FFreeDataset;
    property Dataset: TObject read FDataset write FDataset;
    property TableIndex: integer read FTableIndex write FTableIndex; //Record index
  end;


  //Argument definition (For evaluating of expressions)
  TRtfArgument = class(TObjectList)
  private
    FValue: variant;
    FParent: TRtfArgument;
    FToken: TRtfToken;
    FParam: integer;
    FParser: TtiRtfParser;
    procedure ResolveVariable;
    procedure EvaluateExpression;
    function GetItem(Index: integer): TRtfArgument;
    function Add(AArgument: TRtfArgument): TRtfArgument; overload;
    function Add(AValue: variant; ATokenType: TRtfToken): TRtfArgument; overload;
    procedure Walk(ATokenset: TRtfTokenSet; AExecproc: TRtfArgumentEvent);
    procedure EvaluateAssign(APrevItem, AArgument, ANextItem: TRtfArgument);
    procedure EvaluateComparison(APrevItem, AArgument, ANextItem: TRtfArgument);
    procedure EvaluateUnaryBinary(APrevItem, AArgument, ANextItem: TRtfArgument);
  protected
    procedure Notify(Ptr: pointer; Action: TListNotification); override;
    //Dataset stuff
    procedure ResolveFieldName;
    function GetPicture(APicture: TPicture): string;
    procedure GetGraphicsValue(ADataset: TRtfDataset; AFieldName: string);
    procedure ResolveFieldValue(ADataset: TRtfDataset; AFieldName: string);
    procedure GetPictureData(ABuffer: pointer; ALength: cardinal; var Result: string);
  public
    constructor Create(AParser: TtiRtfParser); overload;
    procedure Evaluate;
    function Check(AParam: integer; ATokens: TRtfTokenSet): boolean; overload;
    function Check(ATokens: array of TRtfTokenSet): boolean; overload;
    procedure ParseExpression(AExpression: string); virtual;

    property Parser: TtiRtfParser read FParser;
    property Parent: TRtfArgument read FParent; //Parent argument list
    property Value: variant read FValue write FValue; //Argument value
    property Param: integer read FParam write FParam; //Just for Scan(Dataset)
    property Token: TRtfToken read FToken write FToken; //Argument type
    property Items[Index: integer]: TRtfArgument read GetItem; default;
  end;


  //Color definition
  TRtfColor = class(TObject)
  private
    FBlue: integer;
    FRed: integer;
    FGreen: integer;
    function GetAsString: string;
  public
    property Red: integer read FRed write FRed;
    property Green: integer read FGreen write FGreen;
    property Blue: integer read FBlue write FBlue;
    property AsString: string read GetAsString;
  end;


  TRtfColorList = class(TObjectlist)
  private
    function GetItem(Index: integer): TRtfColor;
    function GetAsString: string;
  public
    property AsString: string read GetAsString;
    procedure Clear; override;
    function UseColor(AColor: TColor): integer; overload;
    function Add(ARed, AGreen, ABlue: integer): integer;
    function Find(ARed, AGreen, ABlue: integer): integer;
    function UseColor(ARed, AGreen, ABlue: integer): integer; overload;
    property Items[Index: integer]: TRtfColor read GetItem; default;
  end;


  //Parser definition
  TtiRtfParser = class(TObject)
  private
    FBoolTrue: string;
    FBoolFalse: string;
    FHlpItems: TRtfItem;
    TmpItems: TObjectlist;
    FDatasets: TRtfDataset;
    FRtfItems: TRtfItemList;
    FErrorBackColor: TColor;
    FErrorForeColor: TColor;
    FRawItems: TRtfItemList;
    FColorList: TRtfColorList;
    FFunctions: TRtfFunctionList;
    FVariables: TRtfVariableList;
    FOnPicturePath: TRtfPicturePath;
    FOnPictureAttr: TRtfOnPictureAttr;
    FOnEvalutate: TRtfFunctionExecute;
    FPictureOptions: TRtfPictureOptions;
    FOnCreateDataset: TRtfOnCreateDataset;
    procedure PreParse;
    procedure Parse(AItems: TRtfItem);
    procedure ParseExpression(AItem: TRtfItem);
    function AddToRtfItems(AItem: TRtfItem): TRtfItem;
    function SkipParagraph(AItem: TRtfItem): TRtfItem;
    procedure UdfDateTimeTo(AArgument: TRtfArgument; AFormat: string);
  protected
    procedure AddFunctions; virtual;
    procedure UdfDummy(AArgument: TRtfArgument);

    //routines for date time
    procedure UdfNow(AArgument: TRtfArgument);
    procedure UdfDate(AArgument: TRtfArgument);
    procedure UdfTime(AArgument: TRtfArgument);
    procedure UdfYear(AArgument: TRtfArgument);
    procedure UdfMonth(AArgument: TRtfArgument);
    procedure UdfDay(AArgument: TRtfArgument);
    procedure UdfShortDayName(AArgument: TRtfArgument);
    procedure UdfShortMonthName(AArgument: TRtfArgument);
    procedure UdfLongDayName(AArgument: TRtfArgument);
    procedure UdfLongMonthName(AArgument: TRtfArgument);
    { year as string }
    procedure UdfSYear(AArgument: TRtfArgument);
    { month as string }
    procedure UdfSMonth(AArgument: TRtfArgument);
    { day as string }
    procedure UdfSDay(AArgument: TRtfArgument);
    { string to date }
    procedure UdfStod(AArgument: TRtfArgument);
    { date to string }
    procedure UdfDtoS(AArgument: TRtfArgument);
    procedure UdfDateToStr(AArgument: TRtfArgument);
    procedure UdfTimeToStr(AArgument: TRtfArgument);
    procedure UdfDateTimeToStr(AArgument: TRtfArgument);
    procedure UdfStrToDate(AArgument: TRtfArgument);
    procedure UdfStrToTime(AArgument: TRtfArgument);
    procedure UdfStrToDateTime(AArgument: TRtfArgument);

    //routines for strings, int, float etc.
    procedure UdfInt(AArgument: TRtfArgument);
    procedure UdfStr(AArgument: TRtfArgument);
    procedure UdfVal(AArgument: TRtfArgument);
    procedure UdfChr(AArgument: TRtfArgument);
    procedure UdfNul(AArgument: TRtfArgument);
    procedure UdfFrac(AArgument: TRtfArgument);
    procedure UdfEmpty(AArgument: TRtfArgument);
    procedure UdfPadr(AArgument: TRtfArgument);
    procedure UdfPadl(AArgument: TRtfArgument);
    procedure UdfLower(AArgument: TRtfArgument);
    procedure UdfUpper(AArgument: TRtfArgument);
    procedure UdfTrunc(AArgument: TRtfArgument);
    procedure UdfRound(AArgument: TRtfArgument);
    procedure UdfTrim(AArgument: TRtfArgument);
    procedure UdfPower(AArgument: TRtfArgument);
    procedure UdfIntPower(AArgument: TRtfArgument);
    procedure UdfTrimLeft(AArgument: TRtfArgument);
    procedure UdfTrimRight(AArgument: TRtfArgument);
    procedure UdfSubStr(AArgument: TRtfArgument);
    procedure UdfIntToStr(AArgument: TRtfArgument);
    procedure UdfStrToInt(AArgument: TRtfArgument);
    procedure UdfFloatToStr(AArgument: TRtfArgument);
    procedure UdfStrToFloat(AArgument: TRtfArgument);
    procedure UdfFormatFloat(AArgument: TRtfArgument);
    procedure UdfFBool(AArgument: TRtfArgument);

    //routines for conditinals
    procedure UdfIf(AArgument: TRtfArgument);
    procedure UdfIif(AArgument: TRtfArgument);

    //routines for datasets
    procedure UdfDataset(AArgument: TRtfArgument);
    procedure UdfScan(AArgument: TRtfArgument);
    procedure UdfBof(AArgument: TRtfArgument);
    procedure UdfEof(AArgument: TRtfArgument);
    procedure UdfNext(AArgument: TRtfArgument);
    procedure UdfPrior(AArgument: TRtfArgument);
    procedure UdfFirst(AArgument: TRtfArgument);
    procedure UdfLast(AArgument: TRtfArgument);
    procedure UdfOpen(AArgument: TRtfArgument);
    procedure UdfIsEmpty(AArgument: TRtfArgument);
    procedure UdfRecordCount(AArgument: TRtfArgument);

    //misch routines
    procedure UdfPicture(AArgument: TRtfArgument);
    procedure UdfDbPicture(AArgument: TRtfArgument);
  public
    constructor Create; virtual;
    destructor Destroy; override;

    procedure Clear;
    procedure Execute; virtual;

    procedure LoadFromFile(AFilename: string);
    procedure LoadFromString(AString: string);
    procedure LoadFromStream(AStream: TMemoryStream);
    procedure LoadFromBuffer(ABuffer: pchar; ASize: integer);

    function SaveToString: string;
    procedure SaveToFile(AFileName: string);
    procedure SaveToStream(AStream: TMemoryStream);

    function AddVariable(AName: string; AValue: variant; AToken: TRtfToken): TRtfVariable;
    function AddDataset(ATable: TObject; AName: string; AFreeDataset: boolean = false): TRtfDataset;
    function AddFunction(AName: string; ATokenType: TRtfToken; AMin, AMax: smallint; AOnexecute: TRtfFunctionExecute): TRtfFunction;


    //these should all be hidden in component style
    property RawItems: TRtfItemList read FRawItems;
    property HlpItems: TRtfItem read FHlpItems;
    property RtfItems: TRtfItemList read FRtfItems;
    property Datasets: TRtfDataset read FDatasets;
    property Functions: TRtfFunctionList read FFunctions;
    property Variables: TRtfVariableList read FVariables;
    property ColorList: TRtfColorList read FColorList;
    property OnEvalutate: TRtfFunctionExecute read FOnEvalutate write FOnEvalutate; //For debug only
  published
    property BoolTrue: string read FBoolTrue write FBoolTrue;
    property BoolFalse: string read FBoolFalse write FBoolFalse;
    property ErrorForeColor: TColor read FErrorForeColor write FErrorForeColor default clRed;
    property ErrorBackColor: TColor read FErrorBackColor write FErrorBackColor default clYellow;
    property PictureOptions: TRtfPictureOptions read FPictureOptions write FPictureOptions default[poMetafile, poBinary];

    property OnPicturePath: TRtfPicturePath read FOnPicturePath write FOnPicturePath;
    property OnPictureAttr: TRtfOnPictureAttr read FOnPictureAttr write FOnPictureAttr;
    property OnCreateDataset: TRtfOnCreateDataset read FOnCreateDataset write FOnCreateDataset;
  end;

implementation

uses
  math        // IntPower() function
  ,fpg_main   // fpgApplication.HandleExeception()
  ;

resourcestring
  rsNotImplemented = 'Not implemented';
  rsInvalidDateConstant = 'Invalid date constant';
  rsInvalidTimeConstant = 'Invalid time constant';
  rsInvalidDateSeparator = 'Invalid date separator';
  rsInvalidTimeSeparator = 'Invalid time separator';
  rsInvalidDateTimeConstant = 'Invalid date/time constant';
  rsInvalidExpressionCharacter = 'Invalid expression character "%s"';
  rsUnterminatedStringConstant = 'Unterminated string constant';
  rsToManyClosingParenthesis = 'Unexpected parenthesis';
  rsExpectedClosingParenthesis = 'Missing closing parenthesis';
  rsUnexpectedParameterType = 'Unexpected parameter type';

type
  TRtfKey = record
    RtfKMajor: integer;
    RtfKMinor: integer;
    RtfKStr: string;
  end;


  TRawRtfParser = class(TObject)
  private
    APtr, AEnd: pchar;
    APushedChar: char;
    FRtfMajor: integer;
    FRtfMinor: integer;
    FRtfTextBuf: string;
    AParseItem: TRtfItem;
    FRtfClass: TRtfClass;
    FColorTable: TRtfItem;
    RawItems: TRtfItemList;
    procedure RtfHook;
    procedure GetRtfToken;
    function GetRtfChar: char;
  protected
    property RtfClass: TRtfClass read FRtfClass;
    property RtfMajor: integer read FRtfMajor;
    property RtfMinor: integer read FRtfMinor;
    property RtfTextBuf: string read FRtfTextBuf;
  public
    procedure Execute(ARawItems: TRtfItemList; ARtfPtr: pchar; ARtfSize: integer);

    property ColorTable: TRtfItem read FColorTable;
  end;



const
  {@indent off}
  //Control class major numbers
  //RtfVersion            = 01;
  //RtfDefFont            = 02;
  //RtfCharSet            = 03;
  RtfDestination        = 04;
  //RtfFontFamily         = 05;
  //RtfColorName          = 06;
  RtfSpecialChar        = 07;
  //RtfStyleAttr          = 08;
  //RtfDocAttr            = 09;
  //RtfSectAttr           = 10;
  //RtfTblAttr            = 11;
  RtfParAttr            = 12;
  //RtfCharAttr           = 13;
  //RtfPictAttr           = 14;
  //RtfNeXTGrAttr         = 15;
  //RtfFieldAttr          = 16;
  //RtfTOCAttr            = 17;
  //RtfPosAttr            = 18;

  //RtfExpression major numbers
  RtfNormalExpression   = 1;
  RtfIfExpression       = 2;
  RtfThenExpression     = 3;
  RtfElseExpression     = 4;
  RtfEndifExpression    = 5;
  RtfScan               = 6;
  RtfScanEntry          = 7;
  RtfScanFooter         = 8;
  RtfScanEnd            = 9;

  //Group class major numbers
  RtfBeginGroup         = 01;
  RtfEndGroup           = 02;

  //Control class minor numbers
  {RtfAnsiCharSet = 0;
  RtfMacCharSet = 1;
  RtfPcCharSet = 2;
  RtfPcaCharSet = 3;}


  //Destination attributes minor numbers
  {RtfPict = 0;
  RtfNeXTGraphic = 1;
  RtfFootnote = 2;
  RtfHeader = 3;
  RtfHeaderLeft = 4;
  RtfHeaderRight = 5;
  RtfHeaderFirst = 6;
  RtfFooter = 7;
  RtfFooterLeft = 8;
  RtfFooterRight = 9;
  RtfFooterFirst = 10;
  RtfFNSep = 11;
  RtfFNContSep = 12;
  RtfFNContNotice = 13;}
  RtfInfo = 14;
  RtfStyleSheet = 15;
  RtfFontTbl = 16;
  RtfColorTbl = 17;
  RtfField = 18;
  {RtfFieldInst = 19;
  RtfFieldResult = 20;
  RtfIndex = 21;
  RtfIndexBold = 22;
  RtfIndexItalic = 23;
  RtfIndexText = 24;
  RtfIndexRange = 25;
  RtfTOC = 26;
  RtfBookmarkStart = 27;
  RtfBookmarkEnd = 28;
  RtfITitle = 29;
  RtfISubject = 30;
  RtfIAuthor = 31;
  RtfIOperator = 32;
  RtfIKeywords = 33;
  RtfIComment = 34;
  RtfIVersion = 35;
  RtfIDoccomm = 36;}

  //Fonts minor numbers
  {RtfFFNil = 0;
  RtfFFRoman = 1;
  RtfFFSwiss = 2;
  RtfFFModern = 3;
  RtfFFScript = 4;
  RtfFFDecor = 5;
  RtfFFTech = 6;}

  //Color attributes minor numbers
  {RtfRed = 0;
  RtfGreen = 1;
  RtfBlue = 2;}

  //Style attributes minor numbers
  {RtfBasedOn = 0;
  RtfNext = 1;}

  //Special characters minor numbers
  {RtfCurHeadPage = 0;
  RtfCurFNote = 1;
  RtfCurHeadPict = 2;
  RtfCurHeadDate = 3;
  RtfCurHeadTime = 4;}
  RtfFormula = 5;
  RtfNoBrkSpace = 6;
  RtfNoReqHyphen = 7;
  RtfNoBrkHyphen = 8;
  {RtfPage = 9;
  RtfLine = 10;}
  RtfPar = 11;
  {RtfSect = 12;}
  RtfTab = 13;
  {RtfCell = 14;
  RtfRow = 15;
  RtfCurAnnot = 16;
  RtfAnnotation = 17;
  RtfAnnotID = 18;
  RtfCurAnnotRef = 19;
  RtfFNoteSep = 20;
  RtfFNoteCont = 21;
  RtfColumn = 22;}
  RtfOptDest = 23;
  {RtfIIntVersion = 24;
  RtfICreateTime = 25;
  RtfIRevisionTime = 26;
  RtfIPrintTime = 27;
  RtfIBackupTime = 28;
  RtfIEditTime = 29;
  RtfIYear = 30;
  RtfIMonth = 31;
  RtfIDay = 32;
  RtfIHour = 33;
  RtfIMinute = 34;
  RtfINPages = 35;
  RtfINWords = 36;
  RtfINChars = 37;
  RtfIIntID = 38;}
  RtflQuote = 39;
  RtfrQuote = 40;
  RtflDblQuote = 41;
  RtfrDblQuote = 42;


  //Document atributes minor numbers
  {RtfPaperWidth = 0;
  RtfPaperHeight = 1;
  RtfLeftMargin = 2;
  RtfRightMargin = 3;
  RtfTopMargin = 4;
  RtfBottomMargin = 5;
  RtfFacingPage = 6;
  RtfGutterWid = 7;
  RtfDefTab = 8;
  RtfWidowCtrl = 9;
  RtfHyphHotZone = 10;
  RtfFNoteEndSect = 11;
  RtfFNoteEndDoc = 12;
  RtfFNoteText = 13;
  RtfFNoteBottom = 14;
  RtfFNoteStart = 15;
  RtfFNoteRestart = 16;
  RtfPageStart = 17;
  RtfLineStart = 18;
  RtfLandscape = 19;
  RtfFracWidth = 20;
  RtfNextFile = 21;
  RtfTemplate = 22;
  RtfMakeBackup = 23;
  RtfRtfDefault = 24;
  RtfRevisions = 25;
  RtfMirrorMargin = 26;
  RtfRevDisplay = 27;
  RtfRevBar = 28;}

  //Sector attributes minor numbers
  {RtfSectDef = 0;
  RtfNoBreak = 1;
  RtfColBreak = 2;
  RtfPageBreak = 3;
  RtfEvenBreak = 4;
  RtfOddBreak = 5;
  RtfPageStarts = 6;
  RtfPageCont = 7;
  RtfPageRestart = 8;
  RtfPageDecimal = 9;
  RtfPageURoman = 10;
  RtfPageLRoman = 11;
  RtfPageULetter = 12;
  RtfPageLLetter = 13;
  RtfPageNumLeft = 14;
  RtfPageNumTop = 15;
  RtfHeaderY = 16;
  RtfFooterY = 17;
  RtfLineModulus = 18;
  RtfLineDist = 19;
  RtfLineStarts = 20;
  RtfLineRestart = 21;
  RtfLineRestartPg = 22;
  RtfLineCont = 23;
  RtfTopVAlign = 24;
  RtfBottomVAlign = 25;
  RtfCenterVAlign = 26;
  RtfJustVAlign = 27;
  RtfColumns = 28;
  RtfColumnSpace = 29;
  RtfColumnLine = 30;
  RtfENoteHere = 31;
  RtfTitleSpecial = 32;}

  //Table attributes minor numbers
  {RtfCellBordBottom = 0;
  RtfCellBordTop = 1;
  RtfCellBordLeft = 2;
  RtfCellBordRight = 3;
  RtfRowDef = 4;
  RtfRowLeft = 5;
  RtfRowRight = 6;
  RtfRowCenter = 7;
  RtfRowGapH = 8;
  RtfRowHt = 9;
  RtfRowLeftEdge = 10;
  RtfCellPos = 11;
  RtfMergeRngFirst = 12;
  RtfMergePrevious = 13;}

  //Paragrapgh attributes minor numbers
  RtfParDef = 0;
  {RtfStyleNum = 1;
  RtfQuadLeft = 2;
  RtfQuadRight = 3;
  RtfQuadJust = 4;
  RtfQuadCenter = 5;
  RtfFirstIndent = 6;
  RtfLeftIndent = 7;
  RtfRightIndent = 8;
  RtfSpaceBefore = 9;
  RtfSpaceAfter = 10;
  RtfSpaceBetween = 11;
  RtfInTable = 12;
  RtfKeep = 13;
  RtfKeepNext = 14;
  RtfSideBySide = 15;
  RtfPBBefore = 16;
  RtfNoLineNum = 17;
  RtfTabPos = 18;
  RtfTabRight = 19;
  RtfTabCenter = 20;
  RtfTabDecimal = 21;
  RtfTabBar = 22;
  RtfBorderTop = 23;
  RtfBorderBottom = 24;
  RtfBorderLeft = 25;
  RtfBorderRight = 26;
  RtfBorderBox = 27;
  RtfBorderBar = 28;
  RtfBorderBetween = 29;
  RtfBorderSingle = 30;
  RtfBorderThick = 31;
  RtfBorderShadow = 32;
  RtfBorderDouble = 33;
  RtfBorderDot = 34;
  RtfBorderHair = 35;
  RtfBorderSpace = 36;
  RtfLeaderDot = 37;
  RtfLeaderHyphen = 38;
  RtfLeaderUnder = 39;
  RtfLeaderThick = 40;}

  //Character attributes minor numbers
  {RtfPlain = 0;
  RtfBold = 1;
  RtfItalic = 2;
  RtfStrikeThru = 3;
  RtfOutline = 4;
  RtfShadow = 5;
  RtfSmallCaps = 6;
  RtfAllCaps = 7;
  RtfInvisible = 8;
  RtfFontNum = 9;
  RtfFontSize = 10;
  RtfExpand = 11;
  RtfUnderline = 12;
  RtfWUnderline = 13;
  RtfDUnderline = 14;
  RtfDbUnderline = 15;
  RtfNoUnderline = 16;
  RtfSuperScript = 17;
  RtfSubScript = 18;
  RtfRevised = 19;
  RtfForeColor = 20;
  RtfBackColor = 21;
  RtfGray = 22; }

  //Picture attributes minor numbers
  {RtfMacQD = 0;
  RtfWinMetafile = 1;
  RtfWinBitmap = 2;
  RtfPicWid = 3;
  RtfPicHt = 4;
  RtfPicGoalWid = 5;
  RtfPicGoalHt = 6;
  RtfPicScaleX = 7;
  RtfPicScaleY = 8;
  RtfPicScaled = 9;
  RtfPicCropTop = 10;
  RtfPicCropBottom = 11;
  RtfPicCropLeft = 12;
  RtfPicCropRight = 13;
  RtfPixelBits = 14;
  RtfBitmapPlanes = 15;
  RtfBitmapWid = 16;
  RtfPicBinary = 17;}

  //
  {RtfNeXTGWidth = 0;
  RtfNeXTGHeight = 1;}

  //Field attributes minor numbers
  {RtfFieldDirty = 0;
  RtfFieldEdited = 1;
  RtfFieldLocked = 2;
  RtfFieldPrivate = 3;}

  //Toc attributes minor numbers
  {RtfTOCType = 0;
  RtfTOCLevel = 1;}

  //Position attributes minor numbers
  {RtfPosX = 0;
  RtfPosXCenter = 1;
  RtfPosXInside = 2;
  RtfPosXLeft = 3;
  RtfPosXOutSide = 4;
  RtfPosXRight = 5;
  RtfPosY = 6;
  RtfPosYInline = 7;
  RtfPosYTop = 8;
  RtfPosYCenter = 9;
  RtfPosYBottom = 10;
  RtfAbsWid = 11;
  RtfTextDist = 12;
  RtfRPosMargV = 13;
  RtfRPosPageV = 14;
  RtfRPosMargH = 15;
  RtfRPosPageH = 16;
  RtfRPosColH = 17;}

const
  //A reduced set of control words
  RtfKey: array[0..15]of TRtfKey =
  (
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfParDef;         RtfKStr: '\pard'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfPar;            RtfKStr: '\par'          ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfTab;            RtfKStr: '\tab'          ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtflQuote;         RtfKStr: '\lquote'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfrQuote;         RtfKStr: '\rquote'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtflQuote;         RtfKStr: '\'+Chr(39)+'91'),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfrQuote;         RtfKStr: '\'+Chr(39)+'92'),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtflDblQuote;      RtfKStr: '\ldblquote'    ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfrDblQuote;      RtfKStr: '\rdblquote'    ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtflDblQuote;      RtfKStr: '\'+Chr(39)+'93'),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfrDblQuote;      RtfKStr: '\'+Chr(39)+'94'),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfInfo;           RtfKStr: '\info'         ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfStyleSheet;     RtfKStr: '\stylesheet'   ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFontTbl;        RtfKStr: '\fonttbl'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfColorTbl;       RtfKStr: '\colortbl'     ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfField;          RtfKStr: '\field'        )
  );

  {  You could also add the following (but i don't need all that):
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurHeadPict;    RtfKStr: '\chpict'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurHeadDate;    RtfKStr: '\chdate'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurHeadTime;    RtfKStr: '\chtime'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurHeadPage;    RtfKStr: '\chpgn'        ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurFNote;       RtfKStr: '\chftn'        ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCurAnnotRef;    RtfKStr: '\chatn'        ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfFNoteSep;       RtfKStr: '\chftnsep'     ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfFNoteCont;      RtfKStr: '\chftnsepc'    ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfCell;           RtfKStr: '\cell'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfRow;            RtfKStr: '\row'          ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfSect;           RtfKStr: '\sect'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfPage;           RtfKStr: '\page'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfColumn;         RtfKStr: '\column'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfLine;           RtfKStr: '\line'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIIntVersion;    RtfKStr: '\vern'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfICreateTime;    RtfKStr: '\creatim'      ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIRevisionTime;  RtfKStr: '\revtim'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIPrintTime;     RtfKStr: '\printim'      ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIBackupTime;    RtfKStr: '\buptim'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIEditTime;      RtfKStr: '\edmins'       ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIYear;          RtfKStr: '\yr'           ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIMonth;         RtfKStr: '\mo'           ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIDay;           RtfKStr: '\dy'           ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIHour;          RtfKStr: '\hr'           ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIMinute;        RtfKStr: '\min'          ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfINPages;        RtfKStr: '\nofpages'     ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfINWords;        RtfKStr: '\nofwords'     ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfINChars;        RtfKStr: '\nofchars'     ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfIIntID;         RtfKStr: '\id'           ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfPict;           RtfKStr: '\pict'         ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfNeXTGraphic;    RtfKStr: '\nextgraphic'  ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFootnote;       RtfKStr: '\footnote'     ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfHeader;         RtfKStr: '\header'       ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfHeaderLeft;     RtfKStr: '\headerl'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfHeaderRight;    RtfKStr: '\headerr'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfHeaderFirst;    RtfKStr: '\headerf'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFooter;         RtfKStr: '\footer'       ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFooterLeft;     RtfKStr: '\footerl'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFooterRight;    RtfKStr: '\footerr'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFooterFirst;    RtfKStr: '\footerf'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFNSep;          RtfKStr: '\ftnsep'       ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFNContSep;      RtfKStr: '\ftnsepc'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFNContNotice;   RtfKStr: '\ftncn'        ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfAnnotation;     RtfKStr: '\annotation'   ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfAnnotID;        RtfKStr: '\atnid'        ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFieldInst;      RtfKStr: '\fldinst'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfFieldResult;    RtfKStr: '\fldrslt'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIndex;          RtfKStr: '\xe'           ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIndexBold;      RtfKStr: '\bxe'          ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIndexItalic;    RtfKStr: '\ixe'          ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIndexText;      RtfKStr: '\txe'          ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIndexRange;     RtfKStr: '\rxe'          ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfTOC;            RtfKStr: '\tc'           ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfBookmarkStart;  RtfKStr: '\bkmkstart'    ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfBookmarkEnd;    RtfKStr: '\bkmkend'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfITitle;         RtfKStr: '\title'        ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfISubject;       RtfKStr: '\subject'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIAuthor;        RtfKStr: '\author'       ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIOperator;      RtfKStr: '\operator'     ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIKeywords;      RtfKStr: '\keywords'     ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIComment;       RtfKStr: '\comment'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIVersion;       RtfKStr: '\version'      ),
    (RtfKMajor: RtfDestination; RtfKMinor: RtfIDoccomm;       RtfKStr: '\doccomm'      ),
    (RtfKMajor: RtfVersion;     RtfKMinor: - 1;               RtfKStr: '\rtf'          ),
    (RtfKMajor: RtfDefFont;     RtfKMinor: - 1;               RtfKStr: '\deff'         ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfStyleNum;       RtfKStr: '\s'            ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfQuadLeft;       RtfKStr: '\ql'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfQuadRight;      RtfKStr: '\qr'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfQuadJust;       RtfKStr: '\qj'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfQuadCenter;     RtfKStr: '\qc'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfFirstIndent;    RtfKStr: '\fi'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfLeftIndent;     RtfKStr: '\li'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfRightIndent;    RtfKStr: '\ri'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfSpaceBefore;    RtfKStr: '\sb'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfSpaceAfter;     RtfKStr: '\sa'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfSpaceBetween;   RtfKStr: '\sl'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfInTable;        RtfKStr: '\intbl'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfKeep;           RtfKStr: '\keep'         ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfKeepNext;       RtfKStr: '\keepn'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfSideBySide;     RtfKStr: '\sbys'         ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfPBBefore;       RtfKStr: '\pagebb'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfNoLineNum;      RtfKStr: '\noline'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfTabPos;         RtfKStr: '\tx'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfTabRight;       RtfKStr: '\tqr'          ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfTabCenter;      RtfKStr: '\tqc'          ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfTabDecimal;     RtfKStr: '\tqdec'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfTabBar;         RtfKStr: '\tb'           ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderTop;      RtfKStr: '\brdrt'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderBottom;   RtfKStr: '\brdrb'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderLeft;     RtfKStr: '\brdrl'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderRight;    RtfKStr: '\brdrr'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderBar;      RtfKStr: '\bar'          ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderBox;      RtfKStr: '\box'          ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderBetween;  RtfKStr: '\brdrbtw'      ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderSingle;   RtfKStr: '\brdrs'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderThick;    RtfKStr: '\brdrth'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderShadow;   RtfKStr: '\brdrsh'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderDouble;   RtfKStr: '\brdrdb'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderDot;      RtfKStr: '\brdrdot'      ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderHair;     RtfKStr: '\brdrhair'     ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfLeaderDot;      RtfKStr: '\tldot'        ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfLeaderHyphen;   RtfKStr: '\tlhyph'       ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfLeaderUnder;    RtfKStr: '\tlul'         ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfLeaderThick;    RtfKStr: '\tlth'         ),
    (RtfKMajor: RtfParAttr;     RtfKMinor: RtfBorderSpace;    RtfKStr: '\brsp'         ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfCellBordBottom; RtfKStr: '\clbrdrb'      ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfCellBordTop;    RtfKStr: '\clbrdrt'      ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfCellBordLeft;   RtfKStr: '\clbrdrl'      ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfCellBordRight;  RtfKStr: '\clbrdrr'      ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowDef;         RtfKStr: '\trowd'        ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowLeft;        RtfKStr: '\trql'         ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowRight;       RtfKStr: '\trqr'         ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowCenter;      RtfKStr: '\trqc'         ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowGapH;        RtfKStr: '\trgaph'       ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowHt;          RtfKStr: '\trrh'         ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfRowLeftEdge;    RtfKStr: '\trleft'       ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfCellPos;        RtfKStr: '\cellx'        ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfMergeRngFirst;  RtfKStr: '\clmgf'        ),
    (RtfKMajor: RtfTblAttr;     RtfKMinor: RtfMergePrevious;  RtfKStr: '\clmrg'        ),
    (RtfKMajor: RtfTOCAttr;     RtfKMinor: RtfTOCType;        RtfKStr: '\tcf'          ),
    (RtfKMajor: RtfTOCAttr;     RtfKMinor: RtfTOCLevel;       RtfKStr: '\tcl'          ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFNil;          RtfKStr: '\fnil'         ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFRoman;        RtfKStr: '\froman'       ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFSwiss;        RtfKStr: '\fswiss'       ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFModern;       RtfKStr: '\fmodern'      ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFScript;       RtfKStr: '\fscript'      ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFDecor;        RtfKStr: '\fdecor'       ),
    (RtfKMajor: RtfFontFamily;  RtfKMinor: RtfFFTech;         RtfKStr: '\ftech'        ),
    (RtfKMajor: RtfCharSet;     RtfKMinor: RtfMacCharSet;     RtfKStr: '\mac'          ),
    (RtfKMajor: RtfCharSet;     RtfKMinor: RtfAnsiCharSet;    RtfKStr: '\ansi'         ),
    (RtfKMajor: RtfCharSet;     RtfKMinor: RtfPcCharSet;      RtfKStr: '\pc'           ),
    (RtfKMajor: RtfCharSet;     RtfKMinor: RtfPcaCharSet;     RtfKStr: '\pca'          ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfPlain;          RtfKStr: '\plain'        ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfBold;           RtfKStr: '\b'            ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfItalic;         RtfKStr: '\i'            ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfStrikeThru;     RtfKStr: '\strike'       ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfOutline;        RtfKStr: '\outl'         ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfShadow;         RtfKStr: '\shad'         ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfSmallCaps;      RtfKStr: '\scaps'        ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfAllCaps;        RtfKStr: '\caps'         ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfInvisible;      RtfKStr: '\v'            ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfFontNum;        RtfKStr: '\f'            ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfFontSize;       RtfKStr: '\fs'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfExpand;         RtfKStr: '\expnd'        ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfUnderline;      RtfKStr: '\ul'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfWUnderline;     RtfKStr: '\ulw'          ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfDUnderline;     RtfKStr: '\uld'          ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfDbUnderline;    RtfKStr: '\uldb'         ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfNoUnderline;    RtfKStr: '\ulnone'       ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfSuperScript;    RtfKStr: '\up'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfSubScript;      RtfKStr: '\dn'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfRevised;        RtfKStr: '\revised'      ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfForeColor;      RtfKStr: '\cf'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfBackColor;      RtfKStr: '\cb'           ),
    (RtfKMajor: RtfCharAttr;    RtfKMinor: RtfGray;           RtfKStr: '\gray'         ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfFormula;        RtfKStr: '\|'            ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfNoBrkSpace;     RtfKStr: '\~'            ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfNoReqHyphen;    RtfKStr: '\-'            ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfNoBrkHyphen;    RtfKStr: '\_'            ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfOptDest;        RtfKStr: '\*'            ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfPar;            RtfKstr: #10             ),
    (RtfKMajor: RtfSpecialChar; RtfKMinor: RtfPar;            RtfKstr: #13             ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosX;           RtfKStr: '\posx'         ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosXCenter;     RtfKStr: '\posxc'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosXInside;     RtfKStr: '\posxi'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosXLeft;       RtfKStr: '\posxl'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosXOutSide;    RtfKStr: '\posxo'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosXRight;      RtfKStr: '\posxr'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosY;           RtfKStr: '\posy'         ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosYInline;     RtfKStr: '\posyil'       ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosYTop;        RtfKStr: '\posyt'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosYCenter;     RtfKStr: '\posyc'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfPosYBottom;     RtfKStr: '\posyb'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfAbsWid;         RtfKStr: '\absw'         ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfTextDist;       RtfKStr: '\dxfrtext'     ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfRPosMargV;      RtfKStr: '\pvmrg'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfRPosPageV;      RtfKStr: '\pvpg'         ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfRPosMargH;      RtfKStr: '\phmrg'        ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfRPosPageH;      RtfKStr: '\phpg'         ),
    (RtfKMajor: RtfPosAttr;     RtfKMinor: RtfRPosColH;       RtfKStr: '\phcol'        ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfSectDef;        RtfKStr: '\sectd'        ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfNoBreak;        RtfKStr: '\sbknone'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfColBreak;       RtfKStr: '\sbkcol'       ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageBreak;      RtfKStr: '\sbkpage'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfEvenBreak;      RtfKStr: '\sbkeven'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfOddBreak;       RtfKStr: '\sbkodd'       ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageCont;       RtfKStr: '\pgncont'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageStarts;     RtfKStr: '\pgnstarts'    ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageRestart;    RtfKStr: '\pgnrestart'   ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageDecimal;    RtfKStr: '\pgndec'       ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageURoman;     RtfKStr: '\pgnucrm'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageLRoman;     RtfKStr: '\pgnlcrm'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageULetter;    RtfKStr: '\pgnucltr'     ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageLLetter;    RtfKStr: '\pgnlcltr'     ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageNumLeft;    RtfKStr: '\pgnx'         ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfPageNumTop;     RtfKStr: '\pgny'         ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfHeaderY;        RtfKStr: '\headery'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfFooterY;        RtfKStr: '\footery'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineModulus;    RtfKStr: '\linemod'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineDist;       RtfKStr: '\linex'        ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineStarts;     RtfKStr: '\linestarts'   ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineRestart;    RtfKStr: '\linerestart'  ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineRestartPg;  RtfKStr: '\lineppage'    ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfLineCont;       RtfKStr: '\linecont'     ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfTopVAlign;      RtfKStr: '\vertalt'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfBottomVAlign;   RtfKStr: '\vertal'       ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfCenterVAlign;   RtfKStr: '\vertalc'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfJustVAlign;     RtfKStr: '\vertalj'      ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfColumns;        RtfKStr: '\cols'         ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfColumnSpace;    RtfKStr: '\colsx'        ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfColumnLine;     RtfKStr: '\linebetcol'   ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfENoteHere;      RtfKStr: '\endnhere'     ),
    (RtfKMajor: RtfSectAttr;    RtfKMinor: RtfTitleSpecial;   RtfKStr: '\titlepg'      )
    (RtfKMajor: RtfFieldAttr;   RtfKMinor: RtfFieldDirty;     RtfKStr: '\flddirty'     ),
    (RtfKMajor: RtfFieldAttr;   RtfKMinor: RtfFieldEdited;    RtfKStr: '\fldedit'      ),
    (RtfKMajor: RtfFieldAttr;   RtfKMinor: RtfFieldLocked;    RtfKStr: '\fldlock'      ),
    (RtfKMajor: RtfFieldAttr;   RtfKMinor: RtfFieldPrivate;   RtfKStr: '\fldpriv'      ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfPaperWidth;     RtfKStr: '\paperw'       ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfPaperHeight;    RtfKStr: '\paperh'       ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfLeftMargin;     RtfKStr: '\margl'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfRightMargin;    RtfKStr: '\margr'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfTopMargin;      RtfKStr: '\margt'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfBottomMargin;   RtfKStr: '\margb'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFacingPage;     RtfKStr: '\facingp'      ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfGutterWid;      RtfKStr: '\gutter'       ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfDefTab;         RtfKStr: '\deftab'       ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfWidowCtrl;      RtfKStr: '\widowctrl'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfHyphHotZone;    RtfKStr: '\hyphhotz'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteEndSect;   RtfKStr: '\endnotes'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteEndDoc;    RtfKStr: '\enddoc'       ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteBottom;    RtfKStr: '\ftnbj'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteText;      RtfKStr: '\ftntj'        ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteStart;     RtfKStr: '\ftnstart'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFNoteRestart;   RtfKStr: '\ftnrestart'   ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfPageStart;      RtfKStr: '\pgnstart'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfLineStart;      RtfKStr: '\linestart'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfLandscape;      RtfKStr: '\landscape'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfFracWidth;      RtfKStr: '\fracwidth'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfNextFile;       RtfKStr: '\nextfile'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfTemplate;       RtfKStr: '\template'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfMakeBackup;     RtfKStr: '\makeback'     ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfRtfDefault;     RtfKStr: '\defformat'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfRevisions;      RtfKStr: '\revisions'    ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfMirrorMargin;   RtfKStr: '\margmirror'   ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfRevDisplay;     RtfKStr: '\revprop'      ),
    (RtfKMajor: RtfDocAttr;     RtfKMinor: RtfRevBar;         RtfKStr: '\revbar'       ),
    (RtfKMajor: RtfStyleAttr;   RtfKMinor: RtfBasedOn;        RtfKStr: '\sbasedon'     ),
    (RtfKMajor: RtfStyleAttr;   RtfKMinor: RtfNext;           RtfKStr: '\snext'        ),
    (RtfKMajor: RtfColorName;   RtfKMinor: RtfRed;            RtfKStr: '\red'          ),
    (RtfKMajor: RtfColorName;   RtfKMinor: RtfGreen;          RtfKStr: '\green'        ),
    (RtfKMajor: RtfColorName;   RtfKMinor: RtfBlue;           RtfKStr: '\blue'         ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfMacQD;          RtfKStr: '\macpict'      ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfWinMetafile;    RtfKStr: '\wmetafile'    ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfWinBitmap;      RtfKStr: '\wbitmap'      ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicWid;         RtfKStr: '\picw'         ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicHt;          RtfKStr: '\pich'         ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicGoalWid;     RtfKStr: '\picwgoal'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicGoalWid;     RtfKStr: '\picwGoal'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicGoalHt;      RtfKStr: '\pichgoal'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicGoalHt;      RtfKStr: '\pichGoal'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicScaleX;      RtfKStr: '\picscalex'    ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicScaleY;      RtfKStr: '\picscaley'    ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicScaled;      RtfKStr: '\picscaled'    ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicCropTop;     RtfKStr: '\piccropt'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicCropBottom;  RtfKStr: '\piccropb'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicCropLeft;    RtfKStr: '\piccropl'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicCropRight;   RtfKStr: '\piccropr'     ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPixelBits;      RtfKStr: '\wbmbitspixel' ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfBitmapPlanes;   RtfKStr: '\wbmplanes'    ),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfBitmapWid;      RtfKStr: '\wbmwidthbytes'),
    (RtfKMajor: RtfPictAttr;    RtfKMinor: RtfPicBinary;      RtfKStr: '\bin'          ),
    (RtfKMajor: RtfNeXTGrAttr;  RtfKMinor: RtfNeXTGWidth;     RtfKStr: '\width'        ),
    (RtfKMajor: RtfNeXTGrAttr;  RtfKMinor: RtfNeXTGHeight;    RtfKStr: '\height'       ),
    }
  {@indent on}

const
  TRtfAnyType: TRtfTokenSet =[etDataset..etLitTrue];

function ExtractFieldName(const Fields: string; var Pos: integer): string;
var i: integer;
begin
  i := Pos;
  while(i <= Length(Fields))and(Fields[i] <> '.')do Inc(i);
  Result := Trim(Copy(Fields, Pos, i - Pos));
  if(i <= Length(Fields))and(Fields[i] = '.')
  then Inc(i);
  Pos := i;
end;

function Pwr(const Base, Exponent: Double): Double;
begin
  if Exponent = 0.0 then
    Result := 1.0 { n**0 = 1 }
  else if(Base = 0.0)and(Exponent > 0.0) then
    Result := 0.0 { 0**n = 0, n > 0 }
  else if (Frac(Exponent) = 0.0) and (Abs(Exponent) <= MaxInt) then
    Result := IntPower(Base, integer(Trunc(Exponent)))
  else
    Result := Exp(Exponent * Ln(Base))
end;

{ TRtfPictureAttr }

constructor TRtfPictureAttr.Create(AWidth, AHeigth: word);
begin
  inherited Create;
  FScaleX := 100;
  FScaleY := 100;
  FWidth := AWidth;
  FHeigth := AHeigth;
  FWidthmm := AWidth * 0.264596930676;
  FHeigthmm := AHeigth * 0.264596930676;

  FBorderWidth := 0;
  FBorderType := brNone;
  FBorderColor := clBlack;
  FProportional := true;
end;

procedure TRtfPictureAttr.SetScaleX(Value: integer);
var
  AScale: Double;
begin
  if Value < 1 then
    Value := 1
  else if Value > 100 then
    Value := 100;
  AScale := Double(Value) / FScaleX;
  FScaleX := Value;
  FWidth := Round(FWidth * AScale);
  FWidthmm := FWidthmm * AScale;
  if FProportional then
  begin
    FScaleY := Round(FScaleY * AScale);
    FHeigth := Round(FHeigth * AScale);
    FHeigthmm := FHeigthmm * AScale;
  end;
end;

procedure TRtfPictureAttr.SetScaleY(Value: integer);
var
  AScale: Double;
begin
  if Value < 1 then
    Value := 1
  else if Value > 100 then
    Value := 100;
  AScale := Double(Value) / FScaleY;
  FScaleY := Value;
  FHeigth := Round(FHeigth * AScale);
  FHeigthmm := FHeigthmm * AScale;
  if FProportional then
  begin
    FScaleX := Round(FScaleX * AScale);
    FWidth := Round(FWidth * AScale);
    FWidthmm := FWidthmm * AScale;
  end;
end;


{ TRtfItem }

procedure TRtfItem.Assign(ASource: TRtfItem);
begin
  RtfClass := ASource.RtfClass;
  RtfMajor := ASource.RtfMajor;
  RtfMinor := ASource.RtfMinor;
  RtfTextBuf := ASource.RtfTextBuf;
end;

function TRtfItem.CheckItem(AClass: TRtfClass; Major: integer): boolean;
begin
  Result :=(RtfClass = AClass)and(RtfMajor = Major);
end;

function TRtfItem.GetItem(Index: integer): TRtfItem;
begin
  Result := TRtfItem(inherited Items[Index]);
end;

procedure TRtfItem.Notify(Ptr: pointer; Action: TListNotification);
begin
  inherited;
  case Action of
    lnAdded: TRtfItem(Ptr).FParent := Self;
    lnExtracted: TRtfItem(Ptr).FParent := nil;
  end;
end;

{ TRtfItemList }

constructor TRtfItemList.Create;
//Initialize an empty list
begin
  inherited Create;
end;

destructor TRtfItemList.Destroy;
{-Destroy a list}
var n: TRtfItem;
  p: TRtfItem;
begin
  n := FTail;
  while n <> nil do begin
    {Get TRtfItem to previous node}
    p := n.FPrev;
    {Deallocate and destroy this node}
    n.Free;
    {Do the previous node}
    n := p;
  end;
  FTail := nil;
  FHead := nil;
  FCount := 0;
  inherited Destroy;
end;

function TRtfItemList.Add(AItem: TRtfItem): TRtfItem;
{-Add element to end of list}
begin
  Result := AItem;
  {Exit for bad input}
  if AItem = nil
  then Exit;
  AItem.FPrev := FTail;
  AItem.FNext := nil;
  if FHead = nil then begin
    {Special case for first node}
    FHead := AItem;
    FTail := AItem;
  end else begin
    {Add at end of existing list}
    FTail.FNext := AItem;
    FTail := AItem;
  end;
  Inc(FCount);
end;

procedure TRtfItemList.Insert(AItem: TRtfItem);
{-Insert element at start of list}
begin
  {Exit for bad input}
  if AItem = nil
  then Exit;
  AItem.FPrev := nil;
  AItem.FNext := FHead;
  if FHead = nil
  then FTail := AItem {Special case for first node}
  else FHead.FPrev := AItem; {Add at start of existing list}
  FHead := AItem;
  Inc(FCount);
end;

procedure TRtfItemList.PlaceAfter(AItem: TRtfItem; AAfter: TRtfItem);
{-Place element P into list _after_ existing element L}
begin
  {Exit for bad input}
  if(AItem = nil)or(AItem = AAfter)
  then Exit;
  if AAfter = nil
  then Insert(AItem)
  else if AAfter = FTail
  then Add(AItem)
  else begin
    AItem.FPrev := AAfter;
    AItem.FNext := AAfter.FNext;
    AAfter.FNext.FPrev := AItem;
    AAfter.FNext := AItem;
    Inc(FCount);
  end;
end;

procedure TRtfItemList.PlaceBefore(AItem, ABefore: TRtfItem);
{-Place element P into list _before_ existing element L}
begin
  {Exit for bad input}
  if(AItem = nil)or(AItem = ABefore)
  then Exit;
  if(ABefore = nil)or(ABefore = Head)
  then Insert(AItem) {Place the new element at the start of the list}
  else begin
    {Patch in the new element}
    AItem.FNext := ABefore;
    AItem.FPrev := ABefore.FPrev;
    ABefore.FPrev.FNext := AItem;
    ABefore.FPrev := AItem;
    Inc(FCount);
  end;
end;

procedure TRtfItemList.dlRemove(AItem: TRtfItem; DisposeIt: boolean);
{-Delete existing node from list, optionally disposing of it}
var This: TRtfItem;
begin
  {Exit for bad input}
  if(AItem = nil)or(FCount = 0)
  then Exit;

  This := AItem;
  with This do begin
    {Fix pointers of surrounding nodes}
    if FNext <> nil
    then FNext.FPrev := FPrev;
    if FPrev <> nil
    then FPrev.FNext := FNext;
  end;

  {Fix head and tail of list}
  if FTail = This
  then FTail := FTail.FPrev;
  if FHead = This
  then FHead := FHead.FNext;

  Dec(FCount);
  if DisposeIt
  then This.Free;
end;

procedure TRtfItemList.Extract(AItem: TRtfItem);
{-Extract existing element from list without disposing of it}
begin
  dlRemove(AItem, false);
end;

procedure TRtfItemList.Delete(AItem: TRtfItem);
{-Delete an existing node, disposing of its contents}
begin
  dlRemove(AItem, true);
end;

procedure TRtfItemList.Clear;
begin
  while Assigned(FHead)do begin
    dlRemove(FHead, true);
  end;
end;

procedure TRtfItemList.SaveToStream(AStream: TStream; AColors: string);
var AItem: TRtfItem;
  ALine: string;
begin
  AItem := Head;
  while Assigned(AItem)do begin
    if AItem.CheckItem(RtfControl, RtfDestination)and(AItem.RtfMinor = RtfColorTbl)
    then ALine := Format('\colortbl;%s}',[AColors])
    else ALine := AItem.RtfTextBuf;
    if ALine <> ''
    then AStream.Write(ALine[1], Length(ALine));
    AItem := AItem.Next;
  end;
end;

{ TRawRtfParser }

procedure TRawRtfParser.RtfHook;
//Build a tree from the rtf-code tokens
var AItem: TRtfItem;


  function NewItem(AText: string): TRtfItem;
  begin
    Result := TRtfItem.Create;
    Result.RtfClass := RtfClass;
    Result.RtfMajor := RtfMajor;
    Result.RtfMinor := RtfMinor;
    Result.RtfTextBuf := AText;
  end;
begin
  case RtfClass of
    RtfParseBegin: begin
      if Assigned(AParseItem) then begin
        //Then close it
        AParseItem := nil;
        AItem := RawItems.Add(NewItem(''));
        AItem.RtfClass := RtfParseEnd;
      end else begin
        //Otherwise open an item
        AParseItem := RawItems.Add(NewItem(''));
        AParseItem.RtfClass := RtfParseBegin;
      end;
    end;
    RtfControl: begin
      if(RtfMajor = RtfDestination)and(RtfMinor = RtfColorTbl)
      then FColorTable := RawItems.Add(NewItem(RtfTextBuf))
      else RawItems.Add(NewItem(RtfTextBuf));
    end;
    RtfText: begin
      if RawItems.Tail.RtfClass = RtfClass
      then RawItems.Tail.RtfTextBuf := RawItems.Tail.RtfTextBuf + RtfTextBuf
      else RawItems.Add(NewItem(RtfTextBuf));
    end;
    RtfGroup, RtfUnknown: begin
      if RawItems.Tail.RtfClass in[RtfGroup, RtfUnknown]
      then RawItems.Tail.RtfTextBuf := RawItems.Tail.RtfTextBuf + RtfTextBuf
      else RawItems.Add(NewItem(RtfTextBuf));
      RawItems.Tail.RtfClass := RtfUnknown; //Dont use these for compares
    end;
  end;
end;

function TRawRtfParser.GetRtfChar: char;
begin
  if APtr >= AEnd
  then Result := #0
  else begin
    Result := APtr^;
    Inc(APtr);
  end;
end;

procedure TRawRtfParser.GetRtfToken;
var c: char;
  i, ALevel: integer;
begin
  FRtfTextBuf := ''; //not really needed

  //Get first character, which may be a pushback from previous token
  if APushedChar <> #0 then begin
    c := APushedChar;
    APushedChar := #0;
  end
  else c := GetRtfChar;


  case c of
    #0: begin
      FRtfClass := RtfEof;
      FRtfTextBuf := '';
    end;
    #8: begin //effectively a \tab control symbol
      FRtfClass := RtfControl;
      FRtfMajor := RtfSpecialChar;
      FRtfMinor := RtfTab;
      FRtfTextBuf := c;
      c := #0;
    end;
    '{': begin
      FRtfClass := RtfGroup;
      FRtfMajor := RtfBeginGroup;
      FRtfTextBuf := c;
      c := #0;
    end;
    '}': begin
      FRtfClass := RtfGroup;
      FRtfMajor := RtfEndGroup;
      FRtfTextBuf := c;
      c := #0;
    end;
    '\': begin //We have the backslash, advance to next character
      FRtfTextBuf := c;
      c := GetRtfChar;
      case c of
        chr(39): begin //Hex encoded text char, e.g., \'d5, \'d3
          FRtfClass := RtfUnknown;
          FRtfTextBuf := FRtfTextBuf + c;
          c := GetRtfChar;
          if c <> #0 then begin
            FRtfTextBuf := FRtfTextBuf + c;
            c := GetRtfChar;
            if c <> #0 then begin
              FRtfClass := RtfText;
              FRtfTextBuf := FRtfTextBuf + c;
              //It can still be a special character..
              for i := Low(Rtfkey)to High(Rtfkey)do begin
                if FRtfTextBuf = Rtfkey[i].RtfKStr then begin
                  FRtfClass := RtfControl;
                  FRtfMajor := Rtfkey[i].RtfKMajor;
                  FRtfMinor := Rtfkey[i].RtfKMinor;
                  break;
                end;
              end;
              c := #0;
            end;
          end;
        end;
        ':', '{', '}', ';', '\': begin //special escaped text char, e.g., \, \;
          FRtfTextBuf := FRtfTextBuf + c;
          //"\" Marks the start and end of an expression with the RtfParseBegin
          //RtfClass. They will later be removed and replaced by RtfExpression
          //Items between the opening and closing \ will be the expression text
          if c = '\'
          then FRtfClass := RtfParseBegin
          else FRtfClass := RtfText;
          c := #0;
        end;
        '|': begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfFormula;
          c := #0;
        end;
        '~': begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfNoBrkSpace;
          c := #0;
        end;
        '-': begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfNoReqHyphen;
          c := #0;
        end;
        '_': begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfNoBrkHyphen;
          c := #0;
        end;
        '*': begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfOptDest;
          c := #0;
        end;
        #13, #10: begin
          FRtfTextBuf := FRtfTextBuf + c;
          FRtfClass := RtfControl;
          FRtfMajor := RtfSpecialChar;
          FRtfMinor := RtfPar;
          c := #0;
        end;
        else begin //Wasn't anything special, continue with control word

          while(c in['A'..'Z', 'a'..'z'])do begin
            FRtfTextBuf := FRtfTextBuf + c;
            c := GetRtfChar;
          end;

          //Find the control word in the key array
          FRtfClass := RtfUnknown;
          for i := Low(Rtfkey)to High(Rtfkey)do begin
            if FRtfTextBuf = Rtfkey[i].RtfKStr then begin
              FRtfClass := RtfControl;
              FRtfMajor := Rtfkey[i].RtfKMajor;
              FRtfMinor := Rtfkey[i].RtfKMinor;
              break;
            end;
          end;

          //Parse the word parameter negative sign
          if c = '-' then begin
            FRtfTextBuf := FRtfTextBuf + c;
            c := GetRtfChar;
          end;
          //Parse the word parameter number
          while(c in['0'..'9'])do begin
            FRtfTextBuf := FRtfTextBuf + c;
            c := GetRtfChar;
          end;

          //Append control symbol delimiter (i need it for writing)
          if c = ' ' then begin
            FRtfTextBuf := FRtfTextBuf + c;
            c := GetRtfChar;
          end;

          //Crap1: Fix for {\field{\*\fldinst SYMBOL 32 \\f "Symbol" \\s 12}{\fldrslt\...
          //RTF text gets corrupted by this parser (notice the Double backslash!)
          //Crap2:Also INFO since it can contain the first line from rtf as docinfo.
          if(FRtfClass = RtfControl)and(FRtfMajor = RtfDestination) then begin
            if FRtfMinor in[RtfField, RtfInfo, RtfStyleSheet, RtfFontTbl, RtfColorTbl] then begin
              //Just include the whole field Group to the TextBuf (who cares..?)
              ALevel := 1; //All these items have a "group open" before them
              while c <> #0 do begin
                FRtfTextBuf := FRtfTextBuf + c;
                case c of
                  '{': Inc(ALevel);
                  '}': Dec(ALevel);
                end;
                c := GetRtfChar;
                if ALevel = 0
                then break;
              end;
              FRtfClass := RtfControl;
            end;
          end;
        end;
      end;
    end;
    else
    begin
      //literal text char. This will give one character per call (which is slow)
      FRtfTextBuf := c;
      FRtfClass := RtfText;

      c := GetRtfChar;
      while not(c in[#0, #8, '\', '{', '}']) do
      begin
        FRtfTextBuf := FRtfTextBuf + c;
        c := GetRtfChar;
      end;
    end;
  end;

  //Push character back if we read one to much
  if c <> #0 then
    APushedChar := c;
end;

procedure TRawRtfParser.Execute(ARawItems: TRtfItemList; ARtfPtr: pchar; ARtfSize: integer);
var AItem: TRtfItem;
begin
  APtr := ARtfPtr;
  APushedChar := #0;
  RawItems := ARawItems;
  FRtfClass := RtfNothing;
  AEnd := APtr + ARtfSize;

  //Dummy item so tail of list is always assigned
  AItem := TRtfItem.Create;
  AItem.RtfClass := RtfText;
  ARawItems.Add(AItem);

  while true do
  begin
    GetRtfToken;
    if RtfClass = RtfEOF then
      break;
    RtfHook;
  end;
end;

{ TRtfVariableList }

function TRtfVariableList.Add(AName: string; AValue: variant; AToken: TRtfToken): TRtfVariable;
begin
  Result := Find(AName);
  if Assigned(Result) then
    raise TRtfException.CreateFmt('Variable %s already exists',[AName]);
  Result := TRtfVariable.Create;
  inherited Add(Result);
  Result.Name := AName;
  Result.Value := AValue;
  Result.Token := AToken;
end;

destructor TRtfVariableList.Destroy;
begin
  inherited;
end;

function TRtfVariableList.Find(AName: string): TRtfVariable;
var i: integer;
begin
  for i := 0 to Count - 1 do begin
    Result := Items[i];
    if SameText(Result.Name, AName)
    then exit;
  end;
  Result := nil;
end;

function TRtfVariableList.GetItem(Index: integer): TRtfVariable;
begin
  Result := TRtfVariable(inherited Items[Index]);
end;

{ TRtfFunctionList }

function TRtfFunctionList.GetItem(Index: integer): TRtfFunction;
begin
  Result := TRtfFunction(inherited Items[Index]);
end;

function TRtfFunctionList.Add(ATokenType: TRtfToken; AName: string; AMin, AMax: smallint; AOnexecute: TRtfFunctionExecute): TRtfFunction;
//Add a new function or even an additional token to the function list
begin
  Result := Find(AName);
  if Assigned(Result)
  then raise TRtfException.CreateFmt('Function already exists',[AName]);

  Result := TRtfFunction.Create;
  Result.Name := AName;
  Result.Min := AMin;
  Result.Max := AMax;
  Result.Token := ATokenType;
  Result.Onexecute := AOnexecute;
  inherited Add(Result);
end;

function TRtfFunctionList.Find(AName: string): TRtfFunction;
var i: integer;
begin
  for i := 0 to Count - 1 do begin
    Result := Items[i];
    if SameText(Result.Name, AName)
    then exit;
  end;
  Result := nil;
end;

{ TRtfDataset }

procedure TRtfDataset.Notify(Ptr: pointer; Action: TListNotification);
begin
  inherited;
  case Action of
    lnAdded: TRtfDataset(Ptr).FParent := Self;
    lnExtracted: TRtfDataset(Ptr).FParent := nil;
  end;
end;

function TRtfDataset.Bof: boolean;
begin
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      Result := Bof;
    end
  end
  else if Dataset is TtiObjectList then
    Result := TableIndex = 0
  else if Dataset is TtiObject then
    Result := false
  else
    raise TRtfException.Create(rsNotImplemented);
end;

function TRtfDataset.Eof: boolean;
begin
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      Result := Eof;
    end
  end
  else if Dataset is TtiObjectList then
    Result :=(TableIndex >= RecordCount)or(TableIndex < 0)
  else if Dataset is TtiObject then
    Result := false
  else
    Result := false;
end;

function TRtfDataset.Find(AName: string): TRtfDataset;
var i: integer;
begin
  for i := 0 to Count - 1 do begin
    Result := Items[i];
    if SameText(Result.Name, AName)
    then exit;
  end;
  Result := nil;
end;

function TRtfDataset.Add(ADataset: TObject; AName: string; AFreeDataset: boolean = false): TRtfDataset;
begin
  Result := Find(AName);
  if Assigned(Result) then
    raise TRtfException.CreateFmt('Dataset already exists',[AName]);

  Result := TRtfDataset.Create;
  Result.Dataset := ADataset;
  Result.Name := AName;
  Result.FFreeDataset := AFreeDataset;
  inherited Add(Result);
end;

function TRtfDataset.ResolveNestedFields(ATable: TRtfDataset; AName: string; var AFieldName: string): TRtfDataset;
//Advance to field level (skipping nested dataset objects)
var ATableName: string;
  APropInfo: PPropInfo;
  ASubTable: TRtfDataset;
  AIndex, i: integer;
  AObject: TObject;
begin
  AIndex := 1;
  Result := ATable;
  AFieldName := AName;
  while AIndex < Length(AName)do begin

    //Check object dataset and eof state
    AObject := nil; 
    if Result.Dataset is TDataset
    then exit; //A TDataset is never nested
    if Result.Dataset is TtiObjectList then begin
      //Get the right record from the array
      if Result.TableIndex <(Result.Dataset as TtiObjectList).Count
      then AObject :=(Result.Dataset as TtiObjectList)[Result.TableIndex]
      else exit; //Trying beyond eof (or empty table) big problem; nah?
    end else if Result.Dataset is TtiObject
    then AObject := Result.Dataset
    else raise TRtfException.Create('Unknown object');

    //If the next field is a class then advance
    ASubTable := nil;
    ATableName := ExtractFieldName(AName, AIndex);
    APropInfo := GetPropInfo(AObject, ATableName);
    if not Assigned(APropInfo)or(APropInfo^.PropType^.Kind <> tkClass)
    then exit; //As long as it's an object continue parsing..

    //Advance fieldname and find nested table
    AFieldName := Copy(AName, AIndex, Maxint);
    for i := 0 to Result.Count - 1 do begin
      if SameText(Result[i].Name, ATableName) then begin
        ASubTable := Result[i];
        break;
      end;
    end;

    //Add the nested table (for administration of the TableIndex)
    if not Assigned(ASubTable) then begin
      APropInfo := GetPropInfo(AObject, ATableName);
      if not Assigned(APropInfo)
      then raise TRtfException.CreateFmt('property %s not found',[ATableName]);
      if APropInfo^.PropType^.Kind = tkClass
      then AObject := GetObjectProp(AObject, APropInfo)
      else exit; //Just a plain property field (returned via AFieldName)
      ASubTable := Result.Add(AObject, ATableName);
    end;

    //Advance to a deeper table level
    Result := ASubTable;
  end;
end;

function TRtfDataset.Find(AName: string; out AFieldName: string): TRtfDataset;
//Find the requested dataset
var
  ATableName: string;
  AIndex, i: integer;
begin
  //MainTable must be in the list of tables
  //Otherwise no point of reference.
  AIndex := 1;
  Result := nil;
  ATableName := ExtractFieldName(AName, AIndex);
  AFieldName := Copy(AName, AIndex, Maxint);
  for i := 0 to Count - 1 do begin
    if SameText(Items[i].Name, ATableName) then begin
      Result := Items[i];
      break;
    end;
  end;
  if not Assigned(Result)or not Assigned(Result.Dataset)
  then raise TRtfException.CreateFmt('Unable to resolve %s',[ATableName]);
  Result := ResolveNestedFields(Result, AFieldName, AFieldName);
end;

procedure TRtfDataset.Open;
begin
  Clear; //Clear nested tables
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      if not Active
      then Open;
    end
  end;
  First;
end;

procedure TRtfDataset.First;
begin
  Clear; //Clear nested tables
  if Dataset is TDataset then
  begin
    with Dataset as TDataset do
    begin
      First;
    end
  end
  else if Dataset is TtiObjectList then
  begin
    TableIndex := 0;
  end;
end;

function TRtfDataset.GetItem(Index: integer): TRtfDataset;
begin
  Result := TRtfDataset(inherited Items[Index]);
end;

function TRtfDataset.IsEmpty: boolean;
begin
  if Dataset is TDataset then
  begin
    with Dataset as TDataset do
    begin
      Result := IsEmpty;
    end
  end
  else if Dataset is TtiObjectList then
    Result := RecordCount = 0
  else if Dataset is TtiObject then
    Result := false
  else
    raise TRtfException.Create(rsNotImplemented);
end;

procedure TRtfDataset.Last;
begin
  Clear; //Clear nested tables
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      Last;
    end
  end else if Dataset is TtiObjectList then begin
    TableIndex := RecordCount - 1;
  end;
end;

procedure TRtfDataset.Next;
begin
  Clear; //Clear nested tables
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      Next;
    end
  end else if Dataset is TtiObjectList then begin
    if not Eof then begin
      TableIndex := TableIndex + 1;
    end;
  end;
end;

procedure TRtfDataset.Prior;
begin
  Clear; //Clear nested tables
  if Dataset is TDataset then begin
    with Dataset as TDataset do begin
      Prior;
    end
  end else if Dataset is TtiObjectList then begin
    if not Bof then begin
      TableIndex := TableIndex - 1;
    end;
  end;
end;

function TRtfDataset.RecordCount: integer;
//This can give problems with Sql..
begin
  if Dataset is TDataset
  then Result :=(Dataset as TDataset).RecordCount
  else if Dataset is TtiObjectList
  then Result :=(Dataset as TtiObjectList).Count
  else Result := 1; //Single OpfRecord
end;

destructor TRtfDataset.Destroy;
begin
  if FreeDataset
  then FreeAndNil(FDataset);
  inherited;
end;


{ TRtfArgument }

constructor TRtfArgument.Create(AParser: TtiRtfParser);
begin
  inherited Create(true);
  FParser := AParser;
end;

function TRtfArgument.Add(AValue: variant; ATokenType: TRtfToken): TRtfArgument;
begin
  Result := TRtfArgument.Create(Parser);
  inherited Add(Result);
  Result.Value := AValue;
  Result.Token := ATokenType;
end;

function TRtfArgument.Add(AArgument: TRtfArgument): TRtfArgument;
begin
  inherited Add(AArgument);
  Result := AArgument;
end;

function TRtfArgument.GetItem(Index: integer): TRtfArgument;
begin
  Result := TRtfArgument(inherited Items[Index]);
end;

procedure TRtfArgument.Notify(Ptr: pointer; Action: TListNotification);
//Nice way of setting the parent reference
begin
  inherited;
  case Action of
    lnAdded: TRtfArgument(Ptr).FParent := Self;
    lnExtracted: TRtfArgument(Ptr).FParent := nil;
  end;
end;

function TRtfArgument.Check(AParam: integer; ATokens: TRtfTokenSet): boolean;
begin
  if AParam >= Count then begin
    Result := false;
    exit;
  end;
  if not(Items[AParam].Token in ATokens) then begin
    Result := false;
    exit;
  end;
  Result := true;
end;

function TRtfArgument.Check(ATokens: array of TRtfTokenSet): boolean;
var i: integer;
begin
  for i := Low(ATokens)to High(ATokens)do begin
    Result := Check(i, ATokens[i]);
    if not Result
    then exit;
  end;
  Result := true;
end;

procedure TRtfArgument.ParseExpression(AExpression: string);
//Add token to the argument list. Parameters surrounded by parentheses will
//be added to the nested arguments. This will make a nice argument tree.
//Constant .9 wont be parse, but that's ok
var
  FSourcePtr, p, TokenStart: PChar;
  ALastArgument, ALast: TRtfArgument;
  AInts: array[0..6]of integer;
  ASeps: array[0..6]of char;
  AFunction: TRtfFunction;
  AFloatResult: boolean;
  AIntIndex: integer;
  AValue: variant;
  AToken: string;
begin
  ALast := nil;
  Value := varEmpty;
  Token := etNothing;
  ALastArgument := Self;
  FSourcePtr := PChar(AExpression);
  while FSourcePtr^ <> #0 do begin

    p := FSourcePtr;
    while(P^ <> #0)and(P^ <= ' ')do begin
      ALast := nil;
      Inc(p);
    end;

    TokenStart := p;
    case P^ of
      'A'..'Z', 'a'..'z', '_', '@': begin // The '@' infront of a reference variable
        Inc(p);
        ALast := nil;
        while P^ in['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '@']do Inc(p);
        if TokenStart^ = '@' then begin
          Inc(TokenStart); //Remove the '@' prefix
          SetString(AToken, TokenStart, p - TokenStart);
          ALast := ALastArgument.Add(AToken, etVariable)
        end else begin
          SetString(AToken, TokenStart, p - TokenStart);
          AFunction := Parser.Functions.Find(AToken);
          if Assigned(AFunction)
          then ALastArgument.Add(AFunction.Name, AFunction.Token)
          else ALast := ALastArgument.Add(AToken, etFieldName); //Field or tablename, what else can it be?
        end;
      end;
      Chr(39): begin
        Inc(p);
        TokenStart := p;
        while true do begin
          if P^ = Chr(39) then begin
            SetString(AToken, TokenStart, p - TokenStart);
            //Concatenate etFieldName."Field with spaces"
            if Assigned(ALast)and(ALast.Token in[etVariable, etFieldName])
            then ALast.Value := ALast.Value + AToken
            else ALastArgument.Add(AToken, etLitString);
            Inc(p);
            Break;
          end;
          if P^ = #0
          then raise TRtfException.Create(rsUnterminatedStringConstant);
          Inc(p);
        end;
      end;
      '"': begin
        Inc(p);
        TokenStart := p;
        while true do begin
          if P^ = '"' then begin
            SetString(AToken, TokenStart, p - TokenStart);
            //Concatenate etFieldName."Field with spaces"
            if Assigned(ALast)and(ALast.Token in[etVariable, etFieldName])
            then ALast.Value := ALast.Value + AToken
            else ALastArgument.Add(AToken, etLitString);
            Inc(p);
            Break;
          end;
          if P^ = #0
          then raise TRtfException.Create(rsUnterminatedStringConstant);
          Inc(p);
        end;
      end;
      '-': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add(AToken, etSUB);
      end;
      '0'..'9': begin //Ik ga ervan uit dat alles in het amerikaans genoteerd word
        Inc(p);
        ALast := nil;
        AFloatResult := false;
        while P^ in['0'..'9']do Inc(p);
        if P^ = '.' then begin //Floating point
          Inc(p);
          AFloatResult := true;
          while P^ in['0'..'9']do Inc(p);
        end;
        if P^ in['e', 'E'] then begin //1.700000E+308
          AFloatResult := true;
          Inc(p);
          if P^ in['+', '-']
          then Inc(p);
          while P^ in['0'..'9']do Inc(p);
        end;
        SetString(AToken, TokenStart, p - TokenStart);
        if AFloatResult
        then AValue := StrToFloat(AToken)
        else AValue := StrToInt(AToken);
        if AFloatResult
        then ALastArgument.Add(AValue, etLitFloat)
        else ALastArgument.Add(AValue, etLitInt);
      end;
      '(': begin
        Inc(p);
        ALast := nil;
        //Add them to the last function if possible..
        if(ALastArgument.Count > 0)and(ALastArgument[ALastArgument.Count - 1].Token in[etFunction, etProcedure])
        then ALastArgument := ALastArgument[ALastArgument.Count - 1]
        else ALastArgument := ALastArgument.Add('()', etParenthesis);
      end;
      ')': begin
        Inc(p);
        ALast := nil;
        ALastArgument := ALastArgument.Parent;
        if not Assigned(ALastArgument)
        then raise TRtfException.Create(rsToManyClosingParenthesis);
      end;
      '<': begin
        Inc(p);
        ALast := nil;
        case P^ of
          '=': begin
            Inc(p);
            ALastArgument.Add('<=', etLE);
          end;
          '>': begin
            Inc(p);
            ALastArgument.Add('<>', etNE);
          end;
          else ALastArgument.Add('<', etLT);
        end;
      end;
      '=': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add('=', etEq);
      end;
      ':': begin
        Inc(p);
        ALast := nil;
        if P^ = '=' then begin
          Inc(p);
          ALastArgument.Add(':=', etAssign);
        end
        else raise TRtfException.CreateFmt(rsInvalidExpressionCharacter,[P^]);
      end;
      '&': begin
        Inc(p);
        ALast := nil;
        if P^ = '&' then begin
          Inc(p);
          ALastArgument.Add('and', etAnd);
        end
        else raise TRtfException.CreateFmt(rsInvalidExpressionCharacter,[P^]);
      end;
      '|': begin
        Inc(p);
        ALast := nil;
        if P^ = '|' then begin
          Inc(p);
          ALastArgument.Add('or', etOr);
        end
        else raise TRtfException.CreateFmt(rsInvalidExpressionCharacter,[P^]);
      end;
      '!': begin
        Inc(p);
        ALast := nil;
        if P^ = '=' then begin
          Inc(p);
          ALastArgument.Add('!=', etNe);
        end
        else ALastArgument.Add(AToken, etNot);
      end;
      '>': begin
        Inc(p);
        ALast := nil;
        if P^ = '=' then begin
          Inc(p);
          ALastArgument.Add('>=', etGE);
        end
        else ALastArgument.Add('>', etGT);
      end;
      '+': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add('+', etADD);
      end;
      '*': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add('*', etMUL);
      end;
      '/': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add('/', etDIV);
      end;
      ',': begin
        Inc(p);
        ALast := nil;
        ALastArgument.Add(',', etComma);
      end;
      '\': begin //a date/time constant. Since these are
      //in a fixed format we need to parse them ourselves.
        Inc(p);
        ALast := nil;
        if P^ = '{' then begin
          Inc(p);
          FillChar(AInts[0], SizeOf(AInts), 0);
          FillChar(ASeps[0], SizeOf(ASeps), 0);

          AIntIndex := 0;
          while(p^ <> #0)and(p^ in['0'..'9', ' ', ':', '-'])do begin
            //read integer parts
            TokenStart := p;
            while P^ in['0'..'9']do Inc(p);
            SetString(AToken, TokenStart, p - TokenStart);
            if AToken = ''
            then raise TRtfException.Create(rsInvalidDateConstant);
            ASeps[AIntIndex] := p^;
            AInts[AIntIndex] := StrToInt(AToken);
            Inc(AIntIndex);
            if AIntIndex > 6
            then raise TRtfException.Create(rsInvalidDateConstant);
            if(p^ in[' ', '-', ':'])
            then Inc(p);
          end;

          //There shoud be at least two values entered
          if AIntIndex < 2
          then raise TRtfException.Create(rsInvalidDateConstant);

          if not(p^ in['\'])
          then raise TRtfException.Create(rsInvalidDateConstant);
          Inc(p);
          if P^ <> '}'
          then raise TRtfException.Create(rsInvalidDateConstant);
          Inc(p);

          if ASeps[0] = '-' then begin
            //Its a date/time constant.. There should be at least 3 ints
            if AIntIndex < 3
            then raise TRtfException.Create(rsInvalidDateConstant);
            if ASeps[1] <> '-'
            then raise TRtfException.Create(rsInvalidDateSeparator);
            if not(ASeps[2]in[' ', '\'])
            then raise TRtfException.Create(rsInvalidDateSeparator);
            AValue := EncodeDate(AInts[0], AInts[1], AInts[2]);

            //Followed by a optional time constant? There should be at least 2 ints in it
            if AIntIndex > 3 then begin
              if AIntIndex < 5
              then raise TRtfException.Create(rsInvalidTimeConstant);
              if not(ASeps[2]in[' '])
              then raise TRtfException.Create(rsInvalidTimeSeparator);
              if not(ASeps[3]in[':', ' ', '\'])
              then raise TRtfException.Create(rsInvalidTimeSeparator);
              AValue := AValue + EncodeTime(AInts[3], AInts[4], AInts[5], 0);
            end;
          end else if ASeps[0] = ':' then begin
            //Its a time constant.. There should be at least 2 ints
            if AIntIndex < 1
            then raise TRtfException.Create(rsInvalidTimeConstant);
            if not(ASeps[1]in[':', ' ', '\'])
            then raise TRtfException.Create(rsInvalidTimeSeparator);
            AValue := EncodeTime(AInts[0], AInts[1], AInts[2], 0);
          end;
          ALastArgument.Add(AValue, etLitDate)
        end
        else raise TRtfException.CreateFmt(rsInvalidExpressionCharacter,[P^]);
      end;
      else begin
        if p^ <> #0
        then raise TRtfException.CreateFmt(rsInvalidExpressionCharacter,[P^]);
      end;
    end;
    FSourcePtr := p;
  end;
  if ALastArgument <> Self
  then raise TRtfException.Create(rsExpectedClosingParenthesis);
end;

procedure TRtfArgument.EvaluateUnaryBinary(APrevItem, AArgument, ANextItem: TRtfArgument);
begin
  case APrevItem.Token of
    etLitString: begin
      case ANextItem.Token of
        etLitString: begin
          if AArgument.Token <> etAdd
          then raise TRtfException.Create('Unable to combine strings with other types');
          APrevItem.Value := APrevItem.Value + ANextItem.Value;
          Remove(AArgument);
          Remove(ANextItem);
        end;
        else raise TRtfException.Create('Unable to combine strings with other types');
      end;
    end;
    etLitInt: begin
      case ANextItem.Token of
        etLitInt, etLitDate, etLitFloat: begin
          case AArgument.Token of
            etAdd: APrevItem.Value := APrevItem.Value + ANextItem.Value;
            etSub: APrevItem.Value := APrevItem.Value - ANextItem.Value;
            etMul: APrevItem.Value := APrevItem.Value * ANextItem.Value;
            etDiv: APrevItem.Value := APrevItem.Value / ANextItem.Value;
          end;
          if ANextItem.Token = etLitDate
          then APrevItem.Token := etLitDate
          else if ANextItem.Token = etLitFloat
          then APrevItem.Token := etLitFloat
          else if AArgument.Token = etDiv
          then APrevItem.Token := etLitFloat
          else APrevItem.Token := etLitInt;
          Remove(AArgument);
          Remove(ANextItem);
        end;
        else raise TRtfException.Create('Invalid formula');
      end;
    end;
    etLitFloat: begin
      case ANextItem.Token of
        etLitInt, etLitFloat, etLitDate: begin
          case AArgument.Token of
            etAdd: APrevItem.Value := APrevItem.Value + ANextItem.Value;
            etSub: APrevItem.Value := APrevItem.Value - ANextItem.Value;
            etMul: APrevItem.Value := APrevItem.Value * ANextItem.Value;
            etDiv: APrevItem.Value := APrevItem.Value / ANextItem.Value;
          end;
          if ANextItem.Token = etLitDate
          then APrevItem.Token := etLitDate
          else APrevItem.Token := etLitFloat;
          Remove(AArgument);
          Remove(ANextItem);
        end;
        else raise TRtfException.Create('Invalid formula');
      end;
    end;
    etLitDate: begin
      case ANextItem.Token of
        etLitInt, etLitFloat, etLitDate: begin
          case AArgument.Token of
            etAdd: APrevItem.Value := APrevItem.Value + ANextItem.Value;
            etSub: APrevItem.Value := APrevItem.Value - ANextItem.Value;
            etMul: APrevItem.Value := APrevItem.Value * ANextItem.Value;
            etDiv: APrevItem.Value := APrevItem.Value / ANextItem.Value;
          end;
          APrevItem.Token := etLitDate;
          Remove(AArgument);
          Remove(ANextItem);
        end;
        else raise TRtfException.Create('Invalid formula');
      end;
    end;
    etComma: begin
    //Fix for constant int's and float's
      case ANextItem.Token of
        etLitInt, etLitFloat, etLitDate: begin
          case AArgument.Token of
            etAdd:; //nothing just a (..., +Value)
            etSub: ANextItem.Value := ANextItem.Value * - 1;
            else raise TRtfException.Create('Invalid formula');
          end;
          Remove(AArgument);
        end;
        else raise TRtfException.Create('Invalid formula');
      end;
    end;
    etAssign: begin
    //Fix for constant int's and float's
      case ANextItem.Token of
        etLitInt, etLitFloat, etLitDate: begin
          case AArgument.Token of
            etAdd:; //nothing just a @Variable := +Value
            etSub: ANextItem.Value := ANextItem.Value * - 1;
            else raise TRtfException.Create('Invalid formula');
          end;
          Remove(AArgument);
        end;
        else raise TRtfException.Create('Invalid formula');
      end;
    end;
    else raise TRtfException.Create('Invalid formula'); //Otherwise it wont advance
  end;
  if Assigned(Parser.OnEvalutate)
  then Parser.OnEvalutate(Self);
end;

procedure TRtfArgument.EvaluateComparison(APrevItem, AArgument, ANextItem: TRtfArgument);
begin
  if(APrevItem.Token = etLitString)and(ANextItem.Token <> etLitString)
  then raise TRtfException.Create('Invalid comparison');
  if(ANextItem.Token = etLitString)and(APrevItem.Token <> etLitString)
  then raise TRtfException.Create('Invalid comparison');

  case AArgument.Token of
    etEQ: APrevItem.Value := APrevItem.Value = ANextItem.Value;
    etNE: APrevItem.Value := APrevItem.Value <> ANextItem.Value;
    etGE: APrevItem.Value := APrevItem.Value >= ANextItem.Value;
    etLE: APrevItem.Value := APrevItem.Value <= ANextItem.Value;
    etGT: APrevItem.Value := APrevItem.Value > ANextItem.Value;
    etLT: APrevItem.Value := APrevItem.Value < ANextItem.Value;
    etOr: APrevItem.Value := APrevItem.Value or ANextItem.Value;
    etAnd: APrevItem.Value := APrevItem.Value and ANextItem.Value;
    else raise TRtfException.Create('Invalid comparison');
  end;
  if APrevItem.Value
  then APrevItem.Token := etLitTrue
  else APrevItem.Token := etLitFalse;

  Remove(AArgument);
  Remove(ANextItem);
  if Assigned(Parser.OnEvalutate)
  then Parser.OnEvalutate(Self);
end;

procedure TRtfArgument.EvaluateAssign(APrevItem, AArgument, ANextItem: TRtfArgument);
var AVariable: TRtfVariable;
begin
  if APrevItem.Token <> etVariable
  then raise TRtfException.Create('Invalid assignment');

  AVariable := Parser.Variables.Find(APrevItem.Value);
  if Assigned(AVariable) then begin
    AVariable.Value := ANextItem.Value;
    AVariable.Token := ANextItem.Token;
  end
  else AVariable := Parser.Variables.Add(APrevItem.Value, ANextItem.Value, ANextItem.Token);

  APrevItem.Value := AVariable.Value;
  APrevItem.Token := AVariable.Token;

  Remove(AArgument);
  Remove(ANextItem);
  if Assigned(Parser.OnEvalutate)
  then Parser.OnEvalutate(Self);
end;

procedure TRtfArgument.GetPictureData(ABuffer: pointer; ALength: cardinal; var Result: string);
var ASrc: Pbyte;
  ADst: pchar;
  AIndex: cardinal;
  i: integer;
  s: string;
begin
  if poBinary in Parser.PictureOptions then begin
    //Save graphic binary
    Result := Format('%s\bin%d ',[Result, ALength]);
    AIndex := Length(Result);
    SetLength(Result, AIndex + ALength);
    ADst := @Result[AIndex + 1];
    System.Move(ABuffer^, ADst^, ALength);
  end else begin
    //Save graphics as hex
    ASrc := ABuffer;
    Result := Result + ' ';
    AIndex := Length(Result);
    SetLength(Result, AIndex + 2 *(ALength +(ALength div 128)));
    ADst := @Result[AIndex + 1];
    for i := 0 to ALength - 1 do begin
      s := IntToHex(ASrc^, 2);
      ADst^ := s[1];
      Inc(ADst);
      ADst^ := s[2];
      Inc(ADst);
      if(i > 0)and(i and 127 = 0) then begin
        ADst^ := #13;
        Inc(ADst);
        ADst^ := #10;
        Inc(ADst);
      end;
      Inc(ASrc);
    end;
  end;
  Result := Result + #13#10 + '}';
end;

function TRtfArgument.GetPicture(APicture: TPicture): string;
//Convert a picture to a string suitable for in the Rtf
(*
var
  xw, yh: word;
  Rect: TRect;
  ARefDC: HDC;
  ABuffer: pointer;
  ALength: cardinal;
  AMetafile: TMetafile;
  ABorderWidth: integer;
  APictureAttr: TRtfPictureAttr;
  ppi, AColorIndex, xtw, ytw: integer;
*)
begin
  Result := '';
  (*
  ppi := Screen.PixelsPerInch;

  AMetafile := TMetaFile.Create;
  try
    AMetafile.Enhanced := true;

    if poMetafile in Parser.PictureOptions then begin
      AMetafile.Width := Round(APicture.Graphic.Width * ppi / 96);
      AMetafile.Height := Round(APicture.Graphic.Height * ppi / 96);
    end else begin
      if(APicture.graphic is TMetafile)and not APicture.Metafile.Enhanced then begin
        AMetafile.Height := APicture.graphic.Height;
        AMetafile.Width := APicture.graphic.Width;
      end else begin
        AMetafile.Height := Round(APicture.graphic.Height * ppi / 96);
        AMetafile.Width := Round(APicture.graphic.Width * ppi / 96);
      end;
    end;

    Rect.Top := 0;
    Rect.Left := 0;
    Rect.Right := AMetafile.Width - 1;
    Rect.Bottom := AMetafile.Height - 1;

    with TMetaFileCanvas.Create(AMetafile, 0)do try
      if ppi = 96
      then Draw(0, 0, APicture.Graphic)
      else StretchDraw(Rect, APicture.Graphic);
    finally
      Free;
    end;

    if(APicture.Graphic is TMetafile)and not APicture.Metafile.Enhanced then begin
      xw := Round(APicture.Width * 96 / ppi);
      yh := Round(APicture.Height * 96 / ppi);
    end else begin
      xw := APicture.Width;
      yh := APicture.Height;
    end;

    APictureAttr := TRtfPictureAttr.Create(xw, yh);
    try
      AMetafile.MMWidth := Round(APictureAttr.Widthmm * 100);
      AMetafile.MMHeight := Round(APictureAttr.Heigthmm * 100);

      if poMetafile in Parser.PictureOptions then begin
        xtw := Round(APictureAttr.Width * 26.4596930676);
        ytw := Round(APictureAttr.Heigth * 26.4596930676);
      end else begin
        xtw := Round(5669 * APictureAttr.Widthmm / 100);
        ytw := Round(5669 * APictureAttr.Heigthmm / 100);
      end;

      if Assigned(Parser.OnPictureAttr)
      then Parser.OnPictureAttr(APictureAttr);

      Result := Format('{\pict\picscalex%d\picscaley%d\piccropl0' +
        '\piccropr0\piccropt0\piccropb0\picw%d\pich%d',
        [APictureAttr.ScaleX, APictureAttr.ScaleY, xtw, ytw]);
      if poMetafile in Parser.PictureOptions
      then Result := Result + '\wmetafile8'
      else Result := Result + '\emfblip';

      if(APictureAttr.BorderType <> brNone)and(APictureAttr.BorderWidth > 0) then begin
        case APictureAttr.BorderType of
          brSingle: Result := Result + '\brdrs';
          brDouble: Result := Result + '\brdrdb';
          brThick: Result := Result + '\brdrth';
          brShadow: Result := Result + '\brdrsh';
          brDot: Result := Result + '\brdrdot';
          brHair: Result := Result + '\brdrhair';
        end;

        ABorderWidth := APictureAttr.BorderWidth;
        if ABorderWidth > 75
        then ABorderWidth := 75;

        AColorIndex := Parser.ColorList.UseColor(APictureAttr.BorderColor);
        Result := Format('%s\brdrw%d\brdrcf%d',[Result, ABorderWidth, AColorIndex]);
      end;
    finally
      APictureAttr.Free;
    end;


    if poMetafile in Parser.PictureOptions then begin
      ARefDC := GetDC(0);
      try
        ALength := GetWinMetaFileBits(AMetafile.Handle, 0, nil, MM_ANISOTROPIC, ARefDC);
        GetMem(ABuffer, ALength);
        try
          GetWinMetaFileBits(AMetafile.Handle, ALength, ABuffer, MM_ANISOTROPIC, ARefDC);
          GetPictureData(ABuffer, ALength, Result);
        finally
          FreeMem(ABuffer);
        end;
      finally
        ReleaseDC(0, ARefDc);
      end;
    end else begin
      ALength := GetEnhMetaFileBits(AMetafile.Handle, 0, nil);
      GetMem(ABuffer, ALength);
      try
        GetEnhMetaFileBits(AMetafile.Handle, ALength, ABuffer);
        GetPictureData(ABuffer, ALength, Result);
      finally
        FreeMem(ABuffer);
      end;
    end;
  finally
    AMetafile.Free;
  end;
  *)
end;

procedure TRtfArgument.GetGraphicsValue(ADataset: TRtfDataset; AFieldName: string);
(*
var
  APicture: TPicture;
  ABlob: TBlobField;
  APhoto: TJPEGImage;
  AStream: TStringStream;
  s: string[20];
  AField: TField;
*)
begin
(*
  Value := varEmpty;
  Token := etNothing;
  if ADataset.Dataset is TDataset then begin
    AField :=(ADataset.Dataset as TDataset).FieldByName(AFieldName);

    APicture := TPicture.Create;
    try
      ABlob := AField as TBlobField;
      s := Copy(ABlob.Value, 1, 20);
      if(Pos('GIF8', s) > 0)or(Pos('JFIF', s) > 0) then begin
        APhoto := TJPEGImage.Create;
        try
          AStream := TStringStream.Create(ABlob.AsString);
          APhoto.LoadFromStream(AStream);
          APicture.Assign(APhoto);
        finally
          FreeAndNil(APhoto);
          FreeAndNil(AStream);
        end;
      end
      else APicture.Assign(ABlob);

      if Assigned(APicture.Graphic) then begin
        Value := GetPicture(APicture);
        Token := etLitString;
      end;

    finally
      APicture.Free;
    end;
  end
  else
    raise TRtfException.Create('Graphic fields worden alleen ondersteund via de tdataset!');
*)
end;

procedure TRtfArgument.ResolveFieldValue(ADataset: TRtfDataset; AFieldName: string);
//Get field data from a dataset object
var
  AObject: TObject;
  APropInfo: PPropInfo;
  ATypedata: PTypeData;
  ATable: TDataset;
  AField: TField;
begin
  //Can't resolve that
  if AFieldName = '' then
    raise TRtfException.Create('invalid fieldname');

  if ADataset.Dataset is TDataset then
  begin
    ATable := ADataset.Dataset as TDataset;
    AField := ATable.FieldByName(AFieldName);
    case AField.DataType of
      ftMemo, ftFmtMemo, ftFixedChar, ftWideString, ftString: begin
        Token := etLitString;
        Value := AField.AsString;
      end;
      ftLargeint, ftAutoInc, ftSmallint, ftInteger, ftWord: begin
        Token := etLitInt;
        Value := AField.AsInteger;
      end;
      ftBoolean: begin
        Value := AField.AsBoolean;
        if Value then
          Token := etLitTrue
        else
          Token := etLitFalse;
      end;
      ftFloat, ftCurrency, ftBCD: begin
        Token := etLitFloat;
        Value := AField.AsFloat;
      end;
      ftDate, ftTime, ftDateTime, ftTimeStamp: begin
        Token := etLitDate;
        Value := AField.AsDateTime;
      end;
      ftGraphic: begin
        GetGraphicsValue(ADataset, AFieldName);
      end;
      else
        raise TRtfException.CreateFmt('Unable to convert field "%s" value',[AFieldName]);
    end;
  end
  else
  begin
    AObject := ADataset.Dataset;
    if AObject is TtiObjectList then
    begin
      //Get the right record from the array
      if ADataset.TableIndex <(AObject as TtiObjectList).Count then
        AObject :=(AObject as TtiObjectList)[ADataset.TableIndex]
      else
      begin //Trying beyond eof (or empty dataset) big problem; nah?
        Token := etNothing;
        Value := varEmpty;
        exit;
      end;
    end;
    APropInfo := GetPropInfo(AObject, AFieldName);
    if not Assigned(APropInfo) then
      raise TRtfException.CreateFmt('Field "%s" does not exist',[AFieldName]);
    if not Assigned(APropInfo^.GetProc) then
      raise TRtfException.CreateFmt('Cannot access field "%s"',[AFieldName]);
    {$IFDEF FPC}
    ATypeData := GetTypeData(APropInfo^.PropType);
    {$ELSE}
    ATypeData := GetTypeData(APropInfo^.PropType^);
    {$ENDIF}

    case APropInfo^.PropType^.Kind of
      tkChar, tkString, tkLString, tkWString{$IFDEF FPC},tkAString{$ENDIF}: begin
        Token := etLitString;
        Value := GetStrProp(AObject, APropInfo);
      end;
      tkInt64: begin
        Token := etLitInt;
        Value := GetInt64Prop(AObject, APropInfo);
      end;
      tkSet, tkInteger: begin
        Token := etLitInt;
        Value := GetOrdProp(AObject, APropInfo);
      end;
      tkEnumeration: begin
        {$IFDEF FPC}
        if ATypeData^.BaseType = TypeInfo(boolean) then
        {$ELSE}
        if ATypeData^.BaseType^ = TypeInfo(boolean) then
        {$ENDIF}
        begin
          Value := GetOrdProp(AObject, APropInfo) = 1;
          if Value then
            Token := etLitTrue
          else
            Token := etLitFalse;
        end
        else
        begin
          Token := etLitInt;
          Value := GetOrdProp(AObject, APropInfo);
        end;
      end;
      tkFloat: begin
        if SameText(APropInfo^.PropType^.Name, 'TDate')
            or SameText(APropInfo^.PropType^.Name, 'TTime')
            or SameText(APropInfo^.PropType^.Name, 'TDateTime') then
          Token := etLitDate
        else
          Token := etLitFloat;
        Value := GetFloatProp(AObject, APropInfo);
      end;
      else
        raise TRtfException.CreateFmt('Unable to convert field "%s" value',[AFieldName]);
    end;  { case }
  end;  { if/else }
end;

procedure TRtfArgument.ResolveVariable;
var AVariable: TRtfVariable;
  AText, AFieldName: string;
  ADataset: TRtfDataset;
  AIndex: integer;
begin
  AText := Value;
  AIndex := Pos('.', AText);
  if AIndex > 0 then begin
    //Its a dataset reference @Table.Fieldname
    AFieldName := Copy(AText, AIndex + 1, Maxint);
    AText := Copy(AText, 1, AIndex - 1);

    AVariable := Parser.Variables.Find(AText);
    if not Assigned(AVariable)
    then raise TRtfException.Create('variable does not exist');
    Token := AVariable.Token;
    Value := AVariable.Value;
    if Token <> etDataset
    then raise TRtfException.Create('variable is not a dataset');

    ADataset := TRtfDataset(ptrint(Value));
    ADataset := ADataset.ResolveNestedFields(ADataset, AFieldName, AFieldName);
    if AFieldName = '' then begin
      //Its a (nested) dataset
      Token := etDataset;
      Value := PtrInt(ADataset);
    end
    else ResolveFieldValue(ADataset, AFieldName);
  end else begin
    AVariable := Parser.Variables.Find(AText);
    if not Assigned(AVariable)
    then raise TRtfException.Create('variable does not exist');
    Token := AVariable.Token;
    Value := AVariable.Value;
  end;
end;

procedure TRtfArgument.ResolveFieldName;
//Resolve dataset names or fieldnames (seperated with ".")
var ADataset: TRtfDataset;
  AFieldName: string;
begin
  //Otherwise it should be a table reference or fieldname
  ADataset := Parser.Datasets.Find(Value, AFieldName);
  if not Assigned(ADataset) //There should be at least a table reference.
  then raise TRtfException.CreateFmt('Dataset "%s" not found',[Value]);
  if AFieldName <> ''
  then ResolveFieldValue(ADataset, AFieldName)
  else begin
    //Its a dataset or objectlist reference
    Token := etDataset;
    Value := PtrInt(ADataset);
  end;
end;

procedure TRtfArgument.Walk(ATokenset: TRtfTokenSet; AExecproc: TRtfArgumentEvent);
//Not really neat (what can you expect in 1 day)
var i: integer;
  AText: string;
  AResolve: boolean;
  AParent, APrevItem, AArgument, ANextItem: TRtfArgument;
begin
  if Count > 0 then begin
    i := 0;
    while i < Count do begin
      AArgument := Items[i];

      if AArgument.Token = etVariable then begin
        if(i >= Count - 1)or(Items[i + 1].Token <> etAssign)
        then AArgument.ResolveVariable;
      end else if AArgument.Token = etFieldName then begin
        //An exception is the DbPicture(Table.Field). It shoud not evaluate
        //since the DbPicture function should be responsible for that.
        AResolve := true;
        AParent := AArgument.Parent;
        if Assigned(AParent) then begin
          AText := AParent.Value;
          if SameText(AText, 'DbPicture')
          then AResolve := false;
        end;
        if AResolve
        then AArgument.ResolveFieldName;
      end;

      if AArgument.Token = etNot then begin
        if i < Count - 1
        then ANextItem := Items[i + 1]
        else raise TRtfException.Create('invalid formula');
        if ANextItem.Token = etLitFalse
        then ANextItem.Value := true
        else if ANextItem.Token = etLitTrue
        then ANextItem.Value := false
        else raise TRtfException.Create('invalid formula');
        Remove(AArgument);
      end else if AArgument.Token in ATokenSet then begin
        if i > 0
        then APrevItem := Items[i - 1]
        else raise TRtfException.Create('invalid formula');
        if i < Count - 1
        then ANextItem := Items[i + 1]
        else raise TRtfException.Create('invalid formula');
        AExecproc(APrevItem, AArgument, ANextItem);
      end
      else Inc(i);
    end;

    if(Count = 1)and(Token = etParenthesis) then begin
      //Advance the answer from between parenthesis to parent.
      AArgument := Items[0];
      Value := AArgument.Value;
      Token := AArgument.Token;
      Remove(AArgument);
      if Assigned(Parser.OnEvalutate)
      then Parser.OnEvalutate(Self);
    end;
  end;
end;

procedure TRtfArgument.EvaluateExpression;
//Not really neat (what can you expect in 1 day)
//Evaluate the entered expression via ParseExpression()
var AFunction: TRtfFunction;
  AArgument: TRtfArgument;
  i: integer;
begin
  if Count > 0 then begin
    //First the binary operators
    Walk([etMul, etDiv], {$IFDEF FPC}@{$ENDIF}EvaluateUnaryBinary);
    //Secondly the unary operators
    Walk([etAdd, etSub], {$IFDEF FPC}@{$ENDIF}EvaluateUnaryBinary);
    //And finally the simple comparisons
    Walk([etEQ, etNE, etGE, etLE, etGT, etLT], {$IFDEF FPC}@{$ENDIF}EvaluateComparison);
    //And finally the more "complicated" comparisons
    Walk([etAnd, etOr], {$IFDEF FPC}@{$ENDIF}EvaluateComparison);
  end;


  if Token in[etFunction, etProcedure] then begin
    AFunction := Parser.Functions.Find(Value);
    if not Assigned(AFunction)
    then raise TRtfException.Create('Cannot resolve function');

    if not Assigned(AFunction.OnExecute)
    then raise TRtfException.Create('Cannot resolve function');

    //Remove now redundant comma's
    for i := Count - 1 downto 0 do begin
      AArgument := Items[i];
      if AArgument.Token = etComma
      then Remove(AArgument)
      else if VarIsEmpty(AArgument.Value)
      then raise TRtfException.Create('Function needs valid parameters');
    end;

    if Count < AFunction.Min
    then raise TRtfException.Create('expected more parameters');
    if Count > AFunction.Max
    then raise TRtfException.Create('to many parameters');

    Value := varEmpty;
    Token := etNothing;
    if Assigned(Parser.OnEvalutate)
    then Parser.OnEvalutate(Self);
    AFunction.OnExecute(Self);
    Clear; //Clear parameters
    if Assigned(Parser.OnEvalutate)
    then Parser.OnEvalutate(Self);
  end;

  //And not to forget  any optional assignments
  if Count > 0
  then Walk([etAssign], {$IFDEF FPC}@{$ENDIF}EvaluateAssign);
end;

procedure TRtfArgument.Evaluate;
//Not really neat (what can you expect in 1 day)
//Evaluate the expression (not very efficient, but what the hack)
var i: integer;
  AText: string;
  AArgument: TRtfArgument;
begin
  for i := 0 to Count - 1 do begin
    AArgument := Items[i];
    AArgument.Evaluate;
  end;
  EvaluateExpression;

  if(Parent = nil)and(Count > 1)
  then raise TRtfException.Create('invalid formula');

  if Count = 1 then begin
    //Advance the answer from between parenthesis to parent.
    AArgument := Items[0];
    Value := AArgument.Value;
    Token := AArgument.Token;
    Param := AArgument.Param;
    Clear;
    if Assigned(Parser.OnEvalutate)
    then Parser.OnEvalutate(Self);
  end;

  if Token = etLitString then begin
    //Fix: DbExpres appends a #0 character to memo fields
    AText := Value;
    if(Length(AText) > 0)and(AText[Length(AText)] = #0)
    then Value := Copy(AText, 1, Length(AText) - 1);
  end;
end;


{ TRtfColor }

function TRtfColor.GetAsString: string;
begin
  Result := Format('\red%d\green%d\blue%d;',[Red, Green, Blue]);
end;

{ TRtfColorList }

function TRtfColorList.GetItem(Index: integer): TRtfColor;
begin
  Result := TRtfColor(inherited Items[Index]);
end;

procedure TRtfColorList.Clear;
begin
  inherited Clear;
  { TODO -oGraeme : Not sure why this was here, so I removed it. 2009-11-10 }
//  Add(0, 0, 0); //Dummy color..
end;

function TRtfColorList.Add(ARed, AGreen, ABlue: integer): integer;
var AColor: TRtfColor;
begin
  AColor := TRtfColor.Create;
  AColor.Red := ARed;
  AColor.Green := AGreen;
  AColor.Blue := ABlue;
  Result := inherited Add(AColor);
end;

function TRtfColorList.Find(ARed, AGreen, ABlue: integer): integer;
var
  i: integer;
  AColor: TRtfColor;
begin
  //0 is a dummy color
  for i := 1 to Count - 1 do
  begin
    AColor := Items[i];
    if(AColor.Red = ARed)and(AColor.Green = AGreen)and(AColor.Blue = ABlue) then
    begin
      Result := i;
      exit;
    end;
  end;
  Result := - 1;
end;

function TRtfColorList.GetAsString: string;
var
  i: integer;
  AColor: TRtfColor;
begin
  Result := '';
  //0 is a dummy color
  for i := 1 to Count - 1 do
  begin
    AColor := Items[i];
    Result := Result + AColor.AsString;
  end;
end;

function TRtfColorList.UseColor(ARed, AGreen, ABlue: integer): integer;
begin
  Result := Find(ARed, AGreen, ABlue);
  if Result < 0
  then Result := Add(ARed, AGreen, ABlue);
end;

function TRtfColorList.UseColor(AColor: TColor): integer;
var ARed, AGreen, ABlue: integer;
begin
  ARed := AColor and 255;
  AColor := AColor shr 8;
  AGreen := AColor and 255;
  AColor := AColor shr 8;
  ABlue := AColor and 255;
  Result := UseColor(ARed, AGreen, ABlue);
end;


{ TtiRtfParser }

constructor TtiRtfParser.Create;
begin
  inherited Create;
  FBoolTrue := 'Ja';
  FBoolFalse := 'Nee';
  FErrorForeColor := clRed;
  FErrorBackColor := clYellow;
  FPictureOptions :=[poMetafile, poBinary];
  FHlpItems := TRtfItem.Create;
  TmpItems := TObjectlist.Create;
  FDatasets := TRtfDataset.Create;
  FRtfItems := TRtfItemList.Create;
  FRawItems := TRtfItemList.Create;
  FColorList := TRtfColorList.Create;
  FVariables := TRtfVariableList.Create;
  FFunctions := TRtfFunctionList.Create;
  AddFunctions;
end;

destructor TtiRtfParser.Destroy;
begin
  FDatasets.Free;
  FRtfItems.Free;
  TmpItems.Free;
  FHlpItems.Free;
  FVariables.Free;
  FFunctions.Free;
  FRawItems.Free;
  FColorList.Free;
  inherited;
end;

procedure TtiRtfParser.Clear;
begin
  TmpItems.Clear;
  RawItems.Clear;
  RtfItems.Clear;
  HlpItems.Clear;
  ColorList.Clear;
end;

procedure TtiRtfParser.SaveToFile(AFileName: string);
var AStream: TMemoryStream;
begin
  AStream := TMemoryStream.Create;
  try
    RtfItems.SaveToStream(AStream, ColorList.AsString);
    AStream.SaveToFile(AFileName);
  finally
    AStream.Free;
  end;
end;

function TtiRtfParser.SaveToString: string;
var AStream: TMemoryStream;
begin
  Result := '';
  AStream := TMemoryStream.Create;
  try
    RtfItems.SaveToStream(AStream, ColorList.AsString);
    SetLength(Result, AStream.Size);
    if AStream.Size > 0 //Humble admitted its a bit dirty
    then Move(AStream.Memory^, Result[1], AStream.Size);
  finally
    AStream.Free;
  end;
end;

procedure TtiRtfParser.SaveToStream(AStream: TMemoryStream);
begin
  RtfItems.SaveToStream(AStream, ColorList.AsString);
end;

function TtiRtfParser.AddVariable(AName: string; AValue: variant; AToken: TRtfToken): TRtfVariable;
begin
  Result := Variables.Add(AName, AValue, AToken);
end;

function TtiRtfParser.AddDataset(ATable: TObject; AName: string; AFreeDataset: boolean = false): TRtfDataset;
begin
  Result := Datasets.Add(ATable, AName, AFreeDataset);
end;

function TtiRtfParser.AddFunction(AName: string; ATokenType: TRtfToken; AMin, AMax: smallint; AOnexecute: TRtfFunctionExecute): TRtfFunction;
begin
  Result := Functions.Add(ATokenType, AName, AMin, AMax, AOnexecute);
end;

function TtiRtfParser.AddToRtfItems(AItem: TRtfItem): TRtfItem;
begin
  Result := TRtfItem.Create;
  Result.Assign(AItem);
  RtfItems.Add(Result);
end;

procedure TtiRtfParser.LoadFromFile(AFilename: string);
//Tokenize the raw rtf and put it into rawitems
var
  AStream: TMemoryStream;
begin
  Clear;
  AStream := TMemoryStream.Create;
  try
    AStream.LoadFromFile(AFileName);
    LoadFromBuffer(AStream.Memory, AStream.Size);
  finally
    FreeAndNil(AStream);
  end;
end;

procedure TtiRtfParser.LoadFromStream(AStream: TMemoryStream);
//Tokenize the raw rtf and put it into rawitems
begin
  LoadFromBuffer(AStream.Memory, AStream.Size);
end;

procedure TtiRtfParser.LoadFromString(AString: string);
//Tokenize the raw rtf and put it into rawitems
begin
  LoadFromBuffer(pchar(AString), Length(AString));
end;

procedure TtiRtfParser.LoadFromBuffer(ABuffer: pchar; ASize: integer);
//Tokenize the raw rtf and put it into rawitems
var AColorTable: TRtfItem;
  AColors, AToken: string;
  ANumber, ARed, AGreen, ABlue: integer;
  p: pchar;
begin
  Clear;
  with TRawRtfParser.Create do try
    Execute(FRawItems, ABuffer, ASize);
    AColorTable := ColorTable;
  finally
    Free;
  end;

  if not Assigned(AColorTable)
  then raise TRtfException.Create('no colortbl found');

  //Parse the color table (tiny parser)
  ARed := 0;
  ABlue := 0;
  AGreen := 0;
  AColors := Copy(AColorTable.RtfTextBuf, 11, Maxint);
  p := pchar(AColors);
  while p <> #0 do begin
    case p^ of
      '\': begin
        inc(p);
        AToken := '';
        ANumber := 0;
        while(p^ in['A'..'Z', 'a'..'z'])do begin
          AToken := AToken + p^;
          inc(p);
        end;
        while(p^ in['0'..'9'])do begin
          ANumber :=(ANumber * 10) +(ord(p^) - ord('0'));
          inc(p);
        end;
        ANumber := ANumber and 255;
        if SameText(AToken, 'red')
        then ARed := ANumber
        else if SameText(AToken, 'blue')
        then ABlue := ANumber
        else if SameText(AToken, 'green')
        then AGreen := ANumber;
      end;
      ';': begin
        inc(p);
        ColorList.UseColor(ARed, AGreen, ABlue);
        ARed := 0;
        ABlue := 0;
        AGreen := 0;
      end;
      #13, #10: inc(p);
      '}': break;
      else raise TRtfException.Create('Invalid character in colortbl');
    end;
  end;

  (*
  {\colortbl;\red0\green0\blue;\red255\green0\blue;\red255\green255\blue;\red0\green255\blue;\red255\green0\blue;\red0\green0\blue;\red0\green255\blue;\red255\green255\blue;\red128\green0\blue;\red128\green128\blue;\red0\green128\blue;\red128\green0\blue;\red0\green0\blue;\red0\green128\blue;\red128\green128\blue;\red192\green192\blue;}
  *)
end;

procedure TtiRtfParser.Execute;
//Rtf has been already been loaded
begin
  PreParse; //Create a tree for easy parsing of if-then-else and scan-endscan etc.
  Parse(HlpItems); //Parse the tree items in the structure..
end;

procedure TtiRtfParser.PreParse;
//Preparse the items from Items to Structure
//This will make a tree from (sub)expressions and code.
//Specially for the if/else/endif and scan/scanend
var AIndex, AForeColor, ABackColor: integer;
  AItem, AStart, ABranche: TRtfItem;
  AArguments: TRtfArgument;
  ARemoveParagraph: boolean;
  AFirstArgument: string;
  AFirstToken: TRtfToken;
  AText: string;
begin
  AItem := RawItems.Head;
  AArguments := TRtfArgument.Create(Self);
  try
    //Round 1: create expression nodes
    while Assigned(AItem)do begin
      if AItem.RtfClass = RtfParsebegin then begin

        //Items starts with a RtfParseBegin
        AText := AItem.RtfTextBuf; //Initial expression
        AStart := HlpItems[HlpItems.Add(AItem)];
        AStart.RtfClass := RtfExpression;
        AStart.RtfMajor := RtfNormalExpression;
        AStart.RtfTextBuf := '';
        AItem := AItem.Next;
        while Assigned(AItem)do begin
          case AItem.RtfClass of
            RtfParseEnd: begin //End of expression
              AText := AText + AItem.RtfTextBuf;
              AItem := AItem.Next; //Skip's ParseEnd
              break;
            end;
            RtfParseBegin: begin //WTF: Start of expression, this should not happen. Inform user
              raise TRtfException.Create('Error in preparse? at ' + AText);
            end;
            RtfText: AText := AText + AItem.RtfTextBuf;
            RtfControl: begin
              case AItem.RtfMajor of
                RtfSpecialChar: begin //Add some special characters
                  case AItem.RtfMinor of
                    RtfPar, RtfParDef:; //Ignore these
                    RtflQuote, RtfrQuote: AText := AText + Chr(39);
                    RtflDblQuote, RtfrDblQuote: AText := AText + '"';
                    else AText := AText + AItem.RtfTextBuf; //Hope this is Ok?
                  end;
                end;
                else HlpItems.Add(AItem);
              end;
            end;
            else HlpItems.Add(AItem);
          end;
          AItem := AItem.Next;
        end;

        AStart.RtfTextBuf := StringReplace(AText, #13#10, '',[rfReplaceAll]);
        AArguments.Clear;
        ARemoveParagraph := true;
        try
          AArguments.ParseExpression(AText);
        except
          on e: Exception do begin
            //Ignore at this moment, it will be triggered again in the Parse()
          end;
        end;
        if AArguments.Count > 0 then begin
          AFirstToken := AArguments[0].Token;
          AFirstArgument := AArguments[0].Value;
          if SameText(AFirstArgument, 'if')
          then AStart.RtfMajor := RtfIfExpression
          else if SameText(AFirstArgument, 'else')
          then AStart.RtfMajor := RtfElseExpression
          else if SameText(AFirstArgument, 'endif')
          then AStart.RtfMajor := RtfEndifExpression
          else if SameText(AFirstArgument, 'scan')
          then AStart.RtfMajor := RtfScan
          else if SameText(AFirstArgument, 'endscan')
          then AStart.RtfMajor := RtfScanEnd
          else if SameText(AFirstArgument, 'scanentry')
          then AStart.RtfMajor := RtfScanEntry
          else if SameText(AFirstArgument, 'scanfooter')
          then AStart.RtfMajor := RtfScanFooter;
          ARemoveParagraph := AFirstToken in[etVariable, etProcedure, etNothing];
          if(AFirstToken = etVariable)and(AArguments.Count = 1)
          then ARemoveParagraph := false; //One exception: variable reference
        end;

        if ARemoveParagraph
        then AItem := SkipParagraph(AItem);
      end else begin
        HlpItems.Add(AItem);
        AItem := AItem.Next;
      end;
    end;

  finally
    AArguments.Free;
  end;

  //Round 2: create if then else expression sub-nodes
  AIndex := 0;
  ABranche := nil;
  while AIndex < HlpItems.Count do begin
    AItem := HlpItems[AIndex];
    try

      if AItem.CheckItem(RtfExpression, RtfIfExpression) then begin
        if Assigned(ABranche) then begin
          HlpItems.Extract(AItem);
          ABranche.Add(AItem);
        end
        else Inc(AIndex);

        ABranche := TRtfItem.Create;
        ABranche.RtfClass := RtfBranche;
        ABranche.RtfMajor := RtfThenExpression;
        TmpItems.Add(ABranche); //Otherwise memory leak
        AItem.Add(ABranche);
      end else if AItem.CheckItem(RtfExpression, RtfElseExpression) then begin
        if not Assigned(ABranche)
        then raise TRtfException.Create('unexpected else');

        HlpItems.Extract(AItem); //Remove else item
        AItem := ABranche.Parent; //Points to "if" statement
        if AItem.RtfClass = RtfBranche
        then AItem := AItem.Parent; //Points to "if" statement
        if not Assigned(AItem)
        then raise TRtfException.Create('unexpected else');
        if not AItem.CheckItem(RtfExpression, RtfIfExpression)
        then raise TRtfException.Create('unexpected scanentry');

        ABranche := TRtfItem.Create;
        ABranche.RtfClass := RtfBranche;
        ABranche.RtfMajor := RtfElseExpression;
        TmpItems.Add(ABranche); //Otherwise memory leak
        AItem.Add(ABranche);
      end else if AItem.CheckItem(RtfExpression, RtfEndifExpression) then begin
        if not Assigned(ABranche)
        then raise TRtfException.Create('unexpected endif');

        HlpItems.Extract(AItem); //Remove item
        ABranche := ABranche.Parent;
        ABranche := ABranche.Parent;
        if ABranche = HlpItems
        then ABranche := nil;
      end else if AItem.CheckItem(RtfExpression, RtfScan) then begin

        if Assigned(ABranche) then begin
          HlpItems.Extract(AItem);
          ABranche.Add(AItem);
        end
        else Inc(AIndex);

        ABranche := TRtfItem.Create;
        ABranche.RtfClass := RtfBranche;
        ABranche.RtfMajor := RtfScan;
        TmpItems.Add(ABranche); //Otherwise memory leak
        AItem.Add(ABranche);
      end else if AItem.CheckItem(RtfExpression, RtfScanEntry) then begin
        if not Assigned(ABranche)
        then raise TRtfException.Create('unexpected scanentry');

        HlpItems.Extract(AItem); //Remove else item
        AItem := ABranche.Parent; //Points to "scan" statement
        if AItem.RtfClass = RtfBranche
        then AItem := AItem.Parent; //Points to "scan" statement
        if not Assigned(AItem)
        then raise TRtfException.Create('unexpected scanentry');
        if not AItem.CheckItem(RtfExpression, RtfScan)
        then raise TRtfException.Create('unexpected scanentry');

        ABranche := TRtfItem.Create;
        ABranche.RtfClass := RtfBranche;
        ABranche.RtfMajor := RtfScanEntry;
        TmpItems.Add(ABranche); //Otherwise memory leak
        AItem.Add(ABranche);
      end else if AItem.CheckItem(RtfExpression, RtfScanFooter) then begin
        if not Assigned(ABranche)
        then raise TRtfException.Create('unexpected scanfooter');

        HlpItems.Extract(AItem); //Remove item
        AItem := ABranche.Parent; //Points to "scan" statement
        if AItem.RtfClass = RtfBranche
        then AItem := AItem.Parent; //Points to "scan" statement
        if not Assigned(AItem)
        then raise TRtfException.Create('unexpected scanfooter');
        if not AItem.CheckItem(RtfExpression, RtfScan)
        then raise TRtfException.Create('unexpected scanfooter');

        ABranche := TRtfItem.Create;
        ABranche.RtfClass := RtfBranche;
        ABranche.RtfMajor := RtfScanFooter;
        TmpItems.Add(ABranche); //Otherwise memory leak
        AItem.Add(ABranche);
      end else if AItem.CheckItem(RtfExpression, RtfScanEnd) then begin
        if not Assigned(ABranche)
        then raise TRtfException.Create('unexpected scanend');

        HlpItems.Extract(AItem); //Remove item
        ABranche := ABranche.Parent;
        ABranche := ABranche.Parent;
        if ABranche = HlpItems
        then ABranche := nil;
      end else begin
        if Assigned(ABranche) then begin
          HlpItems.Extract(AItem);
          ABranche.Add(AItem);
        end
        else Inc(AIndex);
      end;
    except
      on e: Exception do begin
        fpgApplication.HandleException(e);
{
        if Assigned(AItem)
        then AItem.RtfTextBuf := AItem.RtfTextBuf + ' ' + E.Message;
}
      end;
    end;
  end;

  if Assigned(ABranche) then begin
    if Assigned(AItem) then begin
      AForeColor := ColorList.UseColor(ErrorForeColor);
      ABackColor := ColorList.UseColor(ErrorBackColor);
      AItem.FRtfTextBuf := Format('{\b\ul\highlight%d\cf%d <<<<endif or endscan missing}%s',[ABackColor, AForeColor, AItem.RtfTextBuf]);
    end;
  end;
end;

function TtiRtfParser.SkipParagraph(AItem: TRtfItem): TRtfItem;
//Remove paragraph breaks if it was just a procedure (or a VAR/SET etc.)
//This can be multiple breaks (CrLf and /Par controls) but
//do not remove more than a single item from each of them
var AEnter, APar, AParDef: boolean;
begin
  APar := false;
  AEnter := false;
  AParDef := false;
  while Assigned(AItem) do
  begin
    case AItem.RtfClass of
      RtfText: begin
        if not AEnter and(Pos(#13#10, AItem.RtfTextBuf) > 0) then
        begin
          //Crap, it can contain multiple #13#10's
          AItem.RtfTextBuf := StringReplace(AItem.RtfTextBuf, #13#10, '',[rfReplaceAll]);
          AItem := AItem.Next;
          AEnter := true;
          continue;
        end
        else
          break;
      end;
      RtfControl: begin
        case AItem.RtfMajor of
          RtfSpecialChar: begin
            case AItem.RtfMinor of
              RtfPar: begin
                if not APar then
                begin
                  AItem := AItem.Next;
                  APar := true;
                  continue;
                end
                else
                  break;
              end;
              RtfParDef: begin
                if not AParDef then
                begin
                  AItem := AItem.Next;
                  AParDef := true;
                  continue;
                end
                else
                  break;
              end;
            end;
          end;
        end;
      end;
    end;
    break;
  end;
  Result := AItem;
end;

procedure TtiRtfParser.Parse(AItems: TRtfItem);
//Forward all stuff to the output list
var
  i: integer;
  AItem: TRtfItem;
begin
  for i := 0 to AItems.Count - 1 do
  begin
    AItem := AItems[i];
    if AItem.RtfClass = RtfExpression then
      ParseExpression(AItem)
    else
      AddToRtfItems(AItem);
  end;
end;

procedure TtiRtfParser.ParseExpression(AItem: TRtfItem);
var
  i, ABackColor, AForeColor: integer;
  ARemove: boolean;
  ADataset: TRtfDataset;
  AScanNoEof: boolean;
  AExpression: string;
  AResultValue: variant;
  AResultParam: integer;
  AResultToken: TRtfToken;
  AArguments: TRtfArgument;
  AAnswer, ATemp, AHeader, ARecord, AFooter: TRtfItem;
begin
  AExpression := AItem.RtfTextBuf;
  AAnswer := AddToRtfItems(AItem);
  AAnswer.RtfTextBuf := '';

  try
    ARemove := true;
    AArguments := TRtfArgument.Create(Self);
    try
      AArguments.ParseExpression(AExpression);
      if AArguments.Count > 0 then
      begin
        //procedures and variables have no returning value and etNothing, well
        ARemove := AArguments[0].Token in[etVariable, etProcedure, etNothing];
        if (AArguments[0].Token = etVariable) and (AArguments.Count = 1) then
          ARemove := false; //But show a single variable
      end;
      if Assigned(OnEvalutate) then //debug
        OnEvalutate(AArguments);
      AArguments.Evaluate;
      AResultToken := AArguments.Token;
      AResultValue := AArguments.Value;
      AResultParam := AArguments.Param;
      if Assigned(OnEvalutate) then //debug
        OnEvalutate(AArguments);

      case AItem.RtfMajor of
        RtfNormalExpression: begin
          if not ARemove then begin
            //Expand booleans and date to text values (date because Variant
            //have no typing for it. Place the text into the output rtf
            if AResultToken = etLitTrue then
              AAnswer.RtfTextBuf := BoolTrue
            else if AResultToken = etLitFalse then
              AAnswer.RtfTextBuf := BoolFalse
            else if AResultToken = etLitDate then
            begin
              if Frac(AResultValue) = 0 then
                AAnswer.RtfTextBuf := DateToStr(AResultValue)
              else if Int(AResultValue) = 0 then
                AAnswer.RtfTextBuf := TimeToStr(AResultValue)
              else
                AAnswer.RtfTextBuf := DateTimeToStr(AResultValue);
            end
            else
              AAnswer.RtfTextBuf := VarToStr(AResultValue);
          end;
        end;
        
        RtfIfExpression:
            begin
              if AResultToken = etLitTrue then
                Parse(AItem[0])
              else if(AResultToken = etLitFalse)and(AItem.Count > 1) then
                Parse(AItem[1]);
            end;

        RtfScan:
            begin
        //Scan(Dataset). Find out what items is header, record and footer
          ARecord := nil;
          AHeader := nil;
          AFooter := nil;
          ADataset := TRtfDataset(PtrInt(AResultValue)); //Dirty!

          for i := 0 to AItem.Count - 1 do begin
            ATemp := AItem[i];
            case ATemp.RtfMajor of
              RtfScan: AHeader := ATemp;
              RtfScanEntry: ARecord := ATemp;
              RtfScanFooter: AFooter := ATemp;
            end;
          end;

          if AHeader = ARecord
          then AHeader := nil;
          if ARecord = nil then begin
            ARecord := AHeader;
            AHeader := nil;
          end;

          AScanNoEof := AResultParam = 1;

          //And evaluate the Scan(dataset)
          ADataset.Open;
          if Assigned(AHeader)
          then Parse(AHeader);
          ADataset.First;

          if AScanNoEof and ADataset.Eof
          then exit; //Also no footer..

          while not ADataset.Eof do begin
            if Assigned(ARecord)
            then Parse(ARecord);
            ADataset.Next;
          end;
          if Assigned(AFooter)
          then Parse(AFooter);
        end;
      end;
    finally
      AArguments.Free;
    end;

  except
    on e: Exception do begin
      AForeColor := ColorList.UseColor(ErrorForeColor);
      ABackColor := ColorList.UseColor(ErrorBackColor);
      AAnswer.FRtfTextBuf := Format('{\b\ul\highlight%d\cf%d %s %s}',[ABackColor, AForeColor, AExpression, E.Message]);
    end;
  end;
end;

procedure TtiRtfParser.AddFunctions;
begin
  //Extra tokens not tokenized by RawParser
  FFunctions.Add(etOr, 'Or', 0, 0, nil);
  FFunctions.Add(etNot, 'Not', 0, 0, nil);
  FFunctions.Add(etAnd, 'And', 0, 0, nil);
  FFunctions.Add(etLitTrue, 'True', 0, 0, nil);
  FFunctions.Add(etLitFalse, 'False', 0, 0, nil);

  //Date time functions/conversions
  FFunctions.Add(etFunction, 'Year', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfYear);
  FFunctions.Add(etFunction, 'Month', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfMonth);
  FFunctions.Add(etFunction, 'Day', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfDay);
  FFunctions.Add(etFunction, 'SYear', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfSYear);
  FFunctions.Add(etFunction, 'SMonth', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfSMonth);
  FFunctions.Add(etFunction, 'SDay', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfSDay);
  FFunctions.Add(etFunction, 'Dtos', 1, 2, {$IFDEF FPC}@{$ENDIF}UdfDtos);
  FFunctions.Add(etFunction, 'Stod', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStod);
  FFunctions.Add(etFunction, 'DateToStr', 1, 2, {$IFDEF FPC}@{$ENDIF}UdfDateToStr);
  FFunctions.Add(etFunction, 'TimeToStr', 1, 2, {$IFDEF FPC}@{$ENDIF}UdfTimeToStr);
  FFunctions.Add(etFunction, 'DateTimeToStr', 1, 2, {$IFDEF FPC}@{$ENDIF}UdfDateTimeToStr);
  FFunctions.Add(etFunction, 'StrToDate', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStrToDate);
  FFunctions.Add(etFunction, 'StrToTime', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStrToTime);
  FFunctions.Add(etFunction, 'StrToDateTime', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStrToDateTime);
  FFunctions.Add(etFunction, 'ShortMonthName', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfShortMonthName);
  FFunctions.Add(etFunction, 'ShortDayName', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfShortDayName);
  FFunctions.Add(etFunction, 'LongMonthName', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfLongMonthName);
  FFunctions.Add(etFunction, 'LongDayName', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfLongDayName);

  //String, int, float functions/conversions
  FFunctions.Add(etFunction, 'Int', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfInt);
  FFunctions.Add(etFunction, 'Chr', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfChr);
  FFunctions.Add(etFunction, 'Iif', 3, 3, {$IFDEF FPC}@{$ENDIF}UdfIif);
  FFunctions.Add(etFunction, 'Str', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStr);
  FFunctions.Add(etFunction, 'Val', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfVal);
  FFunctions.Add(etFunction, 'Nul', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfNul);
  FFunctions.Add(etFunction, 'Now', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfNow);
  FFunctions.Add(etFunction, 'Frac', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfFrac);
  FFunctions.Add(etFunction, 'Padr', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfPadr);
  FFunctions.Add(etFunction, 'Padl', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfPadl);
  FFunctions.Add(etFunction, 'Date', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDate);
  FFunctions.Add(etFunction, 'Time', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfTime);
  FFunctions.Add(etFunction, 'Mid', 2, 3, {$IFDEF FPC}@{$ENDIF}UdfSubStr);
  FFunctions.Add(etFunction, 'Copy', 2, 3, {$IFDEF FPC}@{$ENDIF}UdfSubStr);
  FFunctions.Add(etFunction, 'SubStr', 2, 3, {$IFDEF FPC}@{$ENDIF}UdfSubStr);
  FFunctions.Add(etFunction, 'Trunc', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfTrunc);
  FFunctions.Add(etFunction, 'Round', 1, 2, {$IFDEF FPC}@{$ENDIF}UdfRound);
  FFunctions.Add(etFunction, 'Upper', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfUpper);
  FFunctions.Add(etFunction, 'Lower', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfLower);
  FFunctions.Add(etFunction, 'Trim', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfTrim);
  FFunctions.Add(etFunction, 'Empty', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfEmpty);
  FFunctions.Add(etFunction, 'TrimLeft', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfTrimLeft);
  FFunctions.Add(etFunction, 'TrimRight', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfTrimRight);
  FFunctions.Add(etFunction, 'IntToStr', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfIntToStr);
  FFunctions.Add(etFunction, 'StrToInt', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStrToInt);
  FFunctions.Add(etFunction, 'FloatToStr', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfFloatToStr);
  FFunctions.Add(etFunction, 'StrToFloat', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfStrToFloat);
  FFunctions.Add(etFunction, 'Power', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfIntPower);
  FFunctions.Add(etFunction, 'IntPower', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfIntPower);
  FFunctions.Add(etFunction, 'FormatFloat', 2, 2, {$IFDEF FPC}@{$ENDIF}UdfFormatFloat);
  FFunctions.Add(etFunction, 'FBool', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfFbool);

  //Dataset
  FFunctions.Add(etFunction, 'Bof', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfBof);
  FFunctions.Add(etFunction, 'Eof', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfEof);
  FFunctions.Add(etProcedure, 'Next', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfNext);
  FFunctions.Add(etProcedure, 'Prev', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfPrior);
  FFunctions.Add(etProcedure, 'Open', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfOpen);
  FFunctions.Add(etProcedure, 'First', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfFirst);
  FFunctions.Add(etProcedure, 'Last', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfLast);
  FFunctions.Add(etFunction, 'IsEmpty', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfIsEmpty);
  FFunctions.Add(etFunction, 'RecordCount', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfRecordCount);
  FFunctions.Add(etProcedure, 'Scan', 1, 9999, {$IFDEF FPC}@{$ENDIF}UdfScan);
  FFunctions.Add(etProcedure, 'EndScan', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etProcedure, 'ScanEntry', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etProcedure, 'ScanFooter', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etProcedure, 'Dataset', 3, 9999, {$IFDEF FPC}@{$ENDIF}UdfDataset);

  //Misc routines
  FFunctions.Add(etProcedure, 'If', 1, 9999, {$IFDEF FPC}@{$ENDIF}UdfIf);
  FFunctions.Add(etProcedure, 'Else', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etProcedure, 'Endif', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etProcedure, 'NoPar', 0, 0, {$IFDEF FPC}@{$ENDIF}UdfDummy);
  FFunctions.Add(etFunction, 'Picture', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfPicture);
  FFunctions.Add(etFunction, 'DbPicture', 1, 1, {$IFDEF FPC}@{$ENDIF}UdfDbPicture);
end;

procedure TtiRtfParser.UdfDummy(AArgument: TRtfArgument);
begin
  //Nothing, since its an etProcedure the Rtf paragraph will be removed
end;

procedure TtiRtfParser.UdfChr(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitInt])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := Chr(StrToInt(AArgument[0].Value));
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfNow(AArgument: TRtfArgument);
begin
  AArgument.Value := Now;
  AArgument.Token := etLitDate;
end;

procedure TtiRtfParser.UdfDate(AArgument: TRtfArgument);
begin
  AArgument.Value := Date;
  AArgument.Token := etLitDate;
end;

procedure TtiRtfParser.UdfTime(AArgument: TRtfArgument);
begin
  AArgument.Value := Time;
  AArgument.Token := etLitDate;
end;

procedure TtiRtfParser.UdfIntToStr(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitInt])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := IntToStr(AArgument[0].Value);
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfStrToInt(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := StrToInt(AArgument[0].Value);
  AArgument.Token := etLitInt;
end;

procedure TtiRtfParser.UdfFloatToStr(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFloat])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := FloatToStr(Extended(AArgument[0].Value));
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfStrToFloat(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := StrToFloat(AArgument[0].Value);
  AArgument.Token := etLitFloat;
end;

procedure TtiRtfParser.UdfNul(AArgument: TRtfArgument);
var AStr: string;
  ACnt: integer;
begin
  if not AArgument.Check([[etLitInt],[etLitInt]])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AStr := AArgument[0].Value;
  ACnt := AArgument[1].Value;
  while Length(AStr) < ACnt do AStr := '0' + AStr;
  while Length(AStr) > ACnt do Delete(AStr, 1, 1);
  AArgument.Value := AStr;
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfPadl(AArgument: TRtfArgument);
var AStr: string;
  ACnt: integer;
begin
  if not AArgument.Check([[etLitString],[etLitInt]])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AStr := AArgument[0].Value;
  ACnt := AArgument[1].Value;
  AStr := Copy(AStr, 1, ACnt);
  while Length(AStr) < ACnt do begin
    AStr := ' ' + AStr;
  end;
  AArgument.Value := AStr;
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfPadr(AArgument: TRtfArgument);
var AStr: string;
  ACnt: integer;
begin
  if not AArgument.Check([[etLitString],[etLitInt]])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AStr := AArgument[0].Value;
  ACnt := AArgument[1].Value;
  AStr := Copy(AStr, 1, ACnt);
  while Length(AStr) < ACnt do begin
    AStr := AStr + ' ';
  end;
  AArgument.Value := AStr;
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfIif(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFalse, etLitTrue])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitTrue then begin
    AArgument.Value := AArgument[1].Value;
    AArgument.Token := AArgument[1].Token;
  end else begin
    AArgument.Value := AArgument[2].Value;
    AArgument.Token := AArgument[2].Token;
  end;
end;

procedure TtiRtfParser.UdfIf(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFalse, etLitTrue])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := AArgument[0].Value;
  AArgument.Token := AArgument[0].Token;
end;

procedure TtiRtfParser.UdfScan(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Value := AArgument[0].Value;
  AArgument.Token := AArgument[0].Token;
  if AArgument.Count > 1 then begin
    if AArgument[1].Token = etLitTrue
    then AArgument.Param := 1;
  end;
end;

procedure TtiRtfParser.UdfDataset(AArgument: TRtfArgument);
var ADatabase, AAliasName, ASqlScript: string;
  ADataset: TRtfDataset;
  AObject: TObject;
begin
  if not AArgument.Check([[etLitString],[etLitString],[etLitString]])
  then raise TRtfException.Create(rsUnexpectedParameterType);

  ADatabase := AArgument[0].Value;
  AAliasName := AArgument[1].Value;
  ASqlScript := AArgument[2].Value;

  //Delete first argument so Sql params become first
  AArgument.Delete(0);
  AArgument.Delete(0);
  AArgument.Delete(0);

  //Remove existing dataset with same aliasname
  ADataset := Datasets.Find(AAliasName);
  if Assigned(ADataset)
  then Datasets.Remove(ADataset);

  //Create the new query or dataset (whatever)
  if Assigned(OnCreateDataset)
  then OnCreateDataset(ADatabase, AAliasName, ASqlScript, AArgument)
  else raise TRtfException.Create('OnCreateDataset is not assigned');
  if VarIsEmpty(AArgument.Value)
  then raise TRtfException.Create('OnCreateDataset did not return a dataset object');

  AObject := TObject(Ptrint(AArgument.Value));
  ADataset := Datasets.Add(AObject, AAliasname, true);
  AArgument.Token := etDataset;
  AArgument.Value := PtrInt(ADataset);
end;

procedure TtiRtfParser.UdfLower(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := LowerCase(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfUpper(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := UpperCase(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfTrim(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := Trim(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfTrimLeft(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := TrimLeft(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfTrimRight(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := TrimRight(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfSubStr(AArgument: TRtfArgument);
var AStr: string;
  APos, ACnt: integer;
begin
  ACnt := Maxint;
  if not AArgument.Check([[etLitString],[etLitInt]])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument.Count > 2 then begin
    if not AArgument.Check(2,[etLitInt]) then
      raise TRtfException.Create(rsUnexpectedParameterType);
    ACnt := AArgument[2].Value;
  end;
  AStr := AArgument[0].Value;
  APos := AArgument[1].Value;
  AStr := Copy(AStr, APos, ACnt);
  AArgument.Value := AStr;
  AArgument.Token := etLitString;
end;

procedure TtiRtfParser.UdfStr(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFloat, etLitInt]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitFloat then
  begin
    AArgument.Token := etLitString;
    AArgument.Value := FloatToStr(AArgument[0].Value);
  end
  else
  begin
    AArgument.Token := etLitString;
    AArgument.Value := IntToStr(AArgument[0].Value);
  end;
end;

procedure TtiRtfParser.UdfVal(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  if (Pos('.', AArgument[0].Value) > 0)or(Pos(',', AArgument[0].Value) > 0) then
  begin
    AArgument.Token := etLitString;
    AArgument.Value := StrToFloat(AArgument[0].Value)
  end
  else
  begin
    AArgument.Token := etLitString;
    AArgument.Value := StrToInt(AArgument[0].Value)
  end;
end;

procedure TtiRtfParser.UdfBof(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  if ATable.Bof then
  begin
    AArgument.Token := etLitTrue;
    AArgument.Value := true;
  end
  else
  begin
    AArgument.Token := etLitFalse;
    AArgument.Value := false;
  end;
end;

procedure TtiRtfParser.UdfEof(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  if ATable.Eof then
  begin
    AArgument.Token := etLitTrue;
    AArgument.Value := true;
  end
  else
  begin
    AArgument.Token := etLitFalse;
    AArgument.Value := false;
  end;
end;


procedure TtiRtfParser.UdfRecordCount(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  AArgument.Token := etLitInt;
  AArgument.Value := ATable.RecordCount
end;

procedure TtiRtfParser.UdfIsEmpty(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  if ATable.IsEmpty then begin
    AArgument.Token := etLitTrue;
    AArgument.Value := true;
  end else begin
    AArgument.Token := etLitFalse;
    AArgument.Value := false;
  end;
end;

procedure TtiRtfParser.UdfFirst(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  ATable.First;
end;

procedure TtiRtfParser.UdfLast(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  ATable.Last;
end;

procedure TtiRtfParser.UdfNext(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  ATable.Next;
end;

procedure TtiRtfParser.UdfOpen(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  ATable.Open;
end;

procedure TtiRtfParser.UdfPrior(AArgument: TRtfArgument);
var ATable: TRtfDataset;
begin
  if not AArgument.Check(0,[etDataset])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  ATable := TRtfDataset(Ptrint(AArgument[0].Value));
  ATable.Prior;
end;

procedure TtiRtfParser.UdfInt(AArgument: TRtfArgument);
//Returns the integer part of a float
begin
  if not AArgument.Check(0,[etLitFloat, etLitInt])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitFloat then begin
    AArgument.Token := etLitFloat;
    AArgument.Value := Int(AArgument[0].Value);
  end else begin
    AArgument.Token := etLitInt;
    AArgument.Value := AArgument[0].Value;
  end;
end;

procedure TtiRtfParser.UdfFrac(AArgument: TRtfArgument);
//Returns the fractional part of a float
begin
  if not AArgument.Check(0,[etLitFloat, etLitInt])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitFloat then begin
    AArgument.Token := etLitFloat;
    AArgument.Value := Frac(AArgument[0].Value);
  end else begin
    AArgument.Token := etLitInt;
    AArgument.Value := 0;
  end;
end;

procedure TtiRtfParser.UdfRound(AArgument: TRtfArgument);
//0.5 is always rounded to largest integer number
var
  ASign, ADecimals, AInt: integer;
  AFloat, APower, AFrac: Double;
begin
  ADecimals := 0;
  if not AArgument.Check(0,[etLitFloat, etLitInt]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument.Count > 1 then
  begin
    if not AArgument.Check(1,[etLitInt]) then
      raise TRtfException.Create(rsUnexpectedParameterType);
    ADecimals := AArgument[1].Value;
  end;

  if AArgument[0].Token = etLitFloat then
  begin
    AFloat := AArgument[0].Value;

    ASign := 1;
    if AFloat < 0 then
    begin
      AFloat := - AFloat;
      ASign := - 1;
    end;

    if ADecimals = 0 then
    begin
      AInt := Trunc(AFloat); //integer part
      AFrac := AFloat - AInt; //fractional part
      if AFrac >= 0.5 then
        AArgument.Value := ASign *(AInt + 1)
      else
        AArgument.Value := ASign * AInt;
      AArgument.Token := etLitFloat;
    end
    else
    begin
      APower := IntPower(10, ADecimals);
      AInt := Trunc(AFloat * APower); //integer part * 10^ADecimals
      AFrac := AFloat * APower - AInt; //fractional part
      if AFrac >= 0.5 then
        AArgument.Value := ASign * IntPower(10, - ADecimals) *(AInt + 1)
      else
        AArgument.Value := ASign * IntPower(10, - ADecimals) * AInt;
      AArgument.Token := etLitFloat;
    end;
  end
  else
  begin
    AArgument.Token := etLitInt;
    AArgument.Value := AArgument[0].Value;
  end;
end;

procedure TtiRtfParser.UdfTrunc(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFloat, etLitInt])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitFloat then begin
    AArgument.Token := etLitFloat;
    AArgument.Value := Trunc(AArgument[0].Value);
  end else begin
    AArgument.Token := etLitInt;
    AArgument.Value := AArgument[0].Value;
  end;
end;

procedure TtiRtfParser.UdfIntPower(AArgument: TRtfArgument);
var AFloat: Double;
  AExponent: integer;
begin
  if not AArgument.Check([[etLitInt, etLitFloat],[etLitInt]]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  AFloat := AArgument[0].Value;
  AExponent := AArgument[1].Value;
  AArgument.Token := etLitFloat;
  AArgument.Value := IntPower(AFloat, AExponent);
end;

procedure TtiRtfParser.UdfPower(AArgument: TRtfArgument);
var AFloat, AExponent: Double;
begin
  if not AArgument.Check([[etLitInt, etLitFloat],[etLitInt, etLitFloat]])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AFloat := AArgument[0].Value;
  AExponent := AArgument[1].Value;
  AArgument.Token := etLitFloat;
  AArgument.Value := Pwr(AFloat, AExponent);
end;

procedure TtiRtfParser.UdfEmpty(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  if Trim(AArgument[0].Value) = '' then begin
    AArgument.Token := etLitTrue;
    AArgument.Value := true;
  end else begin
    AArgument.Token := etLitFalse;
    AArgument.Value := false;
  end;
end;

procedure TtiRtfParser.UdfDay(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitInt;
  AArgument.Value := ADay;
end;

procedure TtiRtfParser.UdfMonth(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitInt;
  AArgument.Value := AMonth;
end;

procedure TtiRtfParser.UdfYear(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitInt;
  AArgument.Value := AYear;
end;

procedure TtiRtfParser.UdfShortDayName(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := ShortDayNames[ADay];
end;

procedure TtiRtfParser.UdfShortMonthName(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := ShortMonthNames[AMonth];
end;

procedure TtiRtfParser.UdfLongDayName(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := LongMonthNames[AMonth];
end;

procedure TtiRtfParser.UdfLongMonthName(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := LongMonthNames[AMonth];
end;

procedure TtiRtfParser.UdfSDay(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := Format('%0.2d',[ADay]);
end;

procedure TtiRtfParser.UdfSMonth(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := Format('%0.2d',[AMonth]);
end;

procedure TtiRtfParser.UdfSYear(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
begin
  if not AArgument.Check(0,[etLitDate])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  DecodeDate(AArgument[0].Value, AYear, AMonth, ADay);
  AArgument.Token := etLitString;
  AArgument.Value := Format('%0.4d',[AYear]);
end;

procedure TtiRtfParser.UdfStod(AArgument: TRtfArgument);
var AYear, AMonth, ADay: word;
  AStr: string;
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AStr := AArgument[0].Value;
  AYear := StrToInt(Copy(AStr, 1, 4));
  AMonth := StrToInt(Copy(AStr, 5, 2));
  ADay := StrToInt(Copy(AStr, 7, 2));
  AArgument.Token := etLitDate;
  AArgument.Value := EncodeDate(AYear, AMonth, ADay);
end;

procedure TtiRtfParser.UdfDateTimeTo(AArgument: TRtfArgument; AFormat: string);
begin
  if not AArgument.Check(0,[etLitDate]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument.Count > 1 then
  begin
    if not AArgument.Check(1,[etLitString]) then
      raise TRtfException.Create(rsUnexpectedParameterType);
    AFormat := AArgument[1].Value;
  end;
  AArgument.Token := etLitString;
  AArgument.Value := FormatDateTime(AFormat, AArgument[0].Value);
end;

procedure TtiRtfParser.UdfDtoS(AArgument: TRtfArgument);
begin
  UdfDateTimeTo(AArgument, 'YYYYMMDD');
end;

procedure TtiRtfParser.UdfDateToStr(AArgument: TRtfArgument);
begin
  UdfDateTimeTo(AArgument, ShortDateFormat);
end;

procedure TtiRtfParser.UdfTimeToStr(AArgument: TRtfArgument);
begin
  UdfDateTimeTo(AArgument, ShortTimeFormat);
end;

procedure TtiRtfParser.UdfDateTimeToStr(AArgument: TRtfArgument);
begin
  UdfDateTimeTo(AArgument, ShortDateFormat + ' ' + ShortTimeFormat);
end;

procedure TtiRtfParser.UdfStrToDate(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := StrToDate(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfStrToTime(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := StrToTime(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfStrToDateTime(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  AArgument.Token := etLitString;
  AArgument.Value := StrToDateTime(AArgument[0].Value);
end;

procedure TtiRtfParser.UdfFormatFloat(AArgument: TRtfArgument);
var AFormat: string;
  AFloat: Double;
begin
  if not AArgument.Check([[etLitString],[etLitFloat, etLitInt]]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  AFormat := AArgument[0].Value;
  AFloat := AArgument[1].Value;
  AArgument.Token := etLitString;
  AArgument.Value := FormatFloat(AFormat, AFloat);
end;

procedure TtiRtfParser.UdfFBool(AArgument: TRtfArgument);
begin
  if not AArgument.Check(0,[etLitFalse, etLitTrue]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  if AArgument[0].Token = etLitFalse then
  begin
    AArgument.Token := etLitString;
    AArgument.Value := BoolFalse;
  end else begin
    AArgument.Token := etLitString;
    AArgument.Value := BoolTrue;
  end;
end;

procedure TtiRtfParser.UdfPicture(AArgument: TRtfArgument);
{
var
  APicture: TPicture;
  AFilename: string;
}
begin
(*
  if not AArgument.Check(0,[etLitString])
  then raise TRtfException.Create(rsUnexpectedParameterType);
  APicture := TPicture.Create;
  try
    AFilename := AArgument[0].Value;
    if Assigned(OnPicturePath)
    then OnPicturePath(AFilename);

    APicture.LoadFromFile(AFilename);
    if not Assigned(APicture.Graphic)or APicture.Graphic.Empty then begin
      AArgument.Token := etNothing;
      AArgument.Value := varEmpty;
    end else begin
      AArgument.Value := AArgument.GetPicture(APicture);
      AArgument.Token := etLitString;
    end;
  finally
    APicture.Free;
  end;
  *)
end;

procedure TtiRtfParser.UdfDbPicture(AArgument: TRtfArgument);
//Since a simple blob (not ftGraphic field) can contain an image
//It has become kind of a typecast for a dataset field.
var ADataset: TRtfDataset;
  AFieldName: string;
begin
  if not AArgument.Check(0,[etFieldName]) then
    raise TRtfException.Create(rsUnexpectedParameterType);
  ADataset := Datasets.Find(AArgument[0].Value, AFieldName);
  if not Assigned(ADataset) then //There should be at least a table reference.
    raise TRtfException.Create('Dataset not found');
  AArgument.GetGraphicsValue(ADataset, AFieldName);
end;

end.