aboutsummaryrefslogtreecommitdiff
path: root/engines/tony/mpal/mpal.cpp
blob: 5a4310c15baaf3a9180d36d7524b243ecdd80f5b (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
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

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

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *
 */
/*
 * This code is based on original Tony Tough source code
 *
 * Copyright (c) 1997-2003 Nayma Software
 */

#include "common/scummsys.h"
#include "common/file.h"
#include "common/savefile.h"
#include "common/system.h"
#include "tony/tony.h"
#include "tony/mpal/lzo.h"	
#include "tony/mpal/mpal.h"
#include "tony/mpal/mpaldll.h"

namespace Tony {

namespace MPAL {

#define GETARG(type)   va_arg(v, type)

/****************************************************************************\
*       Copyright
\****************************************************************************/

const char *mpalCopyright =
	"\n\nMPAL - MultiPurpose Adventure Language for Windows 95\n"
	"Copyright 1997-98 Giovanni Bajo and Luca Giusti\n"
	"ALL RIGHTS RESERVED\n"
	"\n"
	"\n";

/****************************************************************************\
*       Internal functions
\****************************************************************************/

/**
 * Locks the variables for access
 */
void lockVar(void) {
	GLOBALS.lpmvVars = (LPMPALVAR)globalLock(GLOBALS.hVars);
}


/**
 * Unlocks variables after use
 */
void unlockVar(void) {
	globalUnlock(GLOBALS.hVars);
}


/**
 * Locks the messages for access
 */
static void LockMsg(void) {
#ifdef NEED_LOCK_MSGS
	GLOBALS.lpmmMsgs = (LPMPALMSG)globalLock(GLOBALS.hMsgs);
#endif
}


/**
 * Unlocks the messages after use
 */
static void UnlockMsg(void) {
#ifdef NEED_LOCK_MSGS
	globalUnlock(GLOBALS.hMsgs);
#endif
}


/**
 * Locks the dialogs for access
 */
static void lockDialogs(void) {
	GLOBALS.lpmdDialogs = (LPMPALDIALOG)globalLock(GLOBALS.hDialogs);
}


/**
 * Unlocks the dialogs after use
 */
static void unlockDialogs(void) {
	globalUnlock(GLOBALS.hDialogs);
}


/**
 * Locks the location data structures for access
 */
static void lockLocations(void) {
	GLOBALS.lpmlLocations = (LPMPALLOCATION)globalLock(GLOBALS.hLocations);
}


/**
 * Unlocks the location structures after use
 */
static void unlockLocations(void) {
	globalUnlock(GLOBALS.hLocations);
}


/**
 * Locks the items structures for use
 */
static void lockItems(void) {
	GLOBALS.lpmiItems = (LPMPALITEM)globalLock(GLOBALS.hItems);
}


/**
 * Unlocks the items structures after use
 */
static void unlockItems(void) {
	globalUnlock(GLOBALS.hItems);
}


/**
 * Locks the script data structures for use
 */
static void LockScripts(void) {
	GLOBALS.lpmsScripts = (LPMPALSCRIPT)globalLock(GLOBALS.hScripts);
}


/**
 * Unlocks the script data structures after use
 */
static void unlockScripts(void) {
	globalUnlock(GLOBALS.hScripts);
}


/**
 * Returns the current value of a global variable
 *
 * @param lpszVarName		Name of the variable
 * @returns		Current value
 * @remarks		Before using this method, you must call lockVar() to
 * lock the global variablves for use. Then afterwards, you will
 * need to remember to call UnlockVar()
 */
int32 varGetValue(const char *lpszVarName) {
	int i;
	LPMPALVAR v=GLOBALS.lpmvVars;

	for (i = 0; i < GLOBALS.nVars; v++, i++)
		if (strcmp(lpszVarName, v->lpszVarName) == 0)
			return v->dwVal;

	GLOBALS.mpalError = 1;
	return 0;
}


/**
 * Sets the value of a MPAL global variable
 * @param lpszVarName       Name of the variable
 * @param val				Value to set
 */
void varSetValue(const char *lpszVarName, int32 val) {
	uint i;
	LPMPALVAR v = GLOBALS.lpmvVars;

	for (i = 0; i < GLOBALS.nVars; v++, i++)
		if (strcmp(lpszVarName, v->lpszVarName) == 0) {
			v->dwVal = val;
			if (GLOBALS.lpiifCustom != NULL && strncmp(v->lpszVarName, "Pattern.", 8) == 0) {
				i = 0;
				sscanf(v->lpszVarName, "Pattern.%u", &i);
				GLOBALS.lpiifCustom(i, val, -1);
			} else if (GLOBALS.lpiifCustom != NULL && strncmp(v->lpszVarName, "Status.", 7) == 0) {
				i = 0;
				sscanf(v->lpszVarName,"Status.%u", &i);
				GLOBALS.lpiifCustom(i, -1, val);
			}
			return;
		}

	GLOBALS.mpalError = 1;
	return;
}


/**
 * Find the index of a location within the location array. Remember to call LockLoc() beforehand.
 *
 * @param nLoc				Location number to search for
 * @returns		Index, or -1 if the location is not present
 * @remarks		This function requires the location list to have
 * first been locked with a call to LockLoc().
 */
static int locGetOrderFromNum(uint32 nLoc) {
	int i;
	LPMPALLOCATION loc = GLOBALS.lpmlLocations;

	for (i = 0; i < GLOBALS.nLocations; i++, loc++)
		if (loc->nObj == nLoc)
			return i;

	return -1;
}


/**
 * Find the index of a message within the messages array
 * @param nMsg				Message number to search for
 * @returns		Index, or -1 if the message is not present
 * @remarks		This function requires the message list to have
 * first been locked with a call to LockMsg()
 */
static int msgGetOrderFromNum(uint32 nMsg) {
	int i;
	LPMPALMSG msg = GLOBALS.lpmmMsgs;

	for (i = 0; i < GLOBALS.nMsgs; i++, msg++)
		if (msg->wNum == nMsg)
			return i;

	return -1;
}

/**
 * Find the index of an item within the items array
 * @param nItem				Item number to search for
 * @returns		Index, or -1 if the item is not present
 * @remarks		This function requires the item list to have
 * first been locked with a call to LockItems()
 */
static int itemGetOrderFromNum(uint32 nItem) {
	int i;
	LPMPALITEM item = GLOBALS.lpmiItems;

	for (i = 0; i < GLOBALS.nItems; i++, item++)
		if (item->nObj == nItem)
			return i;

	return -1;
}


/**
 * Find the index of a script within the scripts array
 * @param nScript			Script number to search for
 * @returns		Index, or -1 if the script is not present
 * @remarks		This function requires the script list to have
 * first been locked with a call to LockScripts()
 */
static int scriptGetOrderFromNum(uint32 nScript) {
	int i;
	LPMPALSCRIPT script = GLOBALS.lpmsScripts;

	for (i = 0; i < GLOBALS.nScripts; i++, script++)
		if (script->nObj == nScript)
			return i;

	return -1;
}


/**
 * Find the index of a dialog within the dialogs array
 * @param nDialog			Dialog number to search for
 * @returns		Index, or -1 if the dialog is not present
 * @remarks		This function requires the dialog list to have
 * first been locked with a call to LockDialogs()
 */
static int dialogGetOrderFromNum(uint32 nDialog) {
	int i;
	LPMPALDIALOG dialog = GLOBALS.lpmdDialogs;

	for (i = 0; i < GLOBALS.nDialogs; i++, dialog++)
		if (dialog->nObj == nDialog)
			return i;

	return -1;
}


/**
 * Duplicates a message
 * @param nMsgOrd			Index of the message inside the messages array
 * @returns		Pointer to the duplicated message.
 * @remarks		Remember to free the duplicated message when done with it.
 */
static char *DuplicateMessage(uint32 nMsgOrd) {
	const char *origmsg;
	char *clonemsg;
	int j;

	if (nMsgOrd == (uint32)-1)
		return NULL;

	origmsg = (const char *)globalLock(GLOBALS.lpmmMsgs[nMsgOrd].hText);

	j = 0;
	while (origmsg[j] != '\0' || origmsg[j + 1] != '\0')
		j++;
	j += 2;

	clonemsg = (char *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, j);
	if (clonemsg == NULL)
		return NULL;

	copyMemory(clonemsg, origmsg, j);
	globalUnlock(GLOBALS.lpmmMsgs[nMsgOrd].hText);

	return clonemsg;
}


/**
 * Duplicate a sentence of a dialog
 * @param nDlgOrd			Index of the dialog in the dialogs array
 * @param nPeriod           Sentence number to be duplicated.
 * @returns		Pointer to the duplicated phrase. Remember to free it
 * when done with it.
 */
static char *duplicateDialogPeriod(uint32 nPeriod) {
	const char *origmsg;
	char *clonemsg;
	LPMPALDIALOG dialog = GLOBALS.lpmdDialogs + GLOBALS.nExecutingDialog;
	int i, j;

	for (j = 0; dialog->_periods[j] != NULL; j++)
		if (dialog->_periodNums[j] == nPeriod) {
			/* Found the phrase, it should be duplicated */
			origmsg = (const char *)globalLock(dialog->_periods[j]);

			/* Calculate the length and allocate memory */
			i = 0;
			while (origmsg[i] != '\0') i++;

			clonemsg = (char *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, i + 1);
			if (clonemsg == NULL)
				return NULL;

			copyMemory(clonemsg, origmsg, i);

			globalUnlock(dialog->_periods[j]);

			return clonemsg;
		}

	return NULL;
}


/**
 * Load a resource from the MPR file
 *
 * @param dwId				ID of the resource to load
 * @returns		Handle to the loaded resource
 */
HGLOBAL resLoad(uint32 dwId) {
	int i;
	HGLOBAL h;
	char head[4];
	uint32 nBytesRead;
	uint32 nSizeComp, nSizeDecomp;
	byte *temp, *buf;

	for (i = 0; i < GLOBALS.nResources; i++)
		if (GLOBALS.lpResources[i * 2] == dwId) {
			GLOBALS.hMpr.seek(GLOBALS.lpResources[i * 2 + 1]);
			nBytesRead = GLOBALS.hMpr.read(head, 4);
			if (nBytesRead != 4)
				return NULL;
			if (head[0] != 'R' || head[1] != 'E' || head[2] != 'S' || head[3] != 'D')
				return NULL;

			nSizeDecomp = GLOBALS.hMpr.readUint32LE();
			if (GLOBALS.hMpr.err())
				return NULL;

			nSizeComp = GLOBALS.hMpr.readUint32LE();
			if (GLOBALS.hMpr.err())
				return NULL;

			h = globalAllocate(GMEM_MOVEABLE | GMEM_ZEROINIT, nSizeDecomp + (nSizeDecomp / 1024) * 16);
			buf = (byte *)globalLock(h);
			temp = (byte *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT,nSizeComp);

			nBytesRead = GLOBALS.hMpr.read(temp, nSizeComp);
			if (nBytesRead != nSizeComp)
				return NULL;

			lzo1x_decompress(temp, nSizeComp, buf, &nBytesRead);
			if (nBytesRead != nSizeDecomp)
				return NULL;

			globalDestroy(temp);
			globalUnlock(h);
			return h;
		}

	return NULL;
}

static uint32 *getSelectList(uint32 i) {
	uint32 *sl;
	int j, k, num;
	LPMPALDIALOG dialog = GLOBALS.lpmdDialogs+GLOBALS.nExecutingDialog;

	/* Count how many are active selects */
	num = 0;
	for (j = 0; dialog->_choice[i]._select[j].dwData != 0; j++)
		if (dialog->_choice[i]._select[j].curActive)
			num++;

	/* If there are 0, it's a mistake */
	if (num == 0)
		return NULL;

	sl= (uint32 *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(uint32) * (num + 1));
	if (sl == NULL)
		return NULL;

	/* Copy all the data inside the active select list */
	k = 0;
	for (j = 0; dialog->_choice[i]._select[j].dwData != 0; j++)
		if (dialog->_choice[i]._select[j].curActive)
			sl[k++] = dialog->_choice[i]._select[j].dwData;

	sl[k] = (uint32)NULL;
	return sl;
}

static uint32 *GetItemList(uint32 nLoc) {
	uint32 *il;
	uint32 num,i,j;
	LPMPALVAR v = GLOBALS.lpmvVars;

	num = 0;
	for (i = 0; i < GLOBALS.nVars; i++, v++) {
		if (strncmp(v->lpszVarName,"Location",8) == 0 && v->dwVal == nLoc)
			num++;
	}

	il = (uint32 *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(uint32) * (num + 1));
	if (il == NULL)
		return NULL;

	v = GLOBALS.lpmvVars;
	j = 0;
	for (i = 0; i < GLOBALS.nVars; i++, v++) {
		if (strncmp(v->lpszVarName, "Location", 8) == 0 && v->dwVal == nLoc) {
			sscanf(v->lpszVarName, "Location.%u", &il[j]);
			j++;
		}
	}

	il[j] = (uint32)NULL;
	return il;
}

static LPITEM getItemData(uint32 nOrdItem) {
	LPMPALITEM curitem = GLOBALS.lpmiItems+nOrdItem;
	LPITEM ret;
	HGLOBAL hDat;
	char *dat;
	int i, j;
	char *patlength;
	uint32 dim;

	// Zeroing out the allocated memory is required!!!
	ret = (LPITEM)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(ITEM));
	if (ret == NULL)
		return NULL;
	ret->speed = 150;

	hDat = resLoad(curitem->dwRes);
	dat = (char *)globalLock(hDat);

	if (dat[0] == 'D' && dat[1] == 'A' && dat[2] == 'T') {
		i = dat[3];			// For version 1.0!!
		dat += 4;

		if (i >= 0x10) {	// From 1.0, there's a destination point for each object
			ret->destX = (int16)READ_LE_UINT16(dat);
			ret->destY = (int16)READ_LE_UINT16(dat + 2);
			dat += 4;
		}

		if (i >= 0x11) {	// From 1.1, there's animation speed
			ret->speed = READ_LE_UINT16(dat);
			dat += 2;
		} else
			ret->speed = 150;
	}

	ret->numframe = *dat++;
	ret->numpattern = *dat++;
	ret->Zvalue = *dat++;

	// Upload the left & top co-ordinates of each frame
	for (i = 0; i < ret->numframe; i++) {
		ret->frameslocations[i].left = (int16)READ_LE_UINT16(dat);
		ret->frameslocations[i].top = (int16)READ_LE_UINT16(dat + 2);
		dat += 4;
	}

	// Upload the size of each frame and calculate the right & bottom
	for (i = 0; i < ret->numframe; i++) {
		ret->frameslocations[i].right = (int16)READ_LE_UINT16(dat) + ret->frameslocations[i].left;
		ret->frameslocations[i].bottom = (int16)READ_LE_UINT16(dat + 2) + ret->frameslocations[i].top;
		dat += 4;
	}

	// Upload the bounding boxes of each frame
	for (i = 0; i < ret->numframe; i++) {
		ret->bbox[i].left = (int16)READ_LE_UINT16(dat);
		ret->bbox[i].top = (int16)READ_LE_UINT16(dat + 2);
		ret->bbox[i].right = (int16)READ_LE_UINT16(dat + 4);
		ret->bbox[i].bottom = (int16)READ_LE_UINT16(dat + 6);
		dat += 8;
	}

	// Load the animation pattern
	patlength = dat;
	dat += ret->numpattern;

	for (i = 1; i < ret->numpattern; i++) {
		for (j = 0; j < patlength[i]; j++)
			ret->pattern[i][j] = dat[j];
		ret->pattern[i][(int)patlength[i]] = 255;   // Terminate pattern
		dat += patlength[i];
	}

	// Upload the individual frames of animations
	for (i = 1; i < ret->numframe; i++) {
		dim = (uint32)(ret->frameslocations[i].right-ret->frameslocations[i].left) *
			(uint32)(ret->frameslocations[i].bottom-ret->frameslocations[i].top);
		ret->frames[i] = (char *)globalAlloc(GMEM_FIXED,dim);
   
		if (ret->frames[i] == NULL)
			return NULL;
		copyMemory(ret->frames[i], dat, dim);
		dat += dim;
	}

	// Check if we've got to the end of the file
	i = READ_LE_UINT16(dat);
	if (i != 0xABCD)
		return NULL;

	globalUnlock(hDat);
	globalFree(hDat);

	return ret;
}


/** 
 * Thread that calls a custom function. It is used in scripts, so that each script
 * function is executed without delaying the others.
 *
 * @param param				pointer to a pointer to the structure that defines the call.
 * @remarks		The passed structure is freed when the process finishes.
 */
void CustomThread(CORO_PARAM, const void *param) {
	CORO_BEGIN_CONTEXT;
		LPCFCALL p;
	CORO_END_CONTEXT(_ctx);

	CORO_BEGIN_CODE(_ctx);

	_ctx->p = *(LPCFCALL *)param;

	CORO_INVOKE_4(GLOBALS.lplpFunctions[_ctx->p->nCf], _ctx->p->arg1, _ctx->p->arg2, _ctx->p->arg3, _ctx->p->arg4);

	globalFree(_ctx->p);

	CORO_END_CODE;
}


/**
 * Main process for running a script.
 *
 * @param param				Pointer to a pointer to a structure containing the script data.
 * @remarks		The passed structure is freed when the process finishes.
 */
void ScriptThread(CORO_PARAM, const void *param) {
	CORO_BEGIN_CONTEXT;
		uint i, j, k;
		uint32 dwStartTime;
		uint32 dwCurTime;
		uint32 dwId;
		int numHandles;
		LPCFCALL p;
	CORO_END_CONTEXT(_ctx);

	static uint32 cfHandles[MAX_COMMANDS_PER_MOMENT];
	LPMPALSCRIPT s = *(const LPMPALSCRIPT *)param;

	CORO_BEGIN_CODE(_ctx);

	_ctx->dwStartTime = _vm->getTime();
	_ctx->numHandles = 0;

// debugC(DEBUG_BASIC, kTonyDebugMPAL, "PlayScript(): Moments: %u\n",s->nMoments);
	for (_ctx->i = 0; _ctx->i < s->nMoments; _ctx->i++) {
		// Sleep for the required time
		if (s->Moment[_ctx->i].dwTime == -1) {
			CORO_INVOKE_4(CoroScheduler.waitForMultipleObjects, _ctx->numHandles, cfHandles, true, CORO_INFINITE);
			_ctx->dwStartTime = _vm->getTime();
		} else {
			_ctx->dwCurTime = _vm->getTime();
			if (_ctx->dwCurTime < _ctx->dwStartTime + (s->Moment[_ctx->i].dwTime * 100)) {
  //     debugC(DEBUG_BASIC, kTonyDebugMPAL, "PlayScript(): Sleeping %lums\n",_ctx->dwStartTime+(s->Moment[_ctx->i].dwTime*100)-_ctx->dwCurTime);
				CORO_INVOKE_1(CoroScheduler.sleep, _ctx->dwStartTime+(s->Moment[_ctx->i].dwTime * 100) - _ctx->dwCurTime);
			}
		}

		_ctx->numHandles = 0;
		for (_ctx->j = 0; _ctx->j < s->Moment[_ctx->i].nCmds; _ctx->j++) {
			_ctx->k = s->Moment[_ctx->i].CmdNum[_ctx->j];

			if (s->_command[_ctx->k].type == 1) {
				_ctx->p = (LPCFCALL)globalAlloc(GMEM_FIXED, sizeof(CFCALL));
				if (_ctx->p == NULL) {
					GLOBALS.mpalError = 1;

					CORO_KILL_SELF();
					return;
				}

				_ctx->p->nCf=s->_command[_ctx->k].nCf;
				_ctx->p->arg1=s->_command[_ctx->k].arg1;
				_ctx->p->arg2=s->_command[_ctx->k].arg2;
				_ctx->p->arg3=s->_command[_ctx->k].arg3;
				_ctx->p->arg4=s->_command[_ctx->k].arg4;

					 // !!! New process management
				if ((cfHandles[_ctx->numHandles++] = CoroScheduler.createProcess(CustomThread, &_ctx->p, sizeof(LPCFCALL))) == 0) {
					GLOBALS.mpalError = 1;

					CORO_KILL_SELF();
					return;
				}
			} else if (s->_command[_ctx->k].type == 2) {
				lockVar();
				varSetValue(
					s->_command[_ctx->k].lpszVarName,
					evaluateExpression(s->_command[_ctx->k].expr)
				);
				unlockVar();

			} else {
				GLOBALS.mpalError = 1;
				globalFree(s);

				CORO_KILL_SELF();
				return;
			}
		}
	}

	globalFree(s);

	CORO_KILL_SELF();

	CORO_END_CODE;
}


/**
 * Thread that performs an action on an item. the thread always executes the action, 
 * so it should create a new item in which the action is the one required.
 * Furthermore, the expression is not checked, but it is always performed the action.
 *
 * @param param				Pointer to a pointer to a structure containing the action.
 */
void ActionThread(CORO_PARAM, const void *param) {
	// COROUTINE
	CORO_BEGIN_CONTEXT;
		int j, k;
	CORO_END_CONTEXT(_ctx);

	const LPMPALITEM item = *(const LPMPALITEM *)param;

	CORO_BEGIN_CODE(_ctx);

	GLOBALS.mpalError = 0;
	for (_ctx->j = 0; _ctx->j < item->Action[item->dwRes].nCmds; _ctx->j++) {
		_ctx->k = item->Action[item->dwRes].CmdNum[_ctx->j];

		if (item->_command[_ctx->k].type == 1) {
			// Custom function
			debugC(DEBUG_DETAILED, kTonyDebugActions, "Action Process %d Call=%s params=%d,%d,%d,%d",
				CoroScheduler.getCurrentPID(), GLOBALS.lplpFunctionStrings[item->_command[_ctx->k].nCf].c_str(),
				item->_command[_ctx->k].arg1, item->_command[_ctx->k].arg2,
				item->_command[_ctx->k].arg3, item->_command[_ctx->k].arg4
			);

			CORO_INVOKE_4(GLOBALS.lplpFunctions[item->_command[_ctx->k].nCf],
				item->_command[_ctx->k].arg1,
				item->_command[_ctx->k].arg2,
				item->_command[_ctx->k].arg3,
				item->_command[_ctx->k].arg4

			);
		} else if (item->_command[_ctx->k].type == 2) {
			// Variable assign
			debugC(DEBUG_DETAILED, kTonyDebugActions, "Action Process %d Variable=%s",
				CoroScheduler.getCurrentPID(), item->_command[_ctx->k].lpszVarName);

			lockVar();
			varSetValue(item->_command[_ctx->k].lpszVarName, evaluateExpression(item->_command[_ctx->k].expr));
			unlockVar();

		} else {
			GLOBALS.mpalError = 1;
			break;
		}
	}

	globalDestroy(item);
	
	debugC(DEBUG_DETAILED, kTonyDebugActions, "Action Process %d ended", CoroScheduler.getCurrentPID());

	CORO_END_CODE;
}

/**
 * This thread monitors a created action to detect when it ends.
 * @remarks		Since actions can spawn sub-actions, this needs to be a
 * separate thread to determine when the outer action is done
 */
void ShutUpActionThread(CORO_PARAM, const void *param) {
	// COROUTINE
	CORO_BEGIN_CONTEXT;
		int slotNumber;
	CORO_END_CONTEXT(_ctx);

	uint32 pid = *(const uint32 *)param;

	CORO_BEGIN_CODE(_ctx);

	CORO_INVOKE_2(CoroScheduler.waitForSingleObject, pid, CORO_INFINITE);

	GLOBALS.bExecutingAction = false;

	if (_vm->_initialLoadSlotNumber != -1) {
		_ctx->slotNumber = _vm->_initialLoadSlotNumber;
		_vm->_initialLoadSlotNumber = -1;

		CORO_INVOKE_1(_vm->loadState, _ctx->slotNumber);
	}


	CORO_END_CODE;
}


/**
 * Polls one location (starting point of a process)
 *
 * @param param				Pointer to an index in the array of polling locations.
 */
void LocationPollThread(CORO_PARAM, const void *param) {
	typedef struct {
		uint32 nItem, nAction;

		uint16 wTime;
		byte perc;
		HGLOBAL when;
		byte nCmds;
		uint16 CmdNum[MAX_COMMANDS_PER_ACTION];

		uint32 dwLastTime;
	} MYACTION;

	typedef struct {
		uint32 nItem;
		uint32 hThread;
	} MYTHREAD;

	CORO_BEGIN_CONTEXT;
		uint32 *il;
		int i, j, k;
		int numitems;
		int nRealItems;
		LPMPALITEM curItem,newItem;
		int nIdleActions;
		uint32 curTime;
		uint32 dwSleepTime;
		uint32 dwId;
		int ord;
		bool delayExpired;
		bool expired;

		MYACTION *MyActions;
		MYTHREAD *MyThreads;
	CORO_END_CONTEXT(_ctx);

	uint32 id = *((const uint32 *)param);

	CORO_BEGIN_CODE(_ctx);

	/* To begin with, we need to request the item list from the location */
	_ctx->il = mpalQueryItemList(GLOBALS.nPollingLocations[id]);

	/* Count the items */
	for (_ctx->numitems = 0; _ctx->il[_ctx->numitems] != 0; _ctx->numitems++)
		;

	/* We look for items without idle actions, and eliminate them from the list */
	lockItems();
	_ctx->nIdleActions = 0;
	_ctx->nRealItems = 0;
	for (_ctx->i = 0; _ctx->i < _ctx->numitems; _ctx->i++) {
		_ctx->ord = itemGetOrderFromNum(_ctx->il[_ctx->i]);

		if (_ctx->ord == -1) continue;
	 
		_ctx->curItem = GLOBALS.lpmiItems + _ctx->ord;

		_ctx->k = 0;
		for (_ctx->j = 0; _ctx->j < _ctx->curItem->nActions; _ctx->j++)
			if (_ctx->curItem->Action[_ctx->j].num == 0xFF)
				_ctx->k++;

		_ctx->nIdleActions += _ctx->k;

		if (_ctx->k == 0)
			/* We can remove this item from the list */
			_ctx->il[_ctx->i] = (uint32)NULL;
		else
			_ctx->nRealItems++;
	}
	unlockItems();

	/* If there is nothing left, we can exit */
	if (_ctx->nRealItems == 0) {
		globalDestroy(_ctx->il);
		CORO_KILL_SELF();
		return;
	}

	_ctx->MyThreads = (MYTHREAD *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, _ctx->nRealItems * sizeof(MYTHREAD));
	if (_ctx->MyThreads == NULL) {
		globalDestroy(_ctx->il);
		CORO_KILL_SELF();
		return;
	}


	/* We have established that there is at least one item that contains idle actions.
	   Now we created the mirrored copies of the idle actions. */
	_ctx->MyActions = (MYACTION *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, _ctx->nIdleActions * sizeof(MYACTION));
	if (_ctx->MyActions == NULL) {
		globalDestroy(_ctx->MyThreads);
		globalDestroy(_ctx->il);
		CORO_KILL_SELF();
		return;
	}

	lockItems();
	_ctx->k = 0;

	for (_ctx->i = 0; _ctx->i < _ctx->numitems; _ctx->i++) {
		if (_ctx->il[_ctx->i] == 0)
			continue;

		_ctx->curItem = GLOBALS.lpmiItems + itemGetOrderFromNum(_ctx->il[_ctx->i]);

		for (_ctx->j = 0; _ctx->j < _ctx->curItem->nActions; _ctx->j++)
			if (_ctx->curItem->Action[_ctx->j].num == 0xFF) {
				_ctx->MyActions[_ctx->k].nItem = _ctx->il[_ctx->i];
				_ctx->MyActions[_ctx->k].nAction = _ctx->j;

				_ctx->MyActions[_ctx->k].wTime = _ctx->curItem->Action[_ctx->j].wTime;
				_ctx->MyActions[_ctx->k].perc = _ctx->curItem->Action[_ctx->j].perc;
				_ctx->MyActions[_ctx->k].when = _ctx->curItem->Action[_ctx->j].when;
				_ctx->MyActions[_ctx->k].nCmds = _ctx->curItem->Action[_ctx->j].nCmds;
				copyMemory(_ctx->MyActions[_ctx->k].CmdNum, _ctx->curItem->Action[_ctx->j].CmdNum,
				MAX_COMMANDS_PER_ACTION * sizeof(uint16));

				_ctx->MyActions[_ctx->k].dwLastTime = _vm->getTime();
				_ctx->k++;
			}
	}

	unlockItems();

	/* We don't need the item list anymore */
	globalDestroy(_ctx->il);


	/* Here's the main loop */
	while (1) {
		/* Cerchiamo tra tutte le idle actions quella a cui manca meno tempo per
			l'esecuzione */
		_ctx->curTime = _vm->getTime();
		_ctx->dwSleepTime = (uint32)-1L;

		for (_ctx->k = 0;_ctx->k<_ctx->nIdleActions;_ctx->k++)
			if (_ctx->curTime >= _ctx->MyActions[_ctx->k].dwLastTime + _ctx->MyActions[_ctx->k].wTime) {
				_ctx->dwSleepTime = 0;
				break;
		     } else
				_ctx->dwSleepTime = MIN(_ctx->dwSleepTime, _ctx->MyActions[_ctx->k].dwLastTime + _ctx->MyActions[_ctx->k].wTime - _ctx->curTime);

		/* We fall alseep, but always checking that the event is set when prompted for closure */
		CORO_INVOKE_3(CoroScheduler.waitForSingleObject, GLOBALS.hEndPollingLocations[id], _ctx->dwSleepTime, &_ctx->expired);

		//if (_ctx->k == WAIT_OBJECT_0)
		if (!_ctx->expired)
			break;

		for (_ctx->i = 0; _ctx->i < _ctx->nRealItems; _ctx->i++)
			if (_ctx->MyThreads[_ctx->i].nItem != 0) {
				CORO_INVOKE_3(CoroScheduler.waitForSingleObject, _ctx->MyThreads[_ctx->i].hThread, 0, &_ctx->delayExpired);

				// if result == WAIT_OBJECT_0)
				if (!_ctx->delayExpired)
					_ctx->MyThreads[_ctx->i].nItem = 0;
			}

		_ctx->curTime = _vm->getTime();

		/* Loop through all the necessary idle actions */
		for (_ctx->k = 0; _ctx->k < _ctx->nIdleActions; _ctx->k++)
			if (_ctx->curTime >= _ctx->MyActions[_ctx->k].dwLastTime + _ctx->MyActions[_ctx->k].wTime) {
				_ctx->MyActions[_ctx->k].dwLastTime += _ctx->MyActions[_ctx->k].wTime;

			   /* It's time to check to see if fortune is on the side of the idle action */
				byte randomVal = (byte)_vm->_randomSource.getRandomNumber(99);
				if (randomVal < _ctx->MyActions[_ctx->k].perc) {
					/* Check if there is an action running on the item */
					if ((GLOBALS.bExecutingAction) && (GLOBALS.nExecutingAction == _ctx->MyActions[_ctx->k].nItem))
						continue;

					/* Check to see if there already another idle funning running on the item */
					for (_ctx->i = 0; _ctx->i < _ctx->nRealItems; _ctx->i++)
						if (_ctx->MyThreads[_ctx->i].nItem == _ctx->MyActions[_ctx->k].nItem)
							break;

					if (_ctx->i < _ctx->nRealItems)
						continue;

					/* Ok, we are the only ones :) */
					lockItems();
					_ctx->curItem=GLOBALS.lpmiItems+itemGetOrderFromNum(_ctx->MyActions[_ctx->k].nItem);

					/* Check if there is a WhenExecute expression */
					_ctx->j=_ctx->MyActions[_ctx->k].nAction;
					if (_ctx->curItem->Action[_ctx->j].when != NULL)
						if (!evaluateExpression(_ctx->curItem->Action[_ctx->j].when)) {
							unlockItems();
							continue;
						}

					/* Ok, we can perform the action. For convenience, we do it in a new process */
					_ctx->newItem = (LPMPALITEM)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(MPALITEM));
					if (_ctx->newItem == false) {
						globalDestroy(_ctx->MyThreads);
						globalDestroy(_ctx->MyActions);
						
						CORO_KILL_SELF();
						return;
					}

					copyMemory(_ctx->newItem,_ctx->curItem, sizeof(MPALITEM));
					unlockItems();

					/* We copy the action in #0 */
//					_ctx->newItem->Action[0].nCmds = _ctx->curItem->Action[_ctx->j].nCmds;
//					copyMemory(_ctx->newItem->Action[0].CmdNum,_ctx->curItem->Action[_ctx->j].CmdNum,_ctx->newItem->Action[0].nCmds*sizeof(_ctx->newItem->Action[0].CmdNum[0]));
					_ctx->newItem->dwRes=_ctx->j;

					/* We will create an action, and will provide the necessary details */
					for (_ctx->i = 0; _ctx->i < _ctx->nRealItems; _ctx->i++)
						if (_ctx->MyThreads[_ctx->i].nItem == 0)
							break;

					_ctx->MyThreads[_ctx->i].nItem = _ctx->MyActions[_ctx->k].nItem;

					// Create the process
					if ((_ctx->MyThreads[_ctx->i].hThread = CoroScheduler.createProcess(ActionThread, &_ctx->newItem, sizeof(LPMPALITEM))) == CORO_INVALID_PID_VALUE) {
					//if ((_ctx->MyThreads[_ctx->i].hThread = (void*)_beginthread(ActionThread, 10240,(void *)_ctx->newItem))= = (void*)-1)
						globalDestroy(_ctx->newItem);
						globalDestroy(_ctx->MyThreads);
						globalDestroy(_ctx->MyActions);
						
						CORO_KILL_SELF();
						return;
					}

					/* Skip all idle actions of the same item */
				}
			}
	}


	// Set idle skip on
	CORO_INVOKE_4(GLOBALS.lplpFunctions[200], 0, 0, 0, 0);

	for (_ctx->i = 0; _ctx->i < _ctx->nRealItems; _ctx->i++)
		if (_ctx->MyThreads[_ctx->i].nItem != 0) {
			CORO_INVOKE_3(CoroScheduler.waitForSingleObject, _ctx->MyThreads[_ctx->i].hThread, 5000, &_ctx->delayExpired);

/*
			//if (result != WAIT_OBJECT_0)
			if (_ctx->delayExpired)
				TerminateThread(_ctx->MyThreads[_ctx->i].hThread, 0);
*/
			CoroScheduler.killMatchingProcess(_ctx->MyThreads[_ctx->i].hThread);
		}

	// Set idle skip off
	CORO_INVOKE_4(GLOBALS.lplpFunctions[201], 0, 0, 0, 0);

	/* We're finished */
	globalDestroy(_ctx->MyThreads);
	globalDestroy(_ctx->MyActions);
	
	CORO_KILL_SELF();

	CORO_END_CODE;
}


/**
 * Wait for the end of the dialog execution thread, and then restore global 
 * variables indicating that the dialogue has finished.
 *
 * @param param				Pointer to a handle to the dialog 
 * @remarks		This additional process is used, instead of clearing variables
 * within the same dialog thread, because due to the recursive nature of a dialog,
 * it would be difficult to know within it when the dialog is actually ending.
 */
void ShutUpDialogThread(CORO_PARAM, const void *param) {
	CORO_BEGIN_CONTEXT;
	CORO_END_CONTEXT(_ctx);

	uint32 pid = *(const uint32 *)param;

	CORO_BEGIN_CODE(_ctx);

	CORO_INVOKE_2(CoroScheduler.waitForSingleObject, pid, CORO_INFINITE);

	GLOBALS.bExecutingDialog = false;
	GLOBALS.nExecutingDialog = 0;
	GLOBALS.nExecutingChoice = 0;

	CoroScheduler.setEvent(GLOBALS.hAskChoice);

	CORO_KILL_SELF();

	CORO_END_CODE;
}

void doChoice(CORO_PARAM, uint32 nChoice);


/**
 * Executes a group of the current dialog. Can 'be the Starting point of a process.
 * @parm nGroup				Number of the group to perform
 */
void GroupThread(CORO_PARAM, const void *param) {
	CORO_BEGIN_CONTEXT;
		LPMPALDIALOG dialog;
		int i, j, k;
		int type;
	CORO_END_CONTEXT(_ctx);

	uint32 nGroup = *(const uint32 *)param;

	CORO_BEGIN_CODE(_ctx);

	// Lock the _ctx->dialog
	lockDialogs();

	// Find the pointer to the current _ctx->dialog
	_ctx->dialog = GLOBALS.lpmdDialogs + GLOBALS.nExecutingDialog;

	// Search inside the group requesting the _ctx->dialog
	for (_ctx->i = 0; _ctx->dialog->_group[_ctx->i].num != 0; _ctx->i++) {
		if (_ctx->dialog->_group[_ctx->i].num == nGroup) {
			// Cycle through executing the commands of the group
			for (_ctx->j = 0; _ctx->j < _ctx->dialog->_group[_ctx->i].nCmds; _ctx->j++) {
				_ctx->k = _ctx->dialog->_group[_ctx->i].CmdNum[_ctx->j];

				_ctx->type = _ctx->dialog->_command[_ctx->k].type;
				if (_ctx->type == 1) {
					// Call custom function
					CORO_INVOKE_4(GLOBALS.lplpFunctions[_ctx->dialog->_command[_ctx->k].nCf],
						_ctx->dialog->_command[_ctx->k].arg1, 
						_ctx->dialog->_command[_ctx->k].arg2,
						_ctx->dialog->_command[_ctx->k].arg3, 
						_ctx->dialog->_command[_ctx->k].arg4
					);

				} else if (_ctx->type == 2) {
					// Set a variable
					lockVar();
					varSetValue(_ctx->dialog->_command[_ctx->k].lpszVarName, evaluateExpression(_ctx->dialog->_command[_ctx->k].expr));
					unlockVar();
					
				} else if (_ctx->type == 3) {
					// DoChoice: call the chosen function
					CORO_INVOKE_1(doChoice, (uint32)_ctx->dialog->_command[_ctx->k].nChoice);
					
				} else {
					GLOBALS.mpalError = 1;
					unlockDialogs();
					
					CORO_KILL_SELF();
					return;
				}
			}

			/* The gruop is finished, so we can return to the calling function.
			 * If the group was the first called, then the process will automatically 
			 * end. Otherwise it returns to the caller method
			 */
			return;
		}
	}

	/* If we are here, it means that we have not found the requested group */
	GLOBALS.mpalError = 1;
	unlockDialogs();
	
	CORO_KILL_SELF();

	CORO_END_CODE;
}


/**
 * Make a choice in the current dialog.
 *
 * @param nChoice			Number of choice to perform
 */
void doChoice(CORO_PARAM, uint32 nChoice) {
	CORO_BEGIN_CONTEXT;
		LPMPALDIALOG dialog;
		int i, j, k;
		uint32 nGroup;
	CORO_END_CONTEXT(_ctx);

	CORO_BEGIN_CODE(_ctx);

	/* Lock the dialogs */
	lockDialogs();

	/* Get a pointer to the current dialog */
	_ctx->dialog = GLOBALS.lpmdDialogs + GLOBALS.nExecutingDialog;

	/* Search the choice between those required in the dialog */
	for (_ctx->i = 0; _ctx->dialog->_choice[_ctx->i].nChoice != 0; _ctx->i++)
		if (_ctx->dialog->_choice[_ctx->i].nChoice == nChoice)
			break;

	/* If nothing has been found, exit with an error */
	if (_ctx->dialog->_choice[_ctx->i].nChoice == 0) {
		/* If we're here, we did not find the required choice */
		GLOBALS.mpalError = 1;
		unlockDialogs();

		CORO_KILL_SELF();
		return;
	}

	/* We've found the requested choice. Remember what in global variables */
	GLOBALS.nExecutingChoice = _ctx->i;

	while (1) {
		GLOBALS.nExecutingChoice = _ctx->i;

		_ctx->k = 0;
		/* Calculate the expression of each selection, to see if they're active or inactive */
		for (_ctx->j = 0; _ctx->dialog->_choice[_ctx->i]._select[_ctx->j].dwData != 0; _ctx->j++)
			if (_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].when == NULL) {
				_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].curActive = 1;
				_ctx->k++;
			} else if (evaluateExpression(_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].when)) {
				_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].curActive = 1;
				_ctx->k++;
			} else
				_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].curActive = 0;

		/* If there are no choices activated, then the dialog is finished. */
		if (_ctx->k == 0) {
			unlockDialogs();
			break;
		}

		/* There are choices available to the user, so wait for them to make one */
		CoroScheduler.resetEvent(GLOBALS.hDoneChoice);
		CoroScheduler.setEvent(GLOBALS.hAskChoice);
		CORO_INVOKE_2(CoroScheduler.waitForSingleObject, GLOBALS.hDoneChoice, CORO_INFINITE);

		/* Now that the choice has been made, we can run the groups associated with the choice tbontbtitq
		*/
		_ctx->j = GLOBALS.nSelectedChoice;
		for (_ctx->k = 0; _ctx->dialog->_choice[_ctx->i]._select[_ctx->j].wPlayGroup[_ctx->k] != 0; _ctx->k++) {
			_ctx->nGroup = _ctx->dialog->_choice[_ctx->i]._select[_ctx->j].wPlayGroup[_ctx->k];
			CORO_INVOKE_1(GroupThread, &_ctx->nGroup);
		}

		/* Control attribute */
		if (_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].attr & (1 << 0)) {
			/* Bit 0 set: the end of the choice */
			unlockDialogs();
			break;
		}

		if (_ctx->dialog->_choice[_ctx->i]._select[_ctx->j].attr & (1 << 1)) {
			/* Bit 1 set: the end of the dialog */
			unlockDialogs();
			
			CORO_KILL_SELF();
			return;
		}

		/* End of choic ewithout attributes. We must do it again */
	}

	// If we're here, we found an end choice. Return to the caller group
	return;

	CORO_END_CODE;
}


