File: Hordes.cpp

package info (click to toggle)
pose 3.5-7
  • links: PTS
  • area: contrib
  • in suites: sarge
  • size: 14,136 kB
  • ctags: 29,490
  • sloc: cpp: 93,990; ansic: 62,838; sh: 27,519; perl: 1,891; python: 1,242; makefile: 652
file content (2437 lines) | stat: -rw-r--r-- 60,046 bytes parent folder | download | duplicates (3)
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
/* -*- mode: C++; tab-width: 4 -*- */
/* ===================================================================== *\
	Copyright (c) 1999-2001 Palm, Inc. or its subsidiaries.
	All rights reserved.

	This file is part of the Palm OS Emulator.

	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.
\* ===================================================================== */

#include "EmCommon.h"
#include "Hordes.h"				// class Hordes

#include "CGremlins.h"			// Gremlins
#include "CGremlinsStubs.h"		// StubAppGremlinsOff
#include "EmApplication.h"		// ScheduleQuit
#include "EmEventPlayback.h"	// SaveEvents, LoadEvents, Clear, RecordEvents
#include "EmMapFile.h"			// EmMapFile::Write, etc.
#include "EmMinimize.h"			// EmMinimize::IsDone
#include "EmPatchState.h"		// EmPatchState::UIInitialized
#include "EmSession.h"			// gSession, ScheduleResumeHordesFromFile
#include "EmStreamFile.h"		// kCreateOrOpenForWrite
#include "ErrorHandling.h"		// Errors::ThrowIfPalmError
#include "Logging.h"			// LogStartNew, etc.
#include "Platform.h"			// Platform::GetMilliseconds
#include "PreferenceMgr.h"		// Preference, gEmuPrefs
#include "ROMStubs.h"			// EvtWakeup
#include "SessionFile.h"		// Chunk, EmStreamChunk
#include "Startup.h"			// HordeQuitWhenDone
#include "StringConversions.h"	// ToString, FromString;
#include "Strings.r.h"			// kStr_CmdOpen, etc.
#include "SystemMgr.h"			// sysGetROMVerMajor

#include <math.h>				// sqrt
#include <time.h>				// time, localtime

////////////////////////////////////////////////////////////////////////////////////////
// HORDES CONSTANTS

static const int	MAXGREMLINS	= 999;


////////////////////////////////////////////////////////////////////////////////////////
// HORDES STATIC DATA

static	Gremlins	gTheGremlin;
static	int32		gGremlinStartNumber;
static	int32		gGremlinStopNumber;
static	int32		gSwitchDepth;
static	int32		gMaxDepth;
		int32		gGremlinSaveFrequency;
DatabaseInfoList	gGremlinAppList;
static	int32		gCurrentGremlin;
static	int32		gCurrentDepth;
static	bool		gIsOn;
static	uint32		gStartTime;
static	uint32		gStopTime;
static	EmGremlinThreadInfo		gGremlinHaltedInError[MAXGREMLINS + 1];
static	EmDirRef	gHomeForHordesFiles;

static Bool			gForceNewHordesDirectory;
static EmDirRef		gGremlinDir;

Bool				gWarningHappened;
Bool				gErrorHappened;


////////////////////////////////////////////////////////////////////////////////////////
// HORDES METHODS