/**
 * Perform an action on a certain item.
 *
 * @param nAction			Action number
 * @param ordItem           Index of the item in the items list
 * @param dwParam			Any parameter for the action.
 * @returns		Id of the process that was launched to perform the action, or
 * CORO_INVALID_PID_VALUE if the action was not defined, or the item was inactive.
 * @remarks		You can get the index of an item from its number by using
 * the itemGetOrderFromNum() function. The items list must first be locked
 * by calling LockItem().
 */
static uint32 doAction(uint32 nAction, uint32 ordItem, uint32 dwParam) {
	LPMPALITEM item = GLOBALS.lpmiItems;
	int i;
	LPMPALITEM newitem;
	uint32 h;

	item+=ordItem;
	Common::String buf = Common::String::format("Status.%u", item->nObj);
	if (varGetValue(buf.c_str()) <= 0)
		return CORO_INVALID_PID_VALUE;

	for (i = 0; i < item->nActions; i++) {
		if (item->Action[i].num != nAction)
			continue;

		if (item->Action[i].wParm != dwParam)
			continue;

		if (item->Action[i].when != NULL) {
			if (!evaluateExpression(item->Action[i].when))
				continue;
		}

		// Now we find the right action to be performed
		// Duplicate the item and copy the current action in #i into #0
		newitem = (LPMPALITEM)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(MPALITEM));
		if (newitem == NULL)
			return CORO_INVALID_PID_VALUE;

		// In the new version number of the action in writing dwRes
		Common::copy((byte *)item, (byte *)item + sizeof(MPALITEM), (byte *)newitem);
/*   newitem->Action[0].nCmds=item->Action[i].nCmds;
   copyMemory(newitem->Action[0].CmdNum,item->Action[i].CmdNum,newitem->Action[0].nCmds*sizeof(newitem->Action[0].CmdNum[0]));
*/
		newitem->dwRes = i;

		// And finally we can laucnh the process that will execute the action,
		// and a second process to free up the memory when the action is finished.

		// !!! New process management
		if ((h = CoroScheduler.createProcess(ActionThread, &newitem, sizeof(LPMPALITEM))) == CORO_INVALID_PID_VALUE)
			return CORO_INVALID_PID_VALUE;

		if (CoroScheduler.createProcess(ShutUpActionThread, &h, sizeof(uint32)) == CORO_INVALID_PID_VALUE)
			return CORO_INVALID_PID_VALUE;

		GLOBALS.nExecutingAction = item->nObj;
		GLOBALS.bExecutingAction = true;

		return h;
	}

	return CORO_INVALID_PID_VALUE;
}

/**
 * Shows a dialog in a separate process.
 *
 * @param nDlgOrd				The index of the dialog in the dialog list
 * @param nGroup				Number of the group to perform
 * @returns						The process Id of the process running the dialog
 *								or CORO_INVALID_PID_VALUE on error
 * @remarks						The dialogue runs in a thread created on purpose, 
 * so that must inform through an event and when 'necessary to you make a choice. 
 * The data on the choices may be obtained through various queries.
 */
static uint32 doDialog(uint32 nDlgOrd, uint32 nGroup) {
	uint32 h;

	// Store the running dialog in a global variable
	GLOBALS.nExecutingDialog = nDlgOrd;

	// Enables the flag to indicate that there is' a running dialogue
	GLOBALS.bExecutingDialog = true;

	CoroScheduler.resetEvent(GLOBALS.hAskChoice);
	CoroScheduler.resetEvent(GLOBALS.hDoneChoice);

	// Create a thread that performs the dialogue group

	// Create the process
	if ((h = CoroScheduler.createProcess(GroupThread, &nGroup, sizeof(uint32))) == CORO_INVALID_PID_VALUE)
		return CORO_INVALID_PID_VALUE;

	// Create a thread that waits until the end of the dialog process, and will restore the global variables
	if (CoroScheduler.createProcess(ShutUpDialogThread, &h, sizeof(uint32)) == CORO_INVALID_PID_VALUE) {
		// Something went wrong, so kill the previously started dialog process
		CoroScheduler.killMatchingProcess(h);
		return CORO_INVALID_PID_VALUE;
	}

	return h;
}