/***********************************************************************
 *
 * FUNCTION:	Hordes::Initialize
 *
 * DESCRIPTION: Standard initialization function.  Responsible for
 *				initializing this sub-system when a new session is
 *				created.  Will be followed by at least one call to
 *				Reset or Load.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void Hordes::Initialize (void)
{
	gTheGremlin.Reset ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Reset
 *
 * DESCRIPTION:	Standard reset function.  Sets the sub-system to a
 *				default state.  This occurs not only on a Reset (as
 *				from the menu item), but also when the sub-system
 *				is first initialized (Reset is called after Initialize)
 *				as well as when the system is re-loaded from an
 *				insufficient session file.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void Hordes::Reset (void)
{
	EmDlg::GremlinControlClose ();
	Hordes::Stop ();
	gTheGremlin.Reset ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Save
 *
 * DESCRIPTION:	Standard save function.  Saves any sub-system state to
 *				the given session file.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void Hordes::Save (SessionFile& f)
{
	gTheGremlin.Save (f);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Load
 *
 * DESCRIPTION:	Standard load function.  Loads any sub-system state
 *				from the given session file.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void Hordes::Load (SessionFile& f)
{
	Bool fHordesOn = gTheGremlin.Load (f);
	Hordes::TurnOn (fHordesOn);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Dispose
 *
 * DESCRIPTION:	Standard dispose function.  Completely release any
 *				resources acquired or allocated in Initialize and/or
 *				Load.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void Hordes::Dispose (void)
{
	gTheGremlin.Reset ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::New
 *
 * DESCRIPTION: Starts a new Horde of Gremlins
 *
 * PARAMETERS:	HordeInfo& info - Horde initialization info
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::New(const HordeInfo& info)
{
	gGremlinStartNumber	= min(info.fStartNumber, info.fStopNumber);
	gGremlinStopNumber	= max(info.fStartNumber, info.fStopNumber);
	
	if (info.fSwitchDepth == -1 || gGremlinStartNumber == gGremlinStopNumber)
		gSwitchDepth = info.fMaxDepth;

	else
		gSwitchDepth = info.fSwitchDepth;
	
	gMaxDepth				= info.fMaxDepth;
	gGremlinSaveFrequency	= info.fSaveFrequency;
	gGremlinAppList			= info.fAppList;
	gCurrentDepth			= 0;
	gCurrentGremlin			= gGremlinStartNumber;

	if (gSwitchDepth == 0)
		gSwitchDepth = -1;

	if (gMaxDepth == 0)
		gMaxDepth = -1;

	for (int counter = 0; counter <= MAXGREMLINS; counter++)
	{
		gGremlinHaltedInError[counter].fHalted		= false;
		gGremlinHaltedInError[counter].fErrorEvent	= 0;
		gGremlinHaltedInError[counter].fMessageID	= -1;
	}

	GremlinInfo gremInfo;
	
	gremInfo.fNumber		= gCurrentGremlin;
	gremInfo.fSaveFrequency	= gGremlinSaveFrequency;
	gremInfo.fSteps			= (gMaxDepth == -1) ? gSwitchDepth : min (gSwitchDepth, gMaxDepth);
	gremInfo.fAppList		= gGremlinAppList;
	gremInfo.fFinal			= gMaxDepth;

	gStartTime = Platform::GetMilliseconds ();

	gTheGremlin.New (gremInfo);

	EmDlg::GremlinControlOpen ();

	Hordes::UseNewAutoSaveDirectory ();

	EmEventPlayback::Clear ();

	// When we save our root state, we want it to be saved with all
	// the correct GremlinInfo (per the 2.0 file format) but with
	// Gremlins turned OFF.

	Hordes::TurnOn (false);

	Hordes::SaveRootState ();

	Hordes::TurnOn (true);

	Hordes::StartLog ();

	LogAppendMsg ("New Gremlin #%ld started anew to %ld events",
					gremInfo.fNumber, gremInfo.fSteps);

	LogDump ();

	gWarningHappened	= false;
	gErrorHappened		= false;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::NewGremlin
 *
 * DESCRIPTION: Starts a new Horde of just one Gremlin --
 *				"classic Gremlins"
 *
 * PARAMETERS:	GremlinInfo& info - Gremlin initialization info
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::NewGremlin (const GremlinInfo &info)
{
	HordeInfo newHorde;

	newHorde.fStartNumber	= info.fNumber;
	newHorde.fStopNumber	= info.fNumber;
	newHorde.fSwitchDepth	= info.fSteps;
	newHorde.fMaxDepth		= info.fSteps;
	newHorde.fSaveFrequency	= info.fSaveFrequency;
	newHorde.fAppList		= info.fAppList;
	
	Hordes::New (newHorde);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Status
 *
 * DESCRIPTION: Returns several pieces of status information about the
 *				currently running Gremlin in the Horde.
 *
 * PARAMETERS:	currentNumber - returns the current Gremlin number.
 *				currentStep - returns the current event number of the
 *					currently running Gremlin
 *				currentUntil - returns the current upper event bound of
 *					currently running Gremlin
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::Status (unsigned short *currentNumber, unsigned long *currentStep,
				unsigned long *currentUntil)
{
	gTheGremlin.Status (currentNumber, currentStep, currentUntil);
}


string
Hordes::GremlinsFlagsToString (void)
{
	string output;

	for (int ii = 0; ii < MAXGREMLINS; ++ii)
	{
		gGremlinHaltedInError[ii].fHalted ? output += "1" : output += "0";
	}

	return output;
}

void
Hordes::GremlinsFlagsFromString(string& inFlags)
{
	for (int ii = 0; ii < MAXGREMLINS; ++ii)
	{
		gGremlinHaltedInError[ii].fHalted = (inFlags.c_str()[ii] == '1');
	}
}

void
Hordes::SaveSearchProgress()
{
	StringStringMap	searchProgress;

	searchProgress["gGremlinStartNumber"]	= ::ToString (gGremlinStartNumber);
	searchProgress["gGremlinStopNumber"]	= ::ToString (gGremlinStopNumber);
	searchProgress["gSwitchDepth"]			= ::ToString (gSwitchDepth);
	searchProgress["gMaxDepth"]				= ::ToString (gMaxDepth);
	searchProgress["gGremlinSaveFrequency"]	= ::ToString (gGremlinSaveFrequency);
	searchProgress["gCurrentGremlin"]		= ::ToString (gCurrentGremlin);
	searchProgress["gCurrentDepth"]			= ::ToString (gCurrentDepth);
	searchProgress["gGremlinHaltedInError"]	= Hordes::GremlinsFlagsToString ();
	searchProgress["gStartTime"]			= ::ToString (gStartTime);
	searchProgress["gStopTime"]				= ::ToString (gStopTime);

	EmFileRef	searchFile = Hordes::SuggestFileRef (kHordeProgressFile);

	EmMapFile::Write (searchFile, searchProgress);
}


void
Hordes::ResumeSearchProgress (const EmFileRef& f)
{
	StringStringMap	searchProgress;

	EmMapFile::Read (f, searchProgress);

	::FromString (searchProgress["gGremlinStartNumber"],	gGremlinStartNumber);
	::FromString (searchProgress["gGremlinStopNumber"],		gGremlinStopNumber);
	::FromString (searchProgress["gSwitchDepth"],			gSwitchDepth);
	::FromString (searchProgress["gMaxDepth"],				gMaxDepth);
	::FromString (searchProgress["gGremlinSaveFrequency"],	gGremlinSaveFrequency);
	::FromString (searchProgress["gCurrentGremlin"],		gCurrentGremlin);
	::FromString (searchProgress["gCurrentDepth"],			gCurrentDepth);

	Hordes::GremlinsFlagsFromString (searchProgress["gGremlinHaltedInError"]);

	// Get, then patch up start and stop times.

	::FromString (searchProgress["gStartTime"],				gStartTime);
	::FromString (searchProgress["gStopTime"],				gStopTime);

	uint32	delta = gStopTime - gStartTime;
	gStopTime	= Platform::GetMilliseconds ();
	gStartTime	= gStopTime - delta;

//	gSession->ScheduleResumeHordesFromFile ();
}

Bool
Hordes::IsOn (void)
{
	return gIsOn;
}

Bool
Hordes::InSingleGremlinMode (void)
{
	return gGremlinStartNumber == gGremlinStopNumber;
}


Bool
Hordes::QuitWhenDone (void)
{
	if (Startup::HordeQuitWhenDone ())
		return true;

	return false;
}


Bool
Hordes::CanNew (void)
{
	return !EmMinimize::IsOn () && EmPatchState::UIInitialized ();
}


Bool
Hordes::CanSuspend (void)
{
	return !EmMinimize::IsOn ();
}


Bool
Hordes::CanStep (void)
{
	return (gTheGremlin.IsInitialized () && !gIsOn && !EmMinimize::IsOn ());
}


Bool
Hordes::CanResume (void)
{
	return (gTheGremlin.IsInitialized () && !gIsOn && !EmMinimize::IsOn ());
}


Bool
Hordes::CanStop (void)
{
	return (gIsOn && !EmMinimize::IsOn ());
}


int32
Hordes::GremlinNumber (void)
{
	return gCurrentGremlin;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::TurnOn
 *
 * DESCRIPTION: Turns Hordes on or off.
 *
 * PARAMETERS:	fHordesOn - specifies if Hordes should be on or off.
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::TurnOn (Bool hordesOn)
{
	gIsOn = (hordesOn != false);
	EmEventPlayback::RecordEvents (gIsOn);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::EventCounter
 *
 * DESCRIPTION: Returns the current event count of the currently running
 *				Gremlin
 *
 * PARAMETERS:	none
 *
 * RETURNED:	event count
 *
 ***********************************************************************/