/**
 * Takes note of the selection chosen by the user, and warns the process that was running 
 * the box that it can continue.
 *
 * @param nChoice           Number of choice that was in progress
 * @param dwData			Since combined with select selection
 * @returns		True if everything is OK, false on failure
 */
bool doSelection(uint32 i, uint32 dwData) {
	LPMPALDIALOG dialog = GLOBALS.lpmdDialogs+GLOBALS.nExecutingDialog;
	int j;

	for (j = 0; dialog->_choice[i]._select[j].dwData != 0; j++)
		if (dialog->_choice[i]._select[j].dwData == dwData && dialog->_choice[i]._select[j].curActive != 0)
			break;

	if (dialog->_choice[i]._select[j].dwData == 0)
		return false;

	GLOBALS.nSelectedChoice = j;
	CoroScheduler.setEvent(GLOBALS.hDoneChoice);
	return true;
}


/**
 * @defgroup Exported functions
 */

/**
 * Initialises the MPAL library and opens the .MPC file, which will be used for all queries.
 *
 * @param lpszMpcFileName   Name of the MPC file
 * @param lpszMprFileName   Name of the MPR file
 * @param lplpcfArray		Array of pointers to custom functions.
 * @returns		True if everything is OK, false on failure
 */
bool mpalInit(const char *lpszMpcFileName, const char *lpszMprFileName, 
			  LPLPCUSTOMFUNCTION lplpcfArray, Common::String *lpcfStrings) {
	Common::File hMpc;
	byte buf[5];
	uint32 nBytesRead;
	bool bCompress;
	uint32 dwSizeDecomp, dwSizeComp;
	byte *cmpbuf;

 //printf("Item: %lu\n", sizeof(MPALITEM));
 //printf("Script: %lu\n", sizeof(MPALSCRIPT));
 //printf("Dialog: %lu\n", sizeof(MPALDIALOG));

	/* Save the array of custom functions */
	GLOBALS.lplpFunctions = lplpcfArray;
	GLOBALS.lplpFunctionStrings = lpcfStrings;

	/* OPen the MPC file for reading */
	if (!hMpc.open(lpszMpcFileName))
		return false;

	/* Read and check the header */
	nBytesRead = hMpc.read(buf, 5);
	if (nBytesRead != 5)
		return false;

	if (buf[0] != 'M' || buf[1] != 'P' || buf[2] != 'C' || buf[3] != 0x20)
		return false;

	bCompress = buf[4];

	/* Reads the size of the uncompressed file, and allocate memory */
	dwSizeDecomp = hMpc.readUint32LE();
	if (hMpc.err())
		return false;

	byte *lpMpcImage = (byte *)globalAlloc(GMEM_FIXED, dwSizeDecomp + 16);
	if (lpMpcImage == NULL)
		return false;

	if (bCompress) {
		/* Get the compressed size and read the data in */
		dwSizeComp = hMpc.readUint32LE();
		if (hMpc.err())
			return false;

		cmpbuf = (byte *)globalAlloc(GMEM_FIXED, dwSizeComp);
		if (cmpbuf == NULL)
			return false;

		nBytesRead = hMpc.read(cmpbuf, dwSizeComp);
		if (nBytesRead != dwSizeComp)
			return false;

		/* Decompress the data */
		lzo1x_decompress(cmpbuf, dwSizeComp, lpMpcImage, &nBytesRead);
		if (nBytesRead != dwSizeDecomp)
			return false;

		globalDestroy(cmpbuf);
	} else {
		/* If the file is not compressed, we directly read in the data */
		nBytesRead = hMpc.read(lpMpcImage, dwSizeDecomp);
		if (nBytesRead != dwSizeDecomp)
			return false;
	}

	/* Close the file */
	hMpc.close();

	/* Process the data */
	if (ParseMpc(lpMpcImage) == false)
		return false;

	globalDestroy(lpMpcImage);

	/* Calculate memory usage */
	/*
 {
	 char errbuf[256];
	 wsprintf(errbuf,"Utilizzo in RAM: VAR %lu, MSG %lu, DLG %lu, ITM %lu, LOC %lu, SCR %lu",
	   GLOBALS.nVars*sizeof(MPALVAR),
		 GLOBALS.nMsgs*sizeof(MPALMSG),
		 GLOBALS.nDialogs*sizeof(MPALDIALOG),
		 GLOBALS.nItems*sizeof(MPALITEM),
		 GLOBALS.nLocations*sizeof(MPALLOCATION),
		 GLOBALS.nScripts*sizeof(MPALSCRIPT));
	 MessageBox(NULL,errbuf,"Dump",MB_OK);
 }
*/

	/* Open the MPR file */
	if (!GLOBALS.hMpr.open(lpszMprFileName))
		return false;

	/* Seek to the end of the file to read overall information */
	GLOBALS.hMpr.seek(-12, SEEK_END);

	dwSizeComp = GLOBALS.hMpr.readUint32LE();
	if (GLOBALS.hMpr.err())
		return false;

	GLOBALS.nResources = GLOBALS.hMpr.readUint32LE();
	if (GLOBALS.hMpr.err())
		return false;

	nBytesRead = GLOBALS.hMpr.read(buf, 4);
	if (GLOBALS.hMpr.err())
		return false;

	if (buf[0] !='E' || buf[1] != 'N' || buf[2] != 'D' || buf[3] != '0')
		return false;

	/* Move to the start of the resources header */
	GLOBALS.hMpr.seek(-(12 + (int)dwSizeComp), SEEK_END);

	GLOBALS.lpResources = (uint32 *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, GLOBALS.nResources * 8);
	if (GLOBALS.lpResources == NULL)
		return false;

	cmpbuf = (byte *)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, dwSizeComp);
	if (cmpbuf == NULL)
		return false;

	nBytesRead = GLOBALS.hMpr.read(cmpbuf, dwSizeComp);
	if (nBytesRead != dwSizeComp)
		return false;

	lzo1x_decompress((const byte *)cmpbuf, dwSizeComp, (byte *)GLOBALS.lpResources, (uint32 *)&nBytesRead);
	if (nBytesRead != (uint32)GLOBALS.nResources * 8)
		return false;

	globalDestroy(cmpbuf);

	/* Reset back to the start of the file, leaving it open */
	GLOBALS.hMpr.seek(0, SEEK_SET);

	/* There is no action or dialog running by default */
	GLOBALS.bExecutingAction = false;
	GLOBALS.bExecutingDialog = false;

	/* There's no polling location */
	Common::fill(GLOBALS.nPollingLocations, GLOBALS.nPollingLocations + MAXPOLLINGLOCATIONS, 0);

	/* Create the event that will be used to co-ordinate making choices and choices finishing */
	GLOBALS.hAskChoice = CoroScheduler.createEvent(true, false);
	GLOBALS.hDoneChoice = CoroScheduler.createEvent(true, false);

	return true;
}

/**
 * Frees resources allocated by the MPAL subsystem
 */
void mpalFree() {
	// Free the resource list
	globalDestroy(GLOBALS.lpResources);
}

/**
 * This is a general function to communicate with the library, to request information
 * about what is in the .MPC file
 *
 * @param wQueryType		Type of query. The list is in the QueryTypes enum.
 * @returns		4 bytes depending on the type of query
 * @remarks		This is the specialised version of the original single mpalQuery
 * method that returns numeric results.
 */
uint32 mpalQueryDWORD(uint16 wQueryType, ...) {
	int x, y, z;
	Common::String buf;
	uint32 dwRet = 0;
	char *n;

	va_list v;
	va_start(v, wQueryType);

	GLOBALS.mpalError = OK;

	if (wQueryType == MPQ_VERSION) {

		/*
		 *  uint32 mpalQuery(MPQ_VERSION);
		 */
		dwRet = HEX_VERSION;

	} else if (wQueryType == MPQ_GLOBAL_VAR) {
		/*
		 *  uint32 mpalQuery(MPQ_GLOBAL_VAR, char * lpszVarName);
		 */
		lockVar();
		dwRet = (uint32)varGetValue(GETARG(char *));
		unlockVar();

	} else if (wQueryType == MPQ_MESSAGE) {
		/*
		 *  char * mpalQuery(MPQ_MESSAGE, uint32 nMsg);
		 */
		error("mpalQuery(MPQ_MESSAGE, uint32 nMsg) used incorrect method variant");

		
	} else if (wQueryType == MPQ_ITEM_PATTERN) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_PATTERN, uint32 nItem);
		 */
		lockVar();
		buf = Common::String::format("Pattern.%u", GETARG(uint32));
		dwRet = (uint32)varGetValue(buf.c_str());
		unlockVar();
		
	} else if (wQueryType == MPQ_LOCATION_SIZE) {
		/*
		 *  uint32 mpalQuery(MPQ_LOCATION_SIZE, uint32 nLoc, uint32 dwCoord);
		 */
		lockLocations();
		x = locGetOrderFromNum(GETARG(uint32));
		y = GETARG(uint32);
		if (x != -1) {
			if (y == MPQ_X)
				dwRet = GLOBALS.lpmlLocations[x].dwXlen;
			else if (y == MPQ_Y)
				dwRet = GLOBALS.lpmlLocations[x].dwYlen;
			else
				GLOBALS.mpalError = 1;
		} else
			GLOBALS.mpalError = 1;

		unlockLocations();
		
	} else if (wQueryType == MPQ_LOCATION_IMAGE) {
		/*
		 *  HGLOBAL mpalQuery(MPQ_LOCATION_IMAGE, uint32 nLoc);
		 */
		error("mpalQuery(MPQ_LOCATION_IMAGE, uint32 nLoc) used incorrect variant");

	} else if (wQueryType == MPQ_RESOURCE) {
		/*
		 *  HGLOBAL mpalQuery(MPQ_RESOURCE, uint32 dwRes);
		 */
		error("mpalQuery(MPQ_RESOURCE, uint32 dwRes) used incorrect variant");

	} else if (wQueryType == MPQ_ITEM_LIST) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_LIST, uint32 nLoc);
		 */
		error("mpalQuery(MPQ_ITEM_LIST, uint32 nLoc) used incorrect variant");

	} else if (wQueryType == MPQ_ITEM_DATA) {
		/*
		 *  LPITEM mpalQuery(MPQ_ITEM_DATA, uint32 nItem);
		 */
		error("mpalQuery(MPQ_ITEM_DATA, uint32 nItem) used incorrect variant");

	} else if (wQueryType == MPQ_ITEM_IS_ACTIVE) {
		/*
		 *  bool mpalQuery(MPQ_ITEM_IS_ACTIVE, uint32 nItem);
		 */
		lockVar();
		x = GETARG(uint32);
		buf = Common::String::format("Status.%u", x);
		if (varGetValue(buf.c_str()) <= 0)
			dwRet = (uint32)false;
		else
			dwRet = (uint32)true;

		unlockVar();

	} else if (wQueryType == MPQ_ITEM_NAME) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_NAME, uint32 nItem, char * lpszName);
		 */
		lockVar();
		x = GETARG(uint32);
		n = GETARG(char *);
		buf = Common::String::format("Status.%u", x);
		if (varGetValue(buf.c_str()) <= 0)
			n[0]='\0';
		else {
			lockItems();
			y = itemGetOrderFromNum(x);
			copyMemory(n, (char *)(GLOBALS.lpmiItems + y)->lpszDescribe, MAX_DESCRIBE_SIZE);
			unlockItems();
		}

		unlockVar();

	} else if (wQueryType == MPQ_DIALOG_PERIOD) {
		/*
		 *  char *mpalQuery(MPQ_DIALOG_PERIOD, uint32 nDialog, uint32 nPeriod);
		 */
		error("mpalQuery(MPQ_DIALOG_PERIOD, uint32 nDialog, uint32 nPeriod) used incorrect variant");

	} else if (wQueryType == MPQ_DIALOG_WAITFORCHOICE) {
		/*
		 *  void mpalQuery(MPQ_DIALOG_WAITFORCHOICE);
		 */
		error("mpalQuery(MPQ_DIALOG_WAITFORCHOICE) used incorrect variant");

	} else if (wQueryType == MPQ_DIALOG_SELECTLIST) {
		/*
		 *  uint32 *mpalQuery(MPQ_DIALOG_SELECTLIST, uint32 nChoice);
		 */
		error("mpalQuery(MPQ_DIALOG_SELECTLIST, uint32 nChoice) used incorrect variant");

	} else if (wQueryType == MPQ_DIALOG_SELECTION) {
		/*
		 *  bool mpalQuery(MPQ_DIALOG_SELECTION, uint32 nChoice, uint32 dwData);
		 */
		lockDialogs();
		x = GETARG(uint32);
		y = GETARG(uint32);
		dwRet = (uint32)doSelection(x, y);

		unlockDialogs();

	} else if (wQueryType == MPQ_DO_ACTION) {
		/*
		 *  int mpalQuery(MPQ_DO_ACTION, uint32 nAction, uint32 nItem, uint32 dwParam);
		 */
		lockItems();
		lockVar();
		x = GETARG(uint32);
		z = GETARG(uint32);
		y = itemGetOrderFromNum(z);
		if (y != -1) {
			dwRet = doAction(x, y, GETARG(uint32));
		} else {
			dwRet = CORO_INVALID_PID_VALUE;
			GLOBALS.mpalError = 1;
		}

		unlockVar();
		unlockItems();

	} else if (wQueryType == MPQ_DO_DIALOG) {
		/*
		 *  int mpalQuery(MPQ_DO_DIALOG, uint32 nDialog, uint32 nGroup);
		 */
		if (!GLOBALS.bExecutingDialog) {
			lockDialogs();

			x = dialogGetOrderFromNum(GETARG(uint32));
			y = GETARG(uint32);
			dwRet = doDialog(x, y);
			unlockDialogs();
		}
	} else {
		/*
		 *  DEFAULT -> ERROR
		 */
		GLOBALS.mpalError = 1;
	}

	va_end(v);
	return dwRet;
}

/**
 * This is a general function to communicate with the library, to request information
 * about what is in the .MPC file
 *
 * @param wQueryType		Type of query. The list is in the QueryTypes enum.
 * @returns		4 bytes depending on the type of query
 * @remarks		This is the specialised version of the original single mpalQuery
 * method that returns a pointer or handle.
 */
HANDLE mpalQueryHANDLE(uint16 wQueryType, ...) {
	int x, y;
	char *n;
	Common::String buf;
	va_list v;
	va_start(v, wQueryType);
	void *hRet = NULL;

	GLOBALS.mpalError = OK;

	if (wQueryType == MPQ_VERSION) {
		/*
		 *  uint32 mpalQuery(MPQ_VERSION);
		 */
		error("mpalQuery(MPQ_VERSION) used incorrect variant");

	} else if (wQueryType == MPQ_GLOBAL_VAR) {
		/*
		 *  uint32 mpalQuery(MPQ_GLOBAL_VAR, char * lpszVarName);
		 */
		error("mpalQuery(MPQ_GLOBAL_VAR, char * lpszVarName) used incorrect variant");

	} else if (wQueryType == MPQ_MESSAGE) {
		/*
		 *  char * mpalQuery(MPQ_MESSAGE, uint32 nMsg);
		 */
		LockMsg();
		hRet = DuplicateMessage(msgGetOrderFromNum(GETARG(uint32)));
		UnlockMsg();
		
	} else if (wQueryType == MPQ_ITEM_PATTERN) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_PATTERN, uint32 nItem);
		 */
		error("mpalQuery(MPQ_ITEM_PATTERN, uint32 nItem) used incorrect variant");
		
	} else if (wQueryType == MPQ_LOCATION_SIZE) {
		/*
		 *  uint32 mpalQuery(MPQ_LOCATION_SIZE, uint32 nLoc, uint32 dwCoord);
		 */
		error("mpalQuery(MPQ_LOCATION_SIZE, uint32 nLoc, uint32 dwCoord) used incorrect variant");
		
	} else if (wQueryType == MPQ_LOCATION_IMAGE) {
		/*
		 *  HGLOBAL mpalQuery(MPQ_LOCATION_IMAGE, uint32 nLoc);
		 */
		lockLocations();
		x = locGetOrderFromNum(GETARG(uint32));
		hRet = resLoad(GLOBALS.lpmlLocations[x].dwPicRes);
		unlockLocations();

	} else if (wQueryType == MPQ_RESOURCE) {
		/*
		 *  HGLOBAL mpalQuery(MPQ_RESOURCE, uint32 dwRes);
		 */
		hRet = resLoad(GETARG(uint32));

	} else if (wQueryType == MPQ_ITEM_LIST) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_LIST, uint32 nLoc);
		 */
		lockVar();
		hRet = GetItemList(GETARG(uint32));
		lockVar();

	} else if (wQueryType == MPQ_ITEM_DATA) {
		/*
		 *  LPITEM mpalQuery(MPQ_ITEM_DATA, uint32 nItem);
		 */
		lockItems();
		hRet = getItemData(itemGetOrderFromNum(GETARG(uint32)));
		unlockItems();

	} else if (wQueryType == MPQ_ITEM_IS_ACTIVE) {
		/*
		 *  bool mpalQuery(MPQ_ITEM_IS_ACTIVE, uint32 nItem);
		 */
		error("mpalQuery(MPQ_ITEM_IS_ACTIVE, uint32 nItem) used incorrect variant");

	} else if (wQueryType == MPQ_ITEM_NAME) {
		/*
		 *  uint32 mpalQuery(MPQ_ITEM_NAME, uint32 nItem, char *lpszName);
		 */
		lockVar();
		x = GETARG(uint32);
		n = GETARG(char *);
		buf = Common::String::format("Status.%u", x);
		if (varGetValue(buf.c_str()) <= 0)
			n[0] = '\0';
		else {
			lockItems();
			y = itemGetOrderFromNum(x);
			copyMemory(n, (char *)(GLOBALS.lpmiItems + y)->lpszDescribe, MAX_DESCRIBE_SIZE);
			unlockItems();
		}

		unlockVar();

	} else if (wQueryType == MPQ_DIALOG_PERIOD) {
		/*
		 *  char * mpalQuery(MPQ_DIALOG_PERIOD, uint32 nDialog, uint32 nPeriod);
		 */
		lockDialogs();
		y = GETARG(uint32);
		hRet = duplicateDialogPeriod(y);
		unlockDialogs();

	} else if (wQueryType == MPQ_DIALOG_WAITFORCHOICE) {
		/*
		 *  void mpalQuery(MPQ_DIALOG_WAITFORCHOICE);
		 */
		error("mpalQuery(MPQ_DIALOG_WAITFORCHOICE) used incorrect variant");

	} else if (wQueryType == MPQ_DIALOG_SELECTLIST) {
		/*
		 *  uint32 *mpalQuery(MPQ_DIALOG_SELECTLIST, uint32 nChoice);
		 */
		lockDialogs();
		hRet = getSelectList(GETARG(uint32));
		unlockDialogs();

	} else if (wQueryType == MPQ_DIALOG_SELECTION) {
		/*
		 *  bool mpalQuery(MPQ_DIALOG_SELECTION, uint32 nChoice, uint32 dwData);
		 */
		error("mpalQuery(MPQ_DIALOG_SELECTION, uint32 nChoice, uint32 dwData) used incorrect variant");

	} else if (wQueryType == MPQ_DO_ACTION) {
		/*
		 *  int mpalQuery(MPQ_DO_ACTION, uint32 nAction, uint32 nItem, uint32 dwParam);
		 */
		error("mpalQuery(MPQ_DO_ACTION, uint32 nAction, uint32 nItem, uint32 dwParam) used incorrect variant");

	} else if (wQueryType == MPQ_DO_DIALOG) {
		/*
		 *  int mpalQuery(MPQ_DO_DIALOG, uint32 nDialog, uint32 nGroup);
		 */
		error("mpalQuery(MPQ_DO_DIALOG, uint32 nDialog, uint32 nGroup) used incorrect variant");
	} else {
		/*
		 *  DEFAULT -> ERROR
		 */
		GLOBALS.mpalError = 1;
	}

	va_end(v);
	return hRet;
}


/**
 * This is a general function to communicate with the library, to request information
 * about what is in the .MPC file
 *
 * @param wQueryType		Type of query. The list is in the QueryTypes enum.
 * @returns		4 bytes depending on the type of query
 * @remarks		This is the specialised version of the original single mpalQuery
 * method that needs to run within a co-routine context.
 */
void mpalQueryCORO(CORO_PARAM, uint16 wQueryType, uint32 *dwRet, ...) {
	CORO_BEGIN_CONTEXT;
		uint32 dwRet;
	CORO_END_CONTEXT(_ctx);

	va_list v;
	va_start(v, dwRet);

	CORO_BEGIN_CODE(_ctx);

	if (wQueryType == MPQ_DIALOG_WAITFORCHOICE) {
		/*
		 *  void mpalQuery(MPQ_DIALOG_WAITFORCHOICE);
		 */
		CORO_INVOKE_2(CoroScheduler.waitForSingleObject, GLOBALS.hAskChoice, CORO_INFINITE);

		CoroScheduler.resetEvent(GLOBALS.hAskChoice);

		if (GLOBALS.bExecutingDialog)
			*dwRet = (uint32)GLOBALS.nExecutingChoice;
		else
			*dwRet = (uint32)((int)-1);
	} else {
		error("mpalQueryCORO called with unsupported query type");
	}

	CORO_END_CODE;

	va_end(v);
}


/**
 * Returns the current MPAL error code
 *
 * @returns		Error code
 */
uint32 mpalGetError(void) {
	return GLOBALS.mpalError;
}


/**
 * Execute a script. The script runs on multitasking by a thread.
 *
 * @param nScript			Script number to run
 * @returns		TRUE if the script 'was launched, FALSE on failure
 */
bool mpalExecuteScript(int nScript) {
	int n;
	LPMPALSCRIPT s;

	LockScripts();
	n = scriptGetOrderFromNum(nScript);
	s = (LPMPALSCRIPT)globalAlloc(GMEM_FIXED | GMEM_ZEROINIT, sizeof(MPALSCRIPT));
	if (s == NULL)
		return false;

	copyMemory(s, GLOBALS.lpmsScripts + n, sizeof(MPALSCRIPT));
	unlockScripts();

	// !!! New process management
	if (CoroScheduler.createProcess(ScriptThread, &s, sizeof(LPMPALSCRIPT)) == CORO_INVALID_PID_VALUE)
 		return false;

	return true;
}


/**
 * Install a custom routine That will be called by MPAL every time the pattern 
 * of an item has been changed.
 *
 * @param lpiifCustom		Custom function to install
 */
void mpalInstallItemIrq(LPITEMIRQFUNCTION lpiifCus) {
	GLOBALS.lpiifCustom = lpiifCus;
}


/**
 * Process the idle actions of the items on one location.
 *
 * @param nLoc				Number of the location whose items must be processed 
 * for idle actions.
 * @returns		TRUE if all OK, and FALSE if it exceeded the maximum limit.
 * @remarks		The maximum number of locations that can be polled
 * simultaneously is defined defined by MAXPOLLINGFUNCIONS
 */