int32
Hordes::EventCounter (void)
{
	unsigned short	number;
	unsigned long	step;
	unsigned long	until;

	Hordes::Status (&number, &step, &until);

	return step;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::EventLimit
 *
 * DESCRIPTION: Returns the current event limit of the currently running
 *				Gremlin
 *
 * PARAMETERS:	none
 *
 * RETURNED:	event limit
 *
 ***********************************************************************/

int32
Hordes::EventLimit(void)
{
	unsigned short	number;
	unsigned long	step;
	unsigned long	until;

	Hordes::Status (&number, &step, &until);

	return until;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::EndHordes
 *
 * DESCRIPTION: Ends Hordes, giving back control to user.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::EndHordes (void)
{
	// In an odd twist, logging doesn't work if Hordes is supposedly
	// turned off. So let's spoof that it's on; it will be turned off --
	// again -- below, when Hordes::Stop() is called.

	Hordes::TurnOn (true);

	if (!Hordes::InSingleGremlinMode ())
	{
		LogAppendMsg ("*************   Gremlin Horde ended at Gremlin #%ld\n", gGremlinStopNumber);
	}

	// It's time to print out some basic info:
	//	ROM version
	//	ROM file name
	//	Device name
	//	RAM size

	UInt32 romVersionData;
	::FtrGet (sysFileCSystem, sysFtrNumROMVersion, &romVersionData);

	UInt32 romVersionMajor = sysGetROMVerMajor (romVersionData);
	UInt32 romVersionMinor = sysGetROMVerMinor (romVersionData);

	Preference<Configuration>	pref (kPrefKeyLastConfiguration);
	Preference<EmFileRef>		pref2 (kPrefKeyLastPSF);

	Configuration	cfg				= *pref;
	EmDevice		device			= cfg.fDevice;
	string			deviceStr		= device.GetIDString ();
	RAMSizeType		ramSize			= cfg.fRAMSize;
	EmFileRef		romFile			= cfg.fROMFile;
	string			romFileStr		= romFile.GetFullPath ();
	EmFileRef		sessionFile		= *pref2;
	string			sessionFileStr	= sessionFile.GetFullPath ();

	if (sessionFileStr.empty ())
	{
		sessionFileStr = "<Not selected>";
	}

	LogAppendMsg ("*************   Device Info:");
	LogAppendMsg ("ROM version:             %d.%d", romVersionMajor, romVersionMinor);
	LogAppendMsg ("ROM file name:           %s", (char *) romFileStr.c_str ());
	LogAppendMsg ("Session file:			%s", (char *) sessionFileStr.c_str ());
	LogAppendMsg ("Device name:             %s", (char *) deviceStr.c_str ());
	LogAppendMsg ("RAM size:                %d KB\n", (long) ramSize);

	// Let's come up with some statistics from our new field in 
	// gGremlinHaltedInError.

	int32 min, max, avg, stdDev, smallErrorIndex;
	Hordes::ComputeStatistics (min, max, avg, stdDev, smallErrorIndex);

	LogAppendMsg ("*************   Error Occurrence Statistics:");
	LogAppendMsg ("");

	Hordes::GremlinReport ();

	// check for the sentinel value

	if (smallErrorIndex != 0x7FFFFFFF)
	{
		LogAppendMsg ("");
		LogAppendMsg ("Minimum Event:            %d", min);
		LogAppendMsg ("Maximum Event:            %d", max);
		LogAppendMsg ("Average Event:            %d", avg);
		LogAppendMsg ("Standard Deviation:       %d", stdDev);
		LogAppendMsg ("Overall Shortest Gremlin: #%d\n", smallErrorIndex);
	}
	else
	{
		LogAppendMsg ("No Gremlins found errors.\n");
	}

	LogDump ();

	Hordes::TurnOn (false);

	LogClear();
	EmEventPlayback::Clear ();

	if (!Hordes::InSingleGremlinMode ())
	{
		EmDlg::GremlinControlClose ();

		EmAssert (gSession);
		gSession->ScheduleLoadRootState ();
	}

	if (Hordes::QuitWhenDone ())
	{
		EmAssert (gApplication);
		gApplication->ScheduleQuit ();
	}
	else
	{
		gWarningHappened	= false;
		gErrorHappened		= false;
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::ProposeNextGremlin
 *
 * DESCRIPTION: Proposes the NEXT Gremlin # and corresponding search
 *				depth, FROM the state of the Hordes run specified by the
 *				input paramaters
 *
 * PARAMETERS:	outNextGremlin - passes back suggested next Gremlin
 *				outNextDepth - passes back next depth
 *				inFromGremlin - "current" Gremlin
 *				inFromGremlin - "current" depth
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::ProposeNextGremlin (long& outNextGremlin, long& outNextDepth,
							long inFromGremlin, long inFromDepth)
{
	outNextGremlin	= inFromGremlin + 1;
	outNextDepth	= inFromDepth;

	if (outNextGremlin == gGremlinStopNumber + 1)
	{
		outNextGremlin = gGremlinStartNumber;

		if (outNextDepth >= 0)
			++outNextDepth;
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::StartGremlinFromLoadedRootState
 *
 * DESCRIPTION: After the CPU loads the root state during an off-cycle,
 *				it calls this to indicate that Hordes is meant to start
 *				the current Gremlin, and that the Emulator state is ready
 *				for this.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::StartGremlinFromLoadedRootState (void)
{
	GremlinInfo gremInfo;

	gremInfo.fNumber		= gCurrentGremlin;
	gremInfo.fSaveFrequency	= gGremlinSaveFrequency;
	gremInfo.fSteps			= ((gMaxDepth == -1) ? gSwitchDepth : min(gSwitchDepth, gMaxDepth));
	gremInfo.fAppList		= gGremlinAppList;
	gremInfo.fFinal			= gMaxDepth;

	gTheGremlin.New (gremInfo);

	LogAppendMsg ("New Gremlin #%ld started from root state to %ld events",
					gCurrentGremlin, gremInfo.fSteps);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::StartGremlinFromLoadedSuspendedState
 *
 * DESCRIPTION: After the CPU loads the suspended state during an off-cycle,
 *				it calls this to indicate that Hordes is meant to resume
 *				the current Gremlin, and that the Emulator state is ready
 *				for this.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::StartGremlinFromLoadedSuspendedState (void)
{
	// We reset the Gremlin to go until the next occurence of the
	// depth-bound, or until gMaxDepth, whichever occurs first.

	long newUntil = gSwitchDepth * (gCurrentDepth + 1);

	if (gMaxDepth != -1)
	{
		newUntil = min (newUntil, gMaxDepth);
	}

	gTheGremlin.SetUntil (newUntil);

	LogAppendMsg("Resuming Gremlin #%ld to #%ld events",
		gCurrentGremlin, newUntil);

	Hordes::TurnOn(true);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SetGremlinStatePathFromControlFile
 *
 * DESCRIPTION:	Given the file reference to a control file (actually *any*
 *				file in the Gremlins state path), set the Gremlins state
 *				path to the directory that contains this file.
 *
 * PARAMETERS:	controlFile - reference to the rootStateFile.
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void
Hordes::SetGremlinStatePathFromControlFile (EmFileRef& controlFile)
{
	gGremlinDir = controlFile.GetParent ();
	gForceNewHordesDirectory = false;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::NextGremlin
 *
 * DESCRIPTION: Selects and runs the next Gremlin in the Horde, if there
 *				are unfinished Gremlins left. Otherwise, just loads
 *				the pre-Horde state and stops.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::NextGremlin (void)
{
	Hordes::Stop ();

	Hordes::SaveSearchProgress ();

	// Find the next Gremlin to run.

	long nextGremlin, nextDepth;
	
	// Keep looking until we find a Gremlin in the range which has
	// not halted in error.

	Hordes::ProposeNextGremlin (nextGremlin, nextDepth, gCurrentGremlin, gCurrentDepth);
	
	while (gGremlinHaltedInError[nextGremlin].fHalted) 
	{
		// All Gremlins halted in error when we are back at the current
		// Gremlin at the next depth. (We looped around without finding
		// the next Gremlin that didn't halt in error).

		if (nextGremlin == gCurrentGremlin && nextDepth >= gCurrentDepth + 1)
		{
			Hordes::EndHordes ();
			return;
		}

		Hordes::ProposeNextGremlin (nextGremlin, nextDepth, nextGremlin, nextDepth);
	}

	// Update our current location in the Gremlin search tree.

	gCurrentGremlin	= nextGremlin;
	gCurrentDepth	= nextDepth;

	// All the Gremlins have reached gMaxDepth when the depth exceeds the
	// depth necessary to reach gMaxDepth. Special case for
	// gMaxDepth = forever.

	if ( gMaxDepth != -1 &&
		( (gCurrentDepth > gMaxDepth / gSwitchDepth) ||
		  ( (gCurrentDepth == gMaxDepth / gSwitchDepth) && (gMaxDepth % gSwitchDepth == 0) ) ) )
	{
		Hordes::EndHordes();
		return;
	}

	// If the current depth is 0, we start at the root state.

	if (gCurrentDepth == 0)
	{
		EmAssert (gSession);
		gSession->ScheduleNextGremlinFromRootState ();
	}

	// Otherwise, we load the suspended state, which is where we begin to
	// resume the Gremlin

	else
	{
		EmAssert (gSession);
		gSession->ScheduleNextGremlinFromSuspendedState ();
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::ErrorEncountered
 *
 * DESCRIPTION: Called when an error condition has been encountered.
 *				This function saves the current state and starts in
 *				motion the machinery to start the next Gremlin in the
 *				Horde.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::ErrorEncountered (void)
{
	int32	errorGremlin	= Hordes::GremlinNumber ();
	int32	errorEvent		= Hordes::EventCounter () - 1;

	Hordes::AutoSaveState ();

	LogAppendMsg ("=== ERROR: Gremlin #%ld terminated in error at event #%ld\n",
		errorGremlin, errorEvent);

	LogDump ();

	// This is a fatal error; stop the execution of this Gremlin.

	gGremlinHaltedInError[errorGremlin].fHalted = true;

	// Save the events, now that it's terminated with an error event.

	Hordes::SaveEvents ();

	// Move to the next Gremlin.

//	if (!Hordes::InSingleGremlinMode ())
	{
		Hordes::NextGremlin ();
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::RecordErrorStats
 *
 * DESCRIPTION: Called when an error message needs to be displayed,
 *				either as a result of a hardware exception, an error
 *				condition detected by Poser, or the Palm application
 *				calling SysFatalAlert.  If appropriate, log the error
 *				message.
 *
 * PARAMETERS:	messageID - ID indicating what error occurred.  We pass
 *					that into here so that we can keep stats on the kinds
 *					of errors generated.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::RecordErrorStats (StrCode messageID)
{
	if (Hordes::IsOn ())
	{
		// Update our gGremlinHaltedInError info if it was passed, and if
		// we haven't already assigned an error to this Gremlin. (This is
		// so that the first error, of possibly many if we are continuing
		// on errors, is the one that shows up in the statistics.)

		int32	errorGremlin	= Hordes::GremlinNumber();
		int32	errorEvent		= Hordes::EventCounter () - 1;

		// Only update this if we haven't already logged an error event for the first
		// error

		Bool firstErrForGremlin = gGremlinHaltedInError[errorGremlin].fMessageID == -1;

		if (firstErrForGremlin)
		{
			gGremlinHaltedInError[errorGremlin].fErrorEvent = errorEvent;

			// Now update the message id if a valid one was passed

			if (messageID != -1)
			{
				gGremlinHaltedInError[errorGremlin].fMessageID = (long) messageID;
			}
		}

		// Tell Minimization that a warning or error occurred.
		//
		// Do we ever get here?  RecordErrorStats is called from Errors::DoDialog.
		// Errors::DoDialog is called from Errors::HandleDialog, which calls
		// EmMinimize::ErrorOccurred and returns before calling Errors::DoDialog
		// if minimization is turned on.

		if (EmMinimize::IsOn ())
		{
			EmAssert (false);	// See if we get here.

			LogAppendMsg ("Calling EmMinimize::ErrorOccurred from Hordes::RecordErrorStats");
			EmMinimize::ErrorOccurred ();
		}
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::StopEventReached
 *
 * DESCRIPTION: Message to Hordes indicating that a Gremlin has
 *				completed its last event. Saves a suspended state if
 *				we intend to resume this Gremlin in the future.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::StopEventReached()
{
	int32	gremlinNumber	= Hordes::GremlinNumber ();
	int32	stopEventNumber	= Hordes::EventLimit ();

	LogAppendMsg ("Gremlin #%ld finished successfully to event #%ld",
					gremlinNumber, stopEventNumber);

	if (stopEventNumber == gMaxDepth)
	{
//		LogAppendMsg ("********************************************************************************");
		LogAppendMsg ("*************   Gremlin #%ld successfully completed", gremlinNumber);
//		LogAppendMsg ("********************************************************************************");
	}

	LogDump ();

	// Save the events of the successful run.

	Hordes::SaveEvents ();

	// Move to the next Gremlin.

	Hordes::NextGremlin ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Suspend
 *
 * DESCRIPTION: Suspends the currently running Gremlin.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::Suspend()
{
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Step
 *
 * DESCRIPTION: "Steps" the currently running Gremlin.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::Step()
{
	if (!gIsOn)
	{
		Hordes::TurnOn (true);

		// Spoof info to look as if this was a single Gremlin run. This way,
		// stepping will work; if this is not done, then the next Gremlin is
		// launched, just as if a switching barrier was reached.

		gCurrentDepth = gMaxDepth;
		gGremlinStartNumber = gGremlinStopNumber = gCurrentGremlin;

		gTheGremlin.Step ();

		// Make sure the app's awake.  Normally, we post events on a patch to
		// SysEvGroupWait.  However, if the Palm device is already waiting,
		// then that trap will never get called.  By calling EvtWakeup now,
		// we'll wake up the Palm device from its nap.

		Errors::ThrowIfPalmError (EvtWakeup ());
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Resume
 *
 * DESCRIPTION: Resumes the currently suspended Gremlin.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::Resume()
{
	if (!Hordes::IsOn ())
	{
		Hordes::TurnOn (true);
		
		gStartTime = Platform::GetMilliseconds () - (gStopTime - gStartTime);

		gTheGremlin.RestoreFinalUntil ();

		gTheGremlin.Resume ();
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::Stop
 *
 * DESCRIPTION: Suspends the currently running Gremlin.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::Stop (void)
{
	gStopTime = Platform::GetMilliseconds ();

	StubAppGremlinsOff ();

	gTheGremlin.Stop ();
}


/*****************************************************************************
 *
 * FUNCTION:	Hordes::SuggestFileName
 *
 * DESCRIPTION: This function is responsible for deciding about the names of
 *				files that are created during a horde run.  The file names 
 *				are assigned based on the requested file category. Some 
 *				file categories use gremlins data (event number, gremlin 
 *				number) to construct a unique file name.  The following 
 *				categories are used by the "Horde" class:
 *
 *					kHordeProgressFile
 *					kHordeRootFile
 *					kHordeSuspendFile
 *					kHordeAutoCurrentFile
 *
 *					kHordeSuspendFile	-	last file in a gremlin thread
 *
 * PARAMETERS:	file category
 *
 * RETURNED:	file name or an empty string when the input category is
 *				incorrect
 *
 *****************************************************************************/

string Hordes::SuggestFileName (HordeFileType category, uint32 num)
{
	static const char kStrSearchProgressFile[]	= "Gremlin_Search_Progress.dat";
	static const char kStrRootStateFile[]		= "Gremlin_Root_State.psf";
	static const char kStrSuspendedStateFile[]	= "Gremlin_%03ld_Suspended.psf";
	static const char kStrAutoSaveFile[]		= "Gremlin_%03ld_Event_%08ld.psf";
	static const char kStrEventFile[]			= "Gremlin_%03ld_Events.pev";
	static const char kStrMinimalEventFile []	= "Gremlin_%03ld_Interim_Event_File_%08ld.pev";

	char fileName[64];

	int32	gremlinNumber;
	int32	eventCounter;
	uint32	time;

	switch (category)
	{
		case kHordeProgressFile:

			strcpy (fileName, kStrSearchProgressFile);
			break;

		case kHordeRootFile:

			strcpy (fileName, kStrRootStateFile);
			break;

		case kHordeSuspendFile:

			gremlinNumber = Hordes::GremlinNumber ();
			sprintf (fileName, kStrSuspendedStateFile, gremlinNumber);
			break;

		case kHordeAutoCurrentFile:

			gremlinNumber = Hordes::GremlinNumber ();
			eventCounter = Hordes::EventCounter ();

			if (gGremlinSaveFrequency == 0)
			{
				sprintf (fileName, kStrAutoSaveFile, gremlinNumber, eventCounter);
			}
			else
			{
				eventCounter = (eventCounter / gGremlinSaveFrequency) * gGremlinSaveFrequency;
				sprintf (fileName, kStrAutoSaveFile, gremlinNumber, eventCounter);
			}
			break;

		case kHordeEventFile:

			gremlinNumber = Hordes::GremlinNumber ();
			sprintf (fileName, kStrEventFile, gremlinNumber);
			break;

		case kHordeMinimalEventFile:

			gremlinNumber = num;
			time = Platform::GetMilliseconds ();
			sprintf (fileName, kStrMinimalEventFile, gremlinNumber, time);
			break;

		default:

			*fileName = '\0';
			break;
	};

	return string (fileName);
}


/*****************************************************************************
 *
 * FUNCTION:	Hordes::SuggestFileRef
 *
 * DESCRIPTION: This function is responsible for deciding about the names of
 *				files that are created during a horde run.  The file names 
 *				are assigned based on the requested file category. Some 
 *				file categories use gremlins data (event number, gremlin 
 *				number) to construct a unique file name.  The following 
 *				categories are used by the "Horde" class:
 *
 *					kHordeProgressFile
 *					kHordeRootFile
 *					kHordeSuspendFile
 *					kHordeAutoCurrentFile
 *
 *					kHordeSuspendFile	-	last file in a gremlin thread
 *
 * PARAMETERS:	file category
 *
 * RETURNED:	file ref
 *
 *****************************************************************************/

EmFileRef Hordes::SuggestFileRef (HordeFileType category, uint32 num)
{
	EmFileRef	fileRef (
		Hordes::GetGremlinDirectory (),
		Hordes::SuggestFileName (category, num));

	return fileRef;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::PostLoad
 *
 * DESCRIPTION: Initializes a load that has taken place outside the
 *				control of the Hordes subsystem. For example, if the user
 *				has opened a session file manually. This is to set the
 *				Hordes state to play the Gremlin in the file as a "horde
 *				of one."
 *
 * PARAMETERS:	f - SessionFile to load from
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::PostLoad (void)
{
	// We can't just call NewGremlin with the GremlinInfo because
	// gTheGremlin.Load() has already restored the state of the Gremlin,
	// so we should not call gTheGremlin.New() on it.

	Preference<GremlinInfo>	pref (kPrefKeyGremlinInfo);
	GremlinInfo info = *pref;

	gGremlinStartNumber		= info.fNumber;
	gGremlinStopNumber		= info.fNumber;
	gCurrentGremlin			= info.fNumber;
	gSwitchDepth			= info.fSteps;
	gMaxDepth				= info.fSteps;
	gGremlinSaveFrequency	= info.fSaveFrequency;
	gGremlinAppList			= info.fAppList;
	gCurrentDepth			= 0;

	gStartTime	= gTheGremlin.GetStartTime ();
	gStopTime	= gTheGremlin.GetStopTime ();

	if (Hordes::IsOn())
	{
		Hordes::UseNewAutoSaveDirectory ();

		EmAssert (gSession);
		gSession->ScheduleSaveRootState ();
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::PostFakeEvent
 *
 * DESCRIPTION: Posts a fake event through the currently running Gremlin.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	TRUE if a key or point was enqueued, FALSE otherwise.
 *
 ***********************************************************************/

Bool
Hordes::PostFakeEvent (void)
{
	// check to see if the Gremlin has produced its max # of "events."

	if (Hordes::EventLimit() > 0 && Hordes::EventCounter () > Hordes::EventLimit ())
	{
		Hordes::StopEventReached ();
		return false;
	}

	Bool result = gTheGremlin.GetFakeEvent ();

	Hordes::BumpCounter ();

	return result;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::PostFakePenEvent
 *
 * DESCRIPTION: Posts a phony pen movement to through the currently
 *				running Gremlin
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::PostFakePenEvent (void)
{
	Hordes::BumpCounter ();
	gTheGremlin.GetPenMovement ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SendCharsToType
 *
 * DESCRIPTION: Send a char to the Emulator if any are pending for the
 *				currently running Gremlin
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

Bool
Hordes::SendCharsToType (void)
{
	return gTheGremlin.SendCharsToType ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::ElapsedMilliseconds
 *
 * DESCRIPTION: Returns the elapsed time of the Horde
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

uint32
Hordes::ElapsedMilliseconds (void)
{
	if (gIsOn)
		return Platform::GetMilliseconds () - gStartTime;

	return gStopTime - gStartTime;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::BumpCounter
 *
 * DESCRIPTION: Bumps event counter of the currently running Gremlin
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::BumpCounter (void)
{
	gTheGremlin.BumpCounter ();

	if (gGremlinSaveFrequency != 0 &&
		(Hordes::EventCounter () % gGremlinSaveFrequency) == 0)
	{
		EmAssert (gSession);
		gSession->ScheduleAutoSaveState ();
	}

	if (Hordes::EventLimit () > 0 &&
		Hordes::EventLimit () == Hordes::EventCounter ())
	{	
		EmAssert (gSession);
		gSession->ScheduleSaveSuspendedState ();
	}
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::CanSwitchToApp
 *
 * DESCRIPTION: Returns whether the Horde can switch to the given Palm
 *				app
 *
 * PARAMETERS:	cardNo   \ Palm application info
 *				dbID     /
 *
 * RETURNED:	TRUE if the designated Palm app can be run by the Horde
 *				FALSE otherwise
 *
 ***********************************************************************/

Bool
Hordes::CanSwitchToApp (UInt16 cardNo, LocalID dbID)
{
	if (gGremlinAppList.size () == 0)
		return true;

	DatabaseInfoList			appList = Hordes::GetAppList ();
	DatabaseInfoList::iterator	iter = appList.begin ();

	while (iter != appList.end ())
	{
		DatabaseInfo&	dbInfo = *iter++;

		if (dbInfo.cardNo == cardNo && dbInfo.dbID == dbID)
			return true;
	}

	return false;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SetGremlinsHome
 *
 * DESCRIPTION: Indicates the directory in which the user would like
 *				his Horde files to collect.
 *
 * PARAMETERS:	gremlinsHome - the name of the directory
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::SetGremlinsHome (const EmDirRef& gremlinsHome)
{
	gHomeForHordesFiles = gremlinsHome;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SetGremlinsHomeToDefault
 *
 * DESCRIPTION: Indicates that the user would like his Horde files to
 *				collect in the default location.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::SetGremlinsHomeToDefault (void)
{
	gHomeForHordesFiles = EmDirRef ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::GetGremlinsHome
 *
 * DESCRIPTION: Returns the directory that the user would like to house
 *				his Horde state files.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	TRUE if gHomeForHordesFiles is defined;
 *				FALSE otherwise (use default).
 *
 ***********************************************************************/

Bool
Hordes::GetGremlinsHome (EmDirRef& outPath)
{
	// If we don't have anything, default to Poser home.

	outPath = gHomeForHordesFiles;

	// Try to create the path if it doesn't exist.

	if (!gHomeForHordesFiles.Exists ())
	{
		gHomeForHordesFiles.Create ();
	}

	// Return whether or not we succeeded.

	return gHomeForHordesFiles.Exists ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::AutoSaveState
 *
 * DESCRIPTION: Creates a file reference to where the auto-saved state
 *				should be saved.  Then calls a platform-specific
 *				routine to do the actual saving.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::AutoSaveState (void)
{
	EmFileRef	fileRef = Hordes::SuggestFileRef (kHordeAutoCurrentFile);

	EmAssert (gSession);
	gSession->Save (fileRef, false);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SaveRootState
 *
 * DESCRIPTION: Creates a file reference to where the state
 *				should be saved.  Then calls a platform-specific
 *				routine to do the actual saving.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::SaveRootState (void)
{
	EmFileRef	fileRef = Hordes::SuggestFileRef (kHordeRootFile);

	Bool hordesWasOn = Hordes::IsOn ();

	if (hordesWasOn != false)
		Hordes::TurnOn (false);

	EmAssert (gSession);
	gSession->Save (fileRef, false);

	Hordes::TurnOn (hordesWasOn);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::LoadState
 *
 * DESCRIPTION: Does the work of loading a state while Hordes is running.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

ErrCode
Hordes::LoadState (const EmFileRef& ref)
{
	ErrCode returnedErrCode = errNone;

	try
	{
		EmAssert (gSession);
		gSession->Load (ref);
	}
	catch (ErrCode errCode)
	{
		Hordes::TurnOn (false);

		Errors::SetParameter ("%filename", ref.GetName ());
		Errors::ReportIfError (kStr_CmdOpen, errCode, 0, true);

		returnedErrCode = errCode;
	}

	return returnedErrCode;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::LoadRootState
 *
 * DESCRIPTION: Creates a file reference to where the root state
 *				should be loaded.  Then calls a
 *				routine to do the actual loading.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

ErrCode
Hordes::LoadRootState (void)
{
	EmFileRef	fileRef = Hordes::SuggestFileRef (kHordeRootFile);

	ErrCode		result = Hordes::LoadState (fileRef);

	if (result == 0)
	{
		// There are no events to load, but we need to make sure we at
		// least clear out any old events.

		EmEventPlayback::Clear ();
	}

	return result;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SaveSuspendedState
 *
 * DESCRIPTION: Creates a file reference to where the suspended state
 *				should be saved.  Then calls a platform-specific
 *				routine to do the actual saving.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::SaveSuspendedState (void)
{
	EmFileRef	fileRef = Hordes::SuggestFileRef (kHordeSuspendFile);

	gSession->Save (fileRef, false);

	// This sort of overloads the function, but right now, any time we
	// save the suspend state, we also want to save any recorded events.

	Hordes::SaveEvents ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::LoadSuspendedState
 *
 * DESCRIPTION: Creates a file reference to where the suspended state
 *				should be loaded.  Then calls a	routine to do the actual
 *				loading.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

ErrCode
Hordes::LoadSuspendedState (void)
{
	EmFileRef	fileRef = Hordes::SuggestFileRef (kHordeSuspendFile);

	ErrCode		result = Hordes::LoadState (fileRef);

	if (result == 0)
	{
		// Load the events from the associated file holding them.  Do this
		// *after* Hordes::LoadState, as gSession->Load will try to load
		// events from *its* file, overwriting the ones in our holding file.
		//
		// Note also that we load events in LoadSuspendedState but not
		// LoadRootState, as there should not be any events associated
		// with the root state (none have been generated!).

		Hordes::LoadEvents ();
	}

	return result;
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::SaveEvents
 *
 * DESCRIPTION: Write out the current set of events to the designated
 *				event file.  This file contains the root (initial)
 *				Gremlin state, to which we append the events.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::SaveEvents (void)
{
	EmFileRef		eventRef = Hordes::SuggestFileRef (kHordeEventFile);

	EmStreamFile	eventStream (eventRef, kCreateOrEraseForWrite,
						kFileCreatorEmulator, kFileTypeEvents);
	ChunkFile		eventChunkFile (eventStream);
	SessionFile		eventSessionFile (eventChunkFile);

	// Copy over the root state to the session file, first.

	EmFileRef		rootRef = Hordes::SuggestFileRef (kHordeRootFile);
	EmStreamFile	rootStream (rootRef, kOpenExistingForRead,
						kFileCreatorEmulator, kFileTypeEvents);

	{
		int32		length = rootStream.GetLength ();
		ByteList	buffer (length);
		rootStream.GetBytes (&buffer[0], length);
		eventStream.PutBytes (&buffer[0], length);
	}

	// Finally, write the events to the file.

	EmEventPlayback::SaveEvents (eventSessionFile);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::LoadEvents
 *
 * DESCRIPTION: Load the events from the current event file.
 *
 * PARAMETERS:	None.
 *
 * RETURNED:	Nothing.
 *
 ***********************************************************************/

void
Hordes::LoadEvents (void)
{
	EmFileRef		eventRef = Hordes::SuggestFileRef (kHordeEventFile);

	EmStreamFile	stream (eventRef, kOpenExistingForRead,
						kFileCreatorEmulator, kFileTypeEvents);
	ChunkFile		chunkFile (stream);
	SessionFile		eventFile (chunkFile);

	EmEventPlayback::LoadEvents (eventFile);
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::StartLog
 *
 * DESCRIPTION: Starts Hordes logging
 *
 * PARAMETERS:	none
 *
 * RETURNED:	none
 *
 ***********************************************************************/

void
Hordes::StartLog (void)
{
	LogClear ();
	LogStartNew ();

	LogAppendMsg ("********************************************************************************");
	LogAppendMsg ("*************   Gremlin Hordes started");
	LogAppendMsg ("********************************************************************************");
	LogAppendMsg ("Running Gremlins %ld to %ld", gGremlinStartNumber, gGremlinStopNumber);

	if (gSwitchDepth != -1)
		LogAppendMsg ("Will run each Gremlin %ld events at a time until all Gremlins have terminated in error", gSwitchDepth);

	else
		LogAppendMsg ("Will run each Gremlin until all Gremlins have terminated in error", gSwitchDepth);

	if (gMaxDepth != -1)
		LogAppendMsg ("or have reached a maximum of %ld events", gMaxDepth);

	LogAppendMsg ("********************************************************************************");

	LogDump ();
}


/***********************************************************************
 *
 * FUNCTION:	Hordes::GetGremlinDirectory
 *
 * DESCRIPTION:	Return an EmDirRef for directory where information
 *				about the current Gremlin is saved.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	The desired EmDirRef.
 *
 ***********************************************************************/

EmDirRef
Hordes::GetGremlinDirectory (void)
{
	// If requested, create the directory to use.

	if (gForceNewHordesDirectory)
	{
		gForceNewHordesDirectory = false;

		time_t		now_time;
		time (&now_time);
		struct tm*	now_tm = localtime (&now_time);

		char buffer[30];
		strftime (buffer, countof (buffer), "%Y-%m-%d.%H-%M-%S", now_tm);	// 19 chars + NULL

		char	stateName[30];
		sprintf (stateName, "Gremlins.%s", buffer);

		EmAssert (strlen(stateName) <= 31);	// Max on Macs

		EmDirRef	homeDir;

		if (!Hordes::GetGremlinsHome (homeDir))
		{
			homeDir = EmDirRef::GetEmulatorDirectory ();
		}

		gGremlinDir = EmDirRef (homeDir, stateName);

		if (!gGremlinDir.Exists ())
		{
			try
			{
				gGremlinDir.Create ();
			}
			catch (...)
			{
				// !!! Put up some error message

				gGremlinDir = EmDirRef ();
			}
		}
	}

	// Otherwise, return the previously specified directory.

	return gGremlinDir;
}


// ---------------------------------------------------------------------------
//		 Hordes::UseNewAutoSaveDirectory
// ---------------------------------------------------------------------------

void Hordes::UseNewAutoSaveDirectory (void)
{
	gForceNewHordesDirectory = true;
}


// ---------------------------------------------------------------------------
//		 Hordes::ComputeStatistics
// ---------------------------------------------------------------------------

void Hordes::ComputeStatistics (int32 &min,
								int32 &max,
								int32 &avg,
								int32 &stdDev,
								int32 &smallErrorIndex)
{
	// I'm worried about overflow, but in practice this should be sufficiently large

	int32 sum = 0; 

	// this is the largest value possible with an int32; it is effectively infinity

	min = 0x7FFFFFFF;
	max = 0;

	// initialize this to a sentinel value

	smallErrorIndex = 0x7FFFFFFF;

	int32 numEventsToErr = 0;
	int32 counter = 0;
	int32 errorCounter = 0;

	EmAssert (gGremlinStartNumber <= gGremlinStopNumber);

	for (counter = gGremlinStartNumber; counter <= gGremlinStopNumber; counter++)
	{
		numEventsToErr = gGremlinHaltedInError[counter].fErrorEvent;
		sum += numEventsToErr;

		if (numEventsToErr > max)
		{
			max = numEventsToErr;
		}

		if (numEventsToErr < min && numEventsToErr > 0)
		{
			min = numEventsToErr;
		}

		if (numEventsToErr != 0)
		{
			errorCounter++;

			if ((smallErrorIndex == 0x7FFFFFFF) ||
				(numEventsToErr < gGremlinHaltedInError[smallErrorIndex].fErrorEvent))
			{
				smallErrorIndex = counter;
			}
		}
	}

	if (sum > 0 && errorCounter > 0)
	{
		avg = sum / errorCounter;
	}
	else
	{
		avg = 0;
		stdDev = 0;

		return;
	}

	// now to calculate the standard deviation

	int32 diffSquaredSum = 0;

	for (counter = gGremlinStartNumber; counter <= gGremlinStopNumber; counter++)
	{
		numEventsToErr = gGremlinHaltedInError[counter].fErrorEvent - avg;
		diffSquaredSum += (numEventsToErr * numEventsToErr);
	}

	// I'm assuming that MAXGREMLINS is not 0. Since it is defined, and
	// constant, I think this is a safe assumption.

	diffSquaredSum /= MAXGREMLINS;			// total - 1

	stdDev = (int32) sqrt (diffSquaredSum);

	return;
}


// ---------------------------------------------------------------------------
//		 Hordes::GremlinReport
// ---------------------------------------------------------------------------

void Hordes::GremlinReport (void)
{
	int32	counter					= 0;
	int32	lastSmallIndex			= 0;
	int32	numGremlinsWithError	= 0;
	int32	highestFrequency		= 1;

	// We want a table of sorts showing all of the errors encountered,
	// sorted by frequency. Errors that didn't crop up will be omitted,
	// as they are uninteresting. Alongside each error will be the count
	// of how many discrete Gremlins terminated with the error, and the
	// Gremlin number of the offender which terminated after the least
	// number of events. The errors that will be handled have their
	// constants defined in Strings.r.h

	// There are several interesting problems to deal with: the error
	// distribution, as compared to the number of Gremlins that were run,
	// is likely to be quite low; we would like to come up with the
	// Gremlin that terminates quickest, for each error; and we would like
	// to know which error is most prevalent.

	// According to Strings.r.h, error codes will be in the range {1000, 1199}.
	// Let's set up some offsets, and an array that will eventually hold
	// the error prevalence data.

	const int32		errorBase	= 1000;
	const int32		errorLast	= 1199;

	EmGremlinErrorFrequencyInfo errorCountArray [errorLast - errorBase + 1];

	// Let's initialize the array, using the offset notation that will be
	// used further on, just to be consistent. The first field will contain
	// the count of the error, the second will contain the Gremlin that
	// terminated quickest with the error.

	for (counter = errorBase; counter <= errorLast; counter++)
	{
		errorCountArray [counter - errorBase].fCount = 0;
		errorCountArray [counter - errorBase].fErrorFrequency = 0;

		// sentinel value, so that we know that we haven't seen this error before

		errorCountArray [counter - errorBase].fFirstErrantGremlinIndex = -1;
	}

	// Now let's walk through the gGremlinHaltedInError array, and for each
	// Gremlin that terminated in error, increment the error count for the
	// appropriate error

	int32	errorTypeNumber	= 0;
	int32	temp			= 0;

	EmAssert (gGremlinStartNumber <= gGremlinStopNumber);
	for (counter = gGremlinStartNumber; counter <= gGremlinStopNumber; counter++)
	{
		if (gGremlinHaltedInError[counter].fHalted != false)
		{
			errorTypeNumber = gGremlinHaltedInError[counter].fMessageID - errorBase;

			errorCountArray[errorTypeNumber].fErrorFrequency += 1;
			numGremlinsWithError += 1;

			// if we have not seen this error before, then this Gremlin's index
			// is, by definition, the index of the Gremlin which terminated first
			// with this error.

			lastSmallIndex = errorCountArray[errorTypeNumber].fFirstErrantGremlinIndex;

			if (lastSmallIndex == -1)
			{
				errorCountArray[errorTypeNumber].fCount = gGremlinHaltedInError[counter].fErrorEvent;
				errorCountArray[errorTypeNumber].fFirstErrantGremlinIndex = counter;
			}

			// otherwise, we have seen this error before, so check whether this
			// Gremlin terminated before the last frontrunner did.

			else
			{
				highestFrequency += 1;

				temp = gGremlinHaltedInError[counter].fErrorEvent;

				if (temp < gGremlinHaltedInError[lastSmallIndex].fErrorEvent)
				{
					errorCountArray[errorTypeNumber].fCount = temp;
					errorCountArray[errorTypeNumber].fFirstErrantGremlinIndex = counter;
				}
			}
		}
	}

	// So now we have an array filled with the number of times each error occurred,
	// and the # of the first-offending Gremlin. Now all that remains is to sort
	// the errors by their frequency, and then output our results. Some vital
	// information about the frequencies: their sum is numGremlinsWithError, and
	// the highest frequency of any single error is <= the number of Gremlins with
	// errors - 2 * the number of discrete errors that occurred multiple times.
	// With these constraints in mind, this following algorithm, ostensibly n^2
	// time, is in reality of managable time since n is constrained as above.
	// Why I am doing this is because I don't think that n is sufficiently large
	// to warrant the overhead of a quicksort, and because I don't feel like
	// writing a quicksort for a multi-dimensional array.

	if (numGremlinsWithError == 0)
	{
		return;
	}

	LogAppendMsg ("%d of %d Gremlins terminated in error.", numGremlinsWithError,
					gGremlinStopNumber - gGremlinStartNumber + 1);
	LogAppendMsg ("");
	LogAppendMsg ("Count               Error name                    Shortest Gremlin    Events");

	int32 errorNumber = 0;
	int32 frequency = 0;
	string str;

	// We only go down to 1, since we don't care about the errors that didn't
	// occur.

	for (frequency = highestFrequency;
		 frequency > 0;
		 frequency--)
	{
		for (errorNumber = errorBase; errorNumber <= errorLast; errorNumber++)
		{
			if (errorCountArray[errorNumber - errorBase].fErrorFrequency == frequency)
			{
				str = Hordes::TranslateErrorCode (errorNumber);
				LogAppendMsg ("%-4d                %-29s Gremlin #%-3d        %-4d",
					frequency,
					str.c_str (),
					errorCountArray[errorNumber - errorBase].fFirstErrantGremlinIndex,
					errorCountArray[errorNumber - errorBase].fCount);
			}
		}
	}
}


// ---------------------------------------------------------------------------
//		 Hordes::GetAppList
// ---------------------------------------------------------------------------
// Return the of applications that can be run under this Gremlin.

DatabaseInfoList Hordes::GetAppList (void)
{
	// If it looks like some of the fields need to filled out,
	// then do that now (some versions of Poser saved only the
	// creator, type, and version fields, leaving the others blank
	// -- we have to put back that information now).

	if (gGremlinAppList.size () > 0 && gGremlinAppList.front ().dbID == 0)
	{
		// Get the list of applications.

		DatabaseInfoList	appList;
		::GetDatabases (appList, kApplicationsOnly);

		// Iterate over all the allowed Gremlins applications and all the
		// installed applications, and use information in the latter to
		// fill in the former.

		DatabaseInfoList::iterator	gremlin_iter = gGremlinAppList.begin ();
		while (gremlin_iter != gGremlinAppList.end ())
		{
			DatabaseInfoList::iterator	installed_iter = appList.begin ();
			while (installed_iter != appList.end ())
			{
				if (gremlin_iter->creator == installed_iter->creator &&
					gremlin_iter->type == installed_iter->type &&
					gremlin_iter->version == installed_iter->version)
				{
					*gremlin_iter = *installed_iter;
					break;
				}

				++installed_iter;
			}

			++gremlin_iter;
		}
	}

	return gGremlinAppList;
}


// ---------------------------------------------------------------------------
//		 Hordes::TranslateErrorCode
// ---------------------------------------------------------------------------

string Hordes::TranslateErrorCode (UInt32 errCode)
{
	switch (errCode)
	{
		case kStr_OpError:
			return "OpError";
			break;

		case kStr_OpErrorRecover:
			return "OpErrorRecover";
			break;

		case kStr_ErrBusError:
			return "ErrBusError";
			break;

		case kStr_ErrAddressError:
			return "ErrAddressError";
			break;

		case kStr_ErrIllegalInstruction:
			return "ErrIllegalInstruction";
			break;

		case kStr_ErrDivideByZero:
			return "ErrDivideByZero";
			break;

		case kStr_ErrCHKInstruction:
			return "ErrCHKInstruction";
			break;

		case kStr_ErrTRAPVInstruction:
			return "ErrTRAPVInstruction";
			break;

		case kStr_ErrPrivilegeViolation:
			return "ErrPrivilegeViolation";
			break;

		case kStr_ErrTrace:
			return "ErrTrace";
			break;

		case kStr_ErrATrap:
			return "ErrATrap";
			break;

		case kStr_ErrFTrap:
			return "ErrFTrap";
			break;

		case kStr_ErrTRAPx:
			return "ErrTRAPx";
			break;

		case kStr_ErrStorageHeap:
			return "ErrStorageHeap";
			break;

		case kStr_ErrNoDrawWindow:
			return "ErrNoDrawWindow";
			break;

		case kStr_ErrNoGlobals:
			return "ErrNoGlobals";
			break;

		case kStr_ErrSANE:
			return "ErrSANE";
			break;

		case kStr_ErrTRAP0:
			return "ErrTRAP0";
			break;

		case kStr_ErrTRAP8:
			return "ErrTRAP8";
			break;

		case kStr_ErrStackOverflow:
			return "ErrStackOverflow";
			break;

		case kStr_ErrUnimplementedTrap:
			return "ErrUnimplementedTrap";
			break;

		case kStr_ErrInvalidRefNum:
			return "ErrInvalidRefNum";
			break;

		case kStr_ErrCorruptedHeap:
			return "ErrCorruptedHeap";
			break;

		case kStr_ErrInvalidPC1:
			return "ErrInvalidPC1";
			break;

		case kStr_ErrInvalidPC2:
			return "ErrInvalidPC2";
			break;

		case kStr_ErrLowMemory:
			return "ErrLowMemory";
			break;

		case kStr_ErrSystemGlobals:
			return "ErrSystemGlobals";
			break;

		case kStr_ErrScreen:
			return "ErrScreen";
			break;

		case kStr_ErrHardwareRegisters:
			return "ErrHardwareRegisters";
			break;

		case kStr_ErrROM:
			return "ErrROM";
			break;

		case kStr_ErrMemMgrStructures:
			return "ErrMemMgrStructures";
			break;

		case kStr_ErrMemMgrSemaphore:
			return "ErrMemMgrSemaphore";
			break;

		case kStr_ErrFreeChunk:
			return "ErrFreeChunk";
			break;

		case kStr_ErrUnlockedChunk:
			return "ErrUnlockedChunk";
			break;

		case kStr_ErrLowStack:
			return "ErrLowStack";
			break;

		case kStr_ErrStackFull:
			return "ErrStackFull";
			break;

		case kStr_ErrSizelessObject:
			return "ErrSizelessObject";
			break;

		case kStr_ErrOffscreenObject:
			return "ErrOffscreenObject";
			break;

		case kStr_ErrFormAccess:
			return "ErrFormAccess";
			break;

		case kStr_ErrFormObjectListAccess:
			return "ErrFormObjectListAccess";
			break;

		case kStr_ErrFormObjectAccess:
			return "ErrFormObjectAccess";
			break;

		case kStr_ErrWindowAccess:
			return "ErrWindowAccess";
			break;

		case kStr_ErrBitmapAccess:
			return "ErrBitmapAccess";
			break;

		case kStr_ErrProscribedFunction:
			return "ErrProscribedFunction";
			break;

		case kStr_ErrStepSpy:
			return "ErrStepSpy";
			break;

		case kStr_ErrWatchpoint:
			return "ErrWatchpoint";
			break;

		case kStr_ErrSysFatalAlert:
			return "ErrSysFatalAlert";
			break;

		case kStr_ErrDbgMessage:
			return "ErrDbgMessage";
			break;

		case kStr_BadChecksum:
			return "BadChecksum";
			break;

		case kStr_UnknownDeviceWarning:
			return "UnknownDeviceWarning";
			break;

		case kStr_UnknownDeviceError:
			return "UnknownDeviceError";
			break;

		case kStr_MissingSkins:
			return "MissingSkins";
			break;

		case kStr_InconsistentDatabaseDates:
			return "InconsistentDatabaseDates";
			break;

		case kStr_NULLDatabaseDate:
			return "NULLDatabaseDate";
			break;

		case kStr_NeedHostFS:
			return "NeedHostFS";
			break;

		case kStr_InvalidAddressNotEven:
			return "InvalidAddressNotEven";
			break;

		case kStr_InvalidAddressNotInROMOrRAM:
			return "InvalidAddressNotInROMOrRAM";
			break;

		case kStr_CannotParseCondition:
			return "CannotParseCondition";
			break;

		case kStr_UserNameTooLong:
			return "UserNameTooLong";
			break;

		case kStr_ErrMemoryLeak:
			return "ErrMemoryLeak";
			break;

		case kStr_ErrMemoryLeaks:
			return "ErrMemoryLeaks";
			break;

		default:
			EmAssert (false);
	}

	return "";
}