bool mpalStartIdlePoll(int nLoc) {
	uint32 i;

	for (i = 0; i < MAXPOLLINGLOCATIONS; i++)
		if (GLOBALS.nPollingLocations[i] == (uint32)nLoc)
			return false;

	for (i = 0; i < MAXPOLLINGLOCATIONS; i++) {
		if (GLOBALS.nPollingLocations[i] == 0) {
			GLOBALS.nPollingLocations[i] = nLoc;

			GLOBALS.hEndPollingLocations[i] = CoroScheduler.createEvent(true, false);
// !!! New process management
			if ((GLOBALS.PollingThreads[i] = CoroScheduler.createProcess(LocationPollThread, &i, sizeof(uint32))) == CORO_INVALID_PID_VALUE)
//			 if ((GLOBALS.hEndPollingLocations[i] = (void*)_beginthread(LocationPollThread, 10240,(void *)i))= = (void*)-1)
				return false;

			return true;
		}
	}

	return false;
}


/**
 * Stop processing the idle actions of the items on one location.
 *
 * @param nLo				Number of the location
 * @returns		TRUE if all OK, FALSE if the specified location was not
 * in the process of polling
 */
void mpalEndIdlePoll(CORO_PARAM, int nLoc, bool *result) {
	CORO_BEGIN_CONTEXT;
		int i;
	CORO_END_CONTEXT(_ctx);

	CORO_BEGIN_CODE(_ctx);

	for (_ctx->i = 0; _ctx->i < MAXPOLLINGLOCATIONS; _ctx->i++) {
		if (GLOBALS.nPollingLocations[_ctx->i] == (uint32)nLoc) {
			CoroScheduler.setEvent(GLOBALS.hEndPollingLocations[_ctx->i]);

			CORO_INVOKE_2(CoroScheduler.waitForSingleObject, GLOBALS.PollingThreads[_ctx->i], CORO_INFINITE);

			CoroScheduler.closeEvent(GLOBALS.hEndPollingLocations[_ctx->i]);
			GLOBALS.nPollingLocations[_ctx->i] = 0;

			if (result)
				*result = true;
			return;
		}
	}

	if (result)
		*result = false;

	CORO_END_CODE;
}


/**
 * Retrieve the length of a save state
 *
 * @returns		Length in bytes
 */
int mpalGetSaveStateSize(void) {
	return GLOBALS.nVars * sizeof(MPALVAR) + 4;
}


/**
 * Store the save state into a buffer. The buffer must be
 * length at least the size specified with mpalGetSaveStateSize
 *
 * @param buf				Buffer where to store the state
 */
void mpalSaveState(byte *buf) {
	lockVar();
	WRITE_LE_UINT32(buf, GLOBALS.nVars);
	copyMemory(buf + 4, (byte *)GLOBALS.lpmvVars, GLOBALS.nVars * sizeof(MPALVAR));
	unlockVar();	
}


/**
 * Load a save state from a buffer.
 *
 * @param buf				Buffer where to store the state
 * @returns		Length of the state buffer in bytes
 */
int mpalLoadState(byte *buf) {
	// We must destroy and recreate all the variables
	globalFree(GLOBALS.hVars);

	GLOBALS.nVars = READ_LE_UINT32(buf);
	
	GLOBALS.hVars = globalAllocate(GMEM_ZEROINIT | GMEM_MOVEABLE, GLOBALS.nVars * sizeof(MPALVAR));
	lockVar();
	copyMemory((byte *)GLOBALS.lpmvVars, buf + 4, GLOBALS.nVars * sizeof(MPALVAR));
	unlockVar();

	return GLOBALS.nVars * sizeof(MPALVAR) + 4;
}

bool bDontOutput;

struct MsgCommentsStruct {
	uint16 wStart;
	uint16 wEnd;
	const char *pComment;	
};
const MsgCommentsStruct MsgComments[] = {
	{ 10, 16, "###" },
	{ 560, 563, "@@@ BUTCH & DUDLEY:" },
	{ 551, 553, "@@@ JACK'S LETTER (JACK'S VOICE):" },
	{ 679, 679, "@@@ OFF-SCREEN VOICE:" },
	{ 799, 799, "###" },
	{ 830, 838, "RE-HASHING (FROM MACBETH):" },
	{ 890, 894, "@@@ BEARDED LADY FROM WITHIN HER ROOM:" },
	{ 1175, 1175, "###" },
	{ 1210, 1210, "###" },
	{ 1347, 1349, "###" },
	{ 1175, 1175, "###" },
	{ 1342, 1343, "###" },
	{ 1742, 1742, "@@@ OFF-SCREEN VOICE:" },
	{ 1749, 1749, "###" },
	{ 1759, 1759, "###" },
	{ 2165, 2166, "@@@ MORTIMER:" },
	{ 2370, 2372, "@@@ ELECTRONIC VOICE FROM AN AUTOMATIC PICTURE MACHINE:" },
	{ 2580, 2589, "@@@ BIFF:" },
	{ 2590, 2593, "@@@ BARTENDER:" },
	{ 2596, 2596, "@@@ SAD PIRATE:" },
	{ 2760, 2767, "@@@ EGGHEAD:" },
	{ 2959, 2959, "@@@ MONSTROUS VOICE FROM BEHIND A LOCKED DOOR:" },
	{ 3352, 3352, "@@@ POLLY:" },
	{ 3378, 3379, "@@@ POLLY:" },
	{ 3461, 3469, "@@@ RANDALL:" },
	{ 3571, 3574, "@@@ CAPTAIN'S JOURNAL (CAPTAIN'S VOICE):" },
	{ 3646, 3646, "NOTE: THIS SENTENCE ENDS THE STORY TOLD IN SENTENCES 03640 - 03643:" },
	{ 3647, 3648, "TONY SPEAKS TRYING TO IMITATE CAPTAIN CORNELIUS' VOICE:" },
	{ 3670, 3671, "###" },
	{ 3652, 3652, "###" },
	{ 3656, 3657, "@@@ GATEKEEPER:" },
	{ 3658, 3659, "@@@ GATEKEEPER (FAR AWAY):" },
	{ 3790, 3795, "@@@ GATEKEEPER:" },
	{ 3798, 3799, "@@@ OFF-SCREEN VOICE:" },
	{ 4384, 4384, "###" },
	{ 4394, 4395, "###" },
	{ 4780, 4780, "###" },
	{ 5089, 5089, "TONY PLAYING SOMEONE ELSE, WITH A DEEPER TONE:" },
	{ 5090, 5090, "NORMAL TONY:" },
	{ 5091, 5091, "TONY PLAYING SOMEONE ELSE, WITH A DEEPER TONE:" },
	{ 5262, 5262, "@@@ OFF-SCREEN VOICE" },
	{ 5276, 5277, "###" },
	{ 5326, 5326, "###" },
	{ 5472, 5472, "LYRICS FROM THE SONG \"I AM ONE\", BY SMASHING PUMPKINS:" },
	{ 5488, 5488, "LYRICS FROM THE SONG \"I AM ONE\", BY SMASHING PUMPKINS:" },
	{ 5652, 5653, "###" },
//bernie	{ 11000, 15000, "###" },
	{ 11000, 11111, "###" },


	{ 0, 0, NULL }
};

void outputStartMsgComment(uint16 wNum, Common::OutSaveFile *f) {
	int i;

	for (i = 0; MsgComments[i].wStart != 0; i++)
		if (MsgComments[i].wStart == wNum) {
			debugC(DEBUG_BASIC, kTonyDebugMPAL, "Start: %d\n", wNum);

			f->writeString("</TABLE>\n<P>\n<P>\n");

			if (strcmp(MsgComments[i].pComment, "###") != 0 && strncmp(MsgComments[i].pComment, "@@@", 3) != 0) {
				f->writeString(Common::String::format("%s\n", MsgComments[i].pComment));
				f->writeString("<P>\n<P>\n<TABLE WIDTH = 100%% BORDER = 1>\n");
			} else
				bDontOutput = true;
			return;
		}
}

void OutputEndMsgComment(uint16 wNum, Common::OutSaveFile *f) {
	int i;

	for (i = 0; MsgComments[i].wEnd != 0; i++)
		if (MsgComments[i].wEnd == wNum) {
			debugC(DEBUG_BASIC, kTonyDebugMPAL, "End: %d\n", wNum);

			if (strcmp(MsgComments[i].pComment, "###") != 0 && strncmp(MsgComments[i].pComment, "@@@", 3) != 0) {
				f->writeString("</TABLE>\n<P>\n");
			} else
				bDontOutput = false;
	
			f->writeString("<P>\n<P>\n<TABLE WIDTH = 100%% BORDER = 1>\n");
			return;
		}
}


int OutputStartOther(uint16 wNum, Common::OutSaveFile *f) {
	int i;
	
	for (i = 0; MsgComments[i].wStart != 0; i++)
		if (MsgComments[i].wStart <= wNum && MsgComments[i].wEnd >= wNum) {
			if (strncmp(MsgComments[i].pComment, "@@@", 3) == 0) {
				if (MsgComments[i].wStart == wNum) {
					f->writeString(Common::String::format("%s\n", MsgComments[i].pComment + 4));
					f->writeString("<P>\n<P>\n<TABLE WIDTH = 100%% BORDER = 1>\n");
				}
				
				return 1;				
			}
		}

	return 0;
}


void outputEndOther(uint16 wNum, Common::OutSaveFile *f) {
	int i;

	for (i = 0; MsgComments[i].wStart != 0; i++)
		if (MsgComments[i].wEnd == wNum && strncmp(MsgComments[i].pComment, "@@@", 3) == 0) {
			f->writeString("</TABLE>\n<P>\n");	
			break;
		}
}


void mpalDumpMessages(void) {
	int i, j;
	char *lpMessage;
	char *p;
	char *lpPeriods[30];
	char fname[64];
	char frase[2048];
	int nPeriods;
	Common::OutSaveFile *f, *v1;

	v1 = g_system->getSavefileManager()->openForSaving("voicelist.txt");

	LockMsg();

	bDontOutput = false;

	debugC(DEBUG_BASIC, kTonyDebugMPAL, "Dumping MESSAGES.HTM...\n");
	
	f = g_system->getSavefileManager()->openForSaving("Messages.htm");
	f->writeString("<HTML>\n<BODY>\n<TABLE WIDTH = 100%% BORDER = 1>\n");

	for (i = 0; i < GLOBALS.nMsgs; i++) {
		lpMessage = (char *)globalLock(GLOBALS.lpmmMsgs[i].hText);
		if (*lpMessage != '\0') {
			// bernie: debug
			/*if (GLOBALS.lpmmMsgs[i].wNum == 1950) {
				int a = 1;
			}*/

			nPeriods = 1;
			p = lpPeriods[0] = lpMessage;

			outputStartMsgComment(GLOBALS.lpmmMsgs[i].wNum, f);

			while (1) {
				// Find the end of the current period
				while (*p != '\0')
					p++;

				// If there is another '\0' at the end of the message, then finish
				p++;
				if (*p == '\0')
					break;

				// Otherwise there is another line, so remember the next one's start
				lpPeriods[nPeriods++] = p;
			}

			// Now make a loop over all the periods
			for (j = 0; j < nPeriods; j++) {
				if (nPeriods == 1)
					sprintf(fname, "000-%05d.WAV", GLOBALS.lpmmMsgs[i].wNum);
				else
					sprintf(fname, "000-%05d-%02d.WAV", GLOBALS.lpmmMsgs[i].wNum,j);
			
				strcpy(frase, lpPeriods[j]);

				while ((p = strchr(frase,'^')) != NULL)
					*p = '\"';

				p = frase;
				while (*p == ' ')
					p++;
				if (*p == '\0')
					continue;

				if (!bDontOutput) {
					v1->writeString(Common::String::format("%s\n", fname));
					f->writeString("\t<TR>\n");
					f->writeString(Common::String::format("\t\t<TD WIDTH=20%%> %s </B></TD>\n", fname));
					f->writeString(Common::String::format("\t\t<TD> %s </TD>\n", frase));
					f->writeString("\t</TR>\n");
				}
			}

			OutputEndMsgComment(GLOBALS.lpmmMsgs[i].wNum, f);

			globalUnlock(GLOBALS.lpmmMsgs[i].hText);
		}
	}

	f->writeString("</TABLE>\n</BODY>\n</HTML>\n");

	f->finalize();
	v1->finalize();
	delete f;
	delete v1;

	UnlockMsg();
}



void mpalDumpOthers(void) {
	int i,j;
	char *lpMessage;
	char *p;
	char *lpPeriods[30];
	char fname[64];
	char frase[2048];
	int nPeriods;

	Common::OutSaveFile *f, *v1;

	v1 = g_system->getSavefileManager()->openForSaving("voicelist.txt");
	f = g_system->getSavefileManager()->openForSaving("Others.htm");
	LockMsg();
	
	bDontOutput = false;
	
	debugC(DEBUG_BASIC, kTonyDebugMPAL, "Dumping OTHERS.HTM...\n");

	f->writeString("<HTML>\n<BODY>\n");
	
	for (i = 0; i < GLOBALS.nMsgs; i++) {
		lpMessage = (char *)globalLock(GLOBALS.lpmmMsgs[i].hText);
		if (*lpMessage != '\0') {
			nPeriods = 1;
			p = lpPeriods[0] = lpMessage;
			
			if (OutputStartOther(GLOBALS.lpmmMsgs[i].wNum, f)) {	
				while (1) {
					// Find the end of the current period
					while (*p != '\0')
						p++;
					
					// If there is another '0' at the end, then the message is finished
					p++;
					if (*p == '\0')
						break;
					
					// Remember the start of the next line
					lpPeriods[nPeriods++] = p;
				}
				
				// Now loop over all the periods
				for (j = 0; j < nPeriods; j++) {
					if (nPeriods == 1)
						sprintf(fname, "000-%05d.WAV", GLOBALS.lpmmMsgs[i].wNum);
					else
						sprintf(fname, "000-%05d-%02d.WAV", GLOBALS.lpmmMsgs[i].wNum,j);				

					strcpy(frase,lpPeriods[j]);
					
					while ((p = strchr(frase, '^')) != NULL)
						*p = '\"';

					p = frase;
					while (*p == ' ')
						p++;
					if (*p == '\0')
						continue;		
					
					if (!bDontOutput) {
						v1->writeString(Common::String::format("%s\n", fname));
						f->writeString("\t<TR>\n");
						f->writeString(Common::String::format("\t\t<TD WIDTH=20%%> %s </B></TD>\n", fname));
						f->writeString(Common::String::format("\t\t<TD> %s </TD>\n", frase));
						f->writeString("\t</TR>\n");
					}
				}
			}

			outputEndOther(GLOBALS.lpmmMsgs[i].wNum, f);
			
			globalUnlock(GLOBALS.lpmmMsgs[i].hText);
		}
	}
	
	f->writeString("</BODY>\n</HTML>\n");
	
	f->finalize();
	v1->finalize();

	delete f;
	delete v1;
	UnlockMsg();
}


#if 0 // English names
const char *DLG10[] = { "Tony", NULL };
const char *DLG51[] = { "Tony", "Butch", "Dudley" };
const char *DLG52[] = { "Tony", NULL };
const char *DLG61[] = { "Tony", "Old lady 1", NULL };
const char *DLG71[] = { "Tony", "Timothy", "Convict", NULL, NULL, "Jack (with microphone)", "Old lady 1", NULL };
const char *DLG90[] = { "Tony", "Bearded lady", NULL };
const char *DLG110[] = { "Tony", "Lorenz", NULL };
const char *DLG111[] = { "Tony", "Lorenz", NULL };
const char *DLG130[] = { "Tony", "Piranha", NULL };
const char *DLG150[] = { "Tony", "Rufus", "Snowman", NULL };
const char *DLG151[] = { "Tony", "Rufus", "Snowman", NULL };
const char *DLG152[] = { "Tony", "Rufus", "Snowman", NULL };
const char *DLG153[] = { "Tony", "Rufus", "Snowman", NULL };
const char *DLG154[] = { "Tony", "Rufus", "Snowman", NULL };
const char *DLG160[] = { "Tony", "Shmiley", NULL };
const char *DLG161[] = { "Tony", "Shmiley", NULL };
const char *DLG162[] = { "Tony", "Shmiley", NULL };
const char *DLG163[] = { "Tony", "Shmiley", NULL };
const char *DLG180[] = { "Tony", "Beast", NULL };
const char *DLG190[] = { "Tony", "Beast", NULL };
const char *DLG191[] = { "Tony", "Beast", NULL };
const char *DLG201[] = { "Tony", NULL };
const char *DLG210[] = { "Tony", "Mortimer", NULL };
const char *DLG211[] = { "Tony", "Mortimer", NULL };
const char *DLG212[] = { "Tony", "Mortimer", NULL };
const char *DLG240[] = { "Tony", "Isabella", NULL };
const char *DLG250[] = { "Tony", "Bartender", "Sad pirate", "Anchorman", "Biff", NULL };
const char *DLG251[] = { "Tony", "Bartender", "Sad pirate", "Anchorman", "Biff", NULL };
const char *DLG260[] = { "Tony", "Captain", "Captain (tale)", NULL };
const char *DLG270[] = { "Tony", "Egghead", NULL };
const char *DLG271[] = { "Tony", "Egghead", NULL };
const char *DLG272[] = { "Tony", "Egghead", NULL };
const char *DLG290[] = { "Tony", "Old lady 2", NULL };
const char *DLG310[] = { "Tony", "Wally", NULL };
const char *DLG330[] = { "Tony", "Polly", "Captain (off scene)", NULL };
const char *DLG340[] = { "Tony", "Randall", NULL };
const char *DLG360[] = { "Tony", NULL };
const char *DLG361[] = { "Tony", NULL };
const char *DLG370[] = { "Tony", "Gatekeeper", NULL };
const char *DLG371[] = { "Tony", "Gatekeeper", NULL };
const char *DLG372[] = { "Tony", "Gatekeeper", NULL };
const char *DLG373[] = { "Tony", "Gatekeeper", NULL };
const char *DLG380[] = { "Tony", NULL };
const char *DLG410[] = { "Tony", "Gwendel", NULL };
const char *DLG430[] = { "Tony", "Harold", "Chuck", "Pigeons", "Housekeeper (off scene)", NULL };
const char *DLG460[] = { "Tony", NULL };
const char *DLG470[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG471[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG472[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG473[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG474[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG480[] = { "Tony", "Pin-up", NULL };
const char *DLG490[] = { "Tony", "Gwendel", NULL };	
const char *DLG530[] = { "Tony", "Harold", "Chuck", NULL };
const char *DLG550[] = { "Tony", "Mr. Wishing Well", "Tony (from the top of the well)", NULL  };
const char *DLG560[] = { "Tony", "Superintendent", NULL };
const char *DLG590[] = { "Tony", "Pantagruel", NULL };
const char *DLG600[] = { "Tony", "Jack", "Jack", NULL, "Jack", NULL, NULL, NULL, "Storyteller", "Mr. Wishing Well", NULL };
#endif

#if 0 // Polish names
const char *DLG10[] = { "Tony", NULL };
const char *DLG51[] = { "Tony", "Butch", "Dudley" };
const char *DLG52[] = { "Tony", NULL };
const char *DLG61[] = { "Tony", "Staruszka 1", NULL };
const char *DLG71[] = { "Tony", "Timothy", "Skazaniec", NULL, NULL, "�ebster (przez mikrofon)", "Staruszka 1", NULL };
const char *DLG90[] = { "Tony", "Kobieta z Brod�", NULL };
const char *DLG110[] = { "Tony", "Lorenz", NULL };
const char *DLG111[] = { "Tony", "Lorenz", NULL };
const char *DLG130[] = { "Tony", "Pirania", NULL };
const char *DLG150[] = { "Tony", "Rufus", "Ba�wan", NULL };
const char *DLG151[] = { "Tony", "Rufus", "Ba�wan", NULL };
const char *DLG152[] = { "Tony", "Rufus", "Ba�wan", NULL };
const char *DLG153[] = { "Tony", "Rufus", "Ba�wan", NULL };
const char *DLG154[] = { "Tony", "Rufus", "Ba�wan", NULL };
const char *DLG160[] = { "Tony", "�miechozol", NULL };
const char *DLG161[] = { "Tony", "�miechozol", NULL };
const char *DLG162[] = { "Tony", "�miechozol", NULL };
const char *DLG163[] = { "Tony", "�miechozol", NULL };
const char *DLG180[] = { "Tony", "Wycz", NULL };
const char *DLG190[] = { "Tony", "Wycz", NULL };
const char *DLG191[] = { "Tony", "Wycz", NULL };
const char *DLG201[] = { "Tony", NULL };
const char *DLG210[] = { "Tony", "Mortimer (Okropny)", NULL };
const char *DLG211[] = { "Tony", "Mortimer (Okropny)", NULL };
const char *DLG212[] = { "Tony", "Mortimer (Okropny)", NULL };
const char *DLG240[] = { "Tony", "Isabella", NULL };
const char *DLG250[] = { "Tony", "Barman", "Smutny Pirat", "Wodzirej", "Biff", NULL };
const char *DLG251[] = { "Tony", "Barman", "Smutny Pirat", "Wodzirej", "Biff", NULL };
const char *DLG260[] = { "Tony", "Kapitan", "Captain (opowie��)", NULL };
const char *DLG270[] = { "Tony", "Jajog�owy", NULL };
const char *DLG271[] = { "Tony", "Jajog�owy", NULL };
const char *DLG272[] = { "Tony", "Jajog�owy", NULL };
const char *DLG290[] = { "Tony", "Staruszka 2", NULL };
const char *DLG310[] = { "Tony", "Wally", NULL };
const char *DLG330[] = { "Tony", "Polly", "Kapitan (zza sceny)", NULL };
const char *DLG340[] = { "Tony", "Randall", NULL };
const char *DLG360[] = { "Tony", NULL };
const char *DLG361[] = { "Tony", NULL };
const char *DLG370[] = { "Tony", "Stra�nik", NULL };
const char *DLG371[] = { "Tony", "Stra�nik", NULL };
const char *DLG372[] = { "Tony", "Stra�nik", NULL };
const char *DLG373[] = { "Tony", "Stra�nik", NULL };
const char *DLG380[] = { "Tony", NULL };
const char *DLG410[] = { "Tony", "Gwendel", NULL };
const char *DLG430[] = { "Tony", "Harold", "Chuck", "Pigeons", "Gospodyni (zza sceny)", NULL };
const char *DLG460[] = { "Tony", NULL };
const char *DLG470[] = { "Tony", "Gospodyni", "Mirror", NULL };
const char *DLG471[] = { "Tony", "Gospodyni", "Mirror", NULL };
const char *DLG472[] = { "Tony", "Gospodyni", "Mirror", NULL };
const char *DLG473[] = { "Tony", "Gospodyni", "Mirror", NULL };
const char *DLG474[] = { "Tony", "Gospodyni", "Mirror", NULL };
const char *DLG480[] = { "Tony", "Pin-up", NULL };
const char *DLG490[] = { "Tony", "Gwendel", NULL };
const char *DLG530[] = { "Tony", "Harold", "Chuck", NULL };
const char *DLG550[] = { "Tony", "Pan Studnia �ycze�", "Tony (nad studni�)", NULL  };
const char *DLG560[] = { "Tony", "Inspektor", NULL };
const char *DLG590[] = { "Tony", "Pantaloniarz", NULL };
const char *DLG600[] = { "Tony", "�ebster", "�ebster", NULL, "�ebster", NULL, NULL, NULL, "Narrator", "Pan Studnia �ycze�", NULL };
#endif // Polish


#if 0 // Russian
const char *DLG10[] = { "����", NULL };
const char *DLG51[] = { "����", "���", "�����" };
const char *DLG52[] = { "����", NULL };
const char *DLG61[] = { "����", "�������� 1", NULL };
const char *DLG71[] = { "����", "������", "����������", NULL, NULL, "���� (� ����������)", "�������� 1", NULL };
const char *DLG90[] = { "����", "��������� �������", NULL };
const char *DLG110[] = { "����", "������", NULL };
const char *DLG111[] = { "����", "������", NULL };
const char *DLG130[] = { "����", "�������", NULL };
const char *DLG150[] = { "����", "�����", "��������", NULL };
const char *DLG151[] = { "����", "�����", "��������", NULL };
const char *DLG152[] = { "����", "�����", "��������", NULL };
const char *DLG153[] = { "����", "�����", "��������", NULL };
const char *DLG154[] = { "����", "�����", "��������", NULL };
const char *DLG160[] = { "����", "������", NULL };
const char *DLG161[] = { "����", "������", NULL };
const char *DLG162[] = { "����", "������", NULL };
const char *DLG163[] = { "����", "������", NULL };
const char *DLG180[] = { "����", "��������", NULL };
const char *DLG190[] = { "����", "��������", NULL };
const char *DLG191[] = { "����", "��������", NULL };
const char *DLG201[] = { "����", NULL };
const char *DLG210[] = { "����", "��������", NULL };
const char *DLG211[] = { "����", "��������", NULL };
const char *DLG212[] = { "����", "��������", NULL };
const char *DLG240[] = { "����", "��������", NULL };
const char *DLG250[] = { "����", "������", "�������� �����", "�������", "����", NULL };
const char *DLG251[] = { "����", "������", "�������� �����", "�������", "����", NULL };
const char *DLG260[] = { "����", "�������", "������� (�������)", NULL };
const char *DLG270[] = { "����", "�����������", NULL };
const char *DLG271[] = { "����", "�����������", NULL };
const char *DLG272[] = { "����", "�����������", NULL };
const char *DLG290[] = { "����", "�������� 2", NULL };
const char *DLG310[] = { "����", "�����", NULL };
const char *DLG330[] = { "����", "�����", "������� (�� ������)", NULL };
const char *DLG340[] = { "����", "������", NULL };
const char *DLG360[] = { "����", NULL };
const char *DLG361[] = { "����", NULL };
const char *DLG370[] = { "����", "����������", NULL };
const char *DLG371[] = { "����", "����������", NULL };
const char *DLG372[] = { "����", "����������", NULL };
const char *DLG373[] = { "����", "����������", NULL };
const char *DLG380[] = { "����", NULL };
const char *DLG410[] = { "����", "��������", NULL };
const char *DLG430[] = { "����", "�������", "���", "Pigeons", "Housekeeper (off scene)", NULL };
const char *DLG460[] = { "����", NULL };
const char *DLG470[] = { "����", "Housekeeper", "Mirror", NULL };
const char *DLG471[] = { "����", "Housekeeper", "Mirror", NULL };
const char *DLG472[] = { "����", "Housekeeper", "Mirror", NULL };
const char *DLG473[] = { "����", "Housekeeper", "Mirror", NULL };
const char *DLG474[] = { "����", "Housekeeper", "Mirror", NULL };
const char *DLG480[] = { "����", "Pin-up", NULL };
const char *DLG490[] = { "����", "��������", NULL };	
const char *DLG530[] = { "����", "�������", "���", NULL };
const char *DLG550[] = { "����", "�������� ������� �������", "���� (� ������� �������)", NULL  };
const char *DLG560[] = { "����", "��������� ������", NULL };
const char *DLG590[] = { "����", "�����������", NULL };
const char *DLG600[] = { "����", "����", "����", NULL, "����", NULL, NULL, NULL, "����������", "�������� ������� �������", NULL };
#endif // Russian


#if 0 // Czech names
const char *DLG10[] = { "Tony", NULL };
const char *DLG51[] = { "Tony", "Butch", "Dudley" };
const char *DLG52[] = { "Tony", NULL };
const char *DLG61[] = { "Tony", "Star� pan� 1", NULL };
const char *DLG71[] = { "Tony", "Timothy", "Trestanec", NULL, NULL, "Jack (s mikrofonem)", "Star� pan� 1", NULL };
const char *DLG90[] = { "Tony", "Vousat� �ena", NULL };
const char *DLG110[] = { "Tony", "Lorenz", NULL };
const char *DLG111[] = { "Tony", "Lorenz", NULL };
const char *DLG130[] = { "Tony", "Pira�a", NULL };
const char *DLG150[] = { "Tony", "Rufus", "Sn�hul�k", NULL };
const char *DLG151[] = { "Tony", "Rufus", "Sn�hul�k", NULL };
const char *DLG152[] = { "Tony", "Rufus", "Sn�hul�k", NULL };
const char *DLG153[] = { "Tony", "Rufus", "Sn�hul�k", NULL };
const char *DLG154[] = { "Tony", "Rufus", "Sn�hul�k", NULL };
const char *DLG160[] = { "Tony", "Shmiley", NULL };
const char *DLG161[] = { "Tony", "Shmiley", NULL };
const char *DLG162[] = { "Tony", "Shmiley", NULL };
const char *DLG163[] = { "Tony", "Shmiley", NULL };
const char *DLG180[] = { "Tony", "Zv��e", NULL };
const char *DLG190[] = { "Tony", "Zv��e", NULL };
const char *DLG191[] = { "Tony", "Zv��e", NULL };
const char *DLG201[] = { "Tony", NULL };
const char *DLG210[] = { "Tony", "Mortimer", NULL };
const char *DLG211[] = { "Tony", "Mortimer", NULL };
const char *DLG212[] = { "Tony", "Mortimer", NULL };
const char *DLG240[] = { "Tony", "Isabella", NULL };
const char *DLG250[] = { "Tony", "Barman", "Smutn� pir�t", "Moder�tor", "Biff", NULL };
const char *DLG251[] = { "Tony", "Barman", "Smutn� pir�t", "Moder�tor", "Biff", NULL };
const char *DLG260[] = { "Tony", "Kapit�n", "Kapit�n (p��b�h)", NULL };
const char *DLG270[] = { "Tony", "Intelektu�l", NULL };
const char *DLG271[] = { "Tony", "Intelektu�l", NULL };
const char *DLG272[] = { "Tony", "Intelektu�l", NULL };
const char *DLG290[] = { "Tony", "Star� pan� 2", NULL };
const char *DLG310[] = { "Tony", "Wally", NULL };
const char *DLG330[] = { "Tony", "L�ra", "Kapit�n (mimo sc�nu)", NULL };
const char *DLG340[] = { "Tony", "Randall", NULL };
const char *DLG360[] = { "Tony", NULL };
const char *DLG361[] = { "Tony", NULL };
const char *DLG370[] = { "Tony", "Str�n�", NULL };
const char *DLG371[] = { "Tony", "Str�n�", NULL };
const char *DLG372[] = { "Tony", "Str�n�", NULL };
const char *DLG373[] = { "Tony", "Str�n�", NULL };
const char *DLG380[] = { "Tony", NULL };
const char *DLG410[] = { "Tony", "Gwendel", NULL };
const char *DLG430[] = { "Tony", "Harold", "Chuck", "Pigeons", "Housekeeper (off scene)", NULL };
const char *DLG460[] = { "Tony", NULL };
const char *DLG470[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG471[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG472[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG473[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG474[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG480[] = { "Tony", "Pin-up", NULL };
const char *DLG490[] = { "Tony", "Gwendel", NULL };	
const char *DLG530[] = { "Tony", "Harold", "Chuck", NULL };
const char *DLG550[] = { "Tony", "Pan Studna p��n�", "Tony (z vrcholu studny)", NULL  };
const char *DLG560[] = { "Tony", "Spr�vce", NULL };
const char *DLG590[] = { "Tony", "Pantagruel", NULL };
const char *DLG600[] = { "Tony", "Jack", "Jack", NULL, "Jack", NULL, NULL, NULL, "Vyprav��", "Pan Studna p��n�", NULL };
#endif // Czech names

#if 1 // Deutsch names
const char *DLG10[] = { "Tony", NULL };
const char *DLG51[] = { "Tony", "Butch", "Dudley" };
const char *DLG52[] = { "Tony", NULL };
const char *DLG61[] = { "Tony", "Alte Dame 1", NULL };
const char *DLG71[] = { "Tony", "Timothy", "Str�fling", NULL, NULL, "Jack (mit Mikrofon)", "Alte Dame 1", NULL };
const char *DLG90[] = { "Tony", "B�rtige Dame", NULL };
const char *DLG110[] = { "Tony", "Lorenz", NULL };
const char *DLG111[] = { "Tony", "Lorenz", NULL };
const char *DLG130[] = { "Tony", "Piranha", NULL };
const char *DLG150[] = { "Tony", "Rufus", "Schneemann", NULL };
const char *DLG151[] = { "Tony", "Rufus", "Schneemann", NULL };
const char *DLG152[] = { "Tony", "Rufus", "Schneemann", NULL };
const char *DLG153[] = { "Tony", "Rufus", "Schneemann", NULL };
const char *DLG154[] = { "Tony", "Rufus", "Schneemann", NULL };
const char *DLG160[] = { "Tony", "Shmiley", NULL };
const char *DLG161[] = { "Tony", "Shmiley", NULL };
const char *DLG162[] = { "Tony", "Shmiley", NULL };
const char *DLG163[] = { "Tony", "Shmiley", NULL };
const char *DLG180[] = { "Tony", "Biest", NULL };
const char *DLG190[] = { "Tony", "Biest", NULL };
const char *DLG191[] = { "Tony", "Biest", NULL };
const char *DLG201[] = { "Tony", NULL };
const char *DLG210[] = { "Tony", "Mortimer", NULL };
const char *DLG211[] = { "Tony", "Mortimer", NULL };
const char *DLG212[] = { "Tony", "Mortimer", NULL };
const char *DLG240[] = { "Tony", "Isabella", NULL };
const char *DLG250[] = { "Tony", "Barmann", "Trauriger Pirat", "Chefanimateur", "Biff", NULL };
const char *DLG251[] = { "Tony", "Barmann", "Trauriger Pirat", "Chefanimateur", "Biff", NULL };
const char *DLG260[] = { "Tony", "Kapit�n", "Kapit�n (Erz�hlung)", NULL };
const char *DLG270[] = { "Tony", "Eierkopf", NULL };
const char *DLG271[] = { "Tony", "Eierkopf", NULL };
const char *DLG272[] = { "Tony", "Eierkopf", NULL };
const char *DLG290[] = { "Tony", "Alte Dame 2", NULL };
const char *DLG310[] = { "Tony", "Wally", NULL };
const char *DLG330[] = { "Tony", "Polly", "Kapit�n (im Off)", NULL };
const char *DLG340[] = { "Tony", "Randall", NULL };
const char *DLG360[] = { "Tony", NULL };
const char *DLG361[] = { "Tony", NULL };
const char *DLG370[] = { "Tony", "Pf�rtner", NULL };
const char *DLG371[] = { "Tony", "Pf�rtner", NULL };
const char *DLG372[] = { "Tony", "Pf�rtner", NULL };
const char *DLG373[] = { "Tony", "Pf�rtner", NULL };
const char *DLG380[] = { "Tony", NULL };
const char *DLG410[] = { "Tony", "Gwendel", NULL };
const char *DLG430[] = { "Tony", "Harold", "Chuck", "Pigeons", "Housekeeper (off scene)", NULL };
const char *DLG460[] = { "Tony", NULL };
const char *DLG470[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG471[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG472[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG473[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG474[] = { "Tony", "Housekeeper", "Mirror", NULL };
const char *DLG480[] = { "Tony", "Pin-up", NULL };
const char *DLG490[] = { "Tony", "Gwendel", NULL };	
const char *DLG530[] = { "Tony", "Harold", "Chuck", NULL };
const char *DLG550[] = { "Tony", "Herr Wunschbrunnen", "Tony (�ber dem Brunnen)", NULL  };
const char *DLG560[] = { "Tony", "Verwalter", NULL };
const char *DLG590[] = { "Tony", "Pantagruel", NULL };
const char *DLG600[] = { "Tony", "Jack", "Jack", NULL, "Jack", NULL, NULL, NULL, "Erz�hler", "Herr Wunschbrunnen", NULL };
#endif


#define HANDLE_DIALOG(num)	\
case num:	\
	if (nPers >= (int)(sizeof(DLG##num) / sizeof(const char *)) || DLG##num[nPers] == NULL)	\
	{	\
		warning("ERROR: The character #%d does not exist in dialog %d!\n", nPers, nDlg);	\
		return "ERROR";	\
	}	\
	else	\
		return DLG##num[nPers];


const char *getPersonName(uint16 nDlg, int nPers) {
	switch (nDlg) {
	HANDLE_DIALOG(10);
	HANDLE_DIALOG(51);
	HANDLE_DIALOG(52);
	HANDLE_DIALOG(61);
	HANDLE_DIALOG(71);
	HANDLE_DIALOG(90);
	HANDLE_DIALOG(110);
	HANDLE_DIALOG(111);
	HANDLE_DIALOG(130);
	HANDLE_DIALOG(150);
	HANDLE_DIALOG(151);
	HANDLE_DIALOG(152);
	HANDLE_DIALOG(153);
	HANDLE_DIALOG(154);
	HANDLE_DIALOG(160);
	HANDLE_DIALOG(161);
	HANDLE_DIALOG(162);
	HANDLE_DIALOG(163);
	HANDLE_DIALOG(180);
	HANDLE_DIALOG(190);
	HANDLE_DIALOG(191);
	HANDLE_DIALOG(201);
	HANDLE_DIALOG(210);
	HANDLE_DIALOG(211);
	HANDLE_DIALOG(212);
	HANDLE_DIALOG(240);
	HANDLE_DIALOG(250);
	HANDLE_DIALOG(251);
	HANDLE_DIALOG(260);
	HANDLE_DIALOG(270);
	HANDLE_DIALOG(271);
	HANDLE_DIALOG(272);
	HANDLE_DIALOG(290);
	HANDLE_DIALOG(310);
	HANDLE_DIALOG(330);
	HANDLE_DIALOG(340);
	HANDLE_DIALOG(360);
	HANDLE_DIALOG(361);
	HANDLE_DIALOG(370);
	HANDLE_DIALOG(371);
	HANDLE_DIALOG(372);
	HANDLE_DIALOG(373);
	HANDLE_DIALOG(380);
	HANDLE_DIALOG(410);
	HANDLE_DIALOG(430);
	HANDLE_DIALOG(460);
	HANDLE_DIALOG(470);
	HANDLE_DIALOG(471);
	HANDLE_DIALOG(472);
	HANDLE_DIALOG(473);
	HANDLE_DIALOG(474);
	HANDLE_DIALOG(480);
	HANDLE_DIALOG(490);
	HANDLE_DIALOG(530);
	HANDLE_DIALOG(550);
	HANDLE_DIALOG(560);
	HANDLE_DIALOG(590);
	HANDLE_DIALOG(600);

	default:
		warning("ERROR: Dialog %d does not exist!", (int)nDlg);
		return "ERROR";
	}
}

void mpalDumpDialog(LPMPALDIALOG dlg) {
	char dfn[64];
	char fname[64];
	int g,c,j;
	struct command* curCmd;
	char *frase; char *p;
	char copia[2048];
	bool bAtLeastOne;
	Common::OutSaveFile *f, *v1;

	v1 = g_system->getSavefileManager()->openForSaving("voicelist.txt");
	
	sprintf(dfn,"DIALOG%03d.HTM", dlg->nObj);
	warning("Dumping %s...\n", dfn);

	f = g_system->getSavefileManager()->openForSaving(dfn);

	f->writeString("<HTML>\n<BODY>\n");

	for (g = 0; dlg->_group[g].num != 0; g++) {
		bAtLeastOne = false;

		for (c = 0; c<dlg->_group[g].nCmds; c++) {
			curCmd = &dlg->_command[dlg->_group[g].CmdNum[c]];
			if (curCmd->type == 1 && curCmd->nCf == 71) {
				bAtLeastOne = true;
				break;
			}
		}
		
		if (!bAtLeastOne)
			continue;
		
		f->writeString(Common::String::format("<P>\n<H3>Group %d</H3>\n<P>\n", g));
		f->writeString("<TABLE WIDTH = 100%% BORDER = 1>\n");

		for (c = 0; c < dlg->_group[g].nCmds; c++) {
			curCmd = &dlg->_command[dlg->_group[g].CmdNum[c]];

			// If it's a custom function, call SendDialogMessage(nPers, nMsg)
			if (curCmd->type == 1 && curCmd->nCf == 71) {
				sprintf(fname, "%03d-%05d.WAV", dlg->nObj, curCmd->arg2);
				
				for (j = 0; dlg->_periods[j] != NULL; j++)
					if (dlg->_periodNums[j] == curCmd->arg2)
						break;
						
				if (dlg->_periods[j] == NULL)
					warning("ERROR: Dialog %d, Period %d not found!", (int)dlg->nObj, (int)curCmd->arg2);
				else {	
					frase = (char *)globalLock(dlg->_periods[j]);
					strcpy(copia, frase);
					globalUnlock(dlg->_periods[j]);

					while ((p = strchr(copia,'^')) != NULL)
						*p = '\"';

					p = frase;
					while (*p == ' ')
						p++;
					if (*p == '\0')
						continue;				

					v1->writeString(Common::String::format("%s\n", fname));
					f->writeString("\t<TR>\n");
					f->writeString(Common::String::format("\t\t<TD WIDTH=20%%> %s </TD>\n", fname));
					f->writeString(Common::String::format("\t\t<TD WIDTH = 13%%> <B> %s </B> </TD>\n", 
						getPersonName(dlg->nObj, curCmd->arg1)));
					f->writeString(Common::String::format("\t\t<TD> %s </TD>\n",copia));
					f->writeString("\t</TR>\n");
					//fprintf(f, "(%s) <%s> %s\n", fname, GetPersonName(dlg->nObj, curCmd->arg1), copia);
				}
			}
		}

		f->writeString("</TABLE><P>\n");
		//fprintf(f,"\n\n\n\n");
	}

	f->finalize();
	v1->finalize();
	delete f;
	delete v1;
}

void mpalDumpDialogs(void) {
	int i;

	lockDialogs();

	for (i = 0; i < GLOBALS.nDialogs; i++)
		mpalDumpDialog(&GLOBALS.lpmdDialogs[i]);

	unlockDialogs();
}

} // end of namespace MPAL

} // end of namespace Tony