aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs
blob: 0bd9a0677f586c8a2cf9864dd98bd3dd333f6c6a (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
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics; //for [DebuggerNonUserCode]
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using OpenSim.Region.ScriptEngine.Interfaces;
using Timer = OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;

using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;

namespace OpenSim.Region.ScriptEngine.XEngine
{
    public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Control the printing of certain debug messages.
        /// </summary>
        /// <remarks>
        /// If DebugLevel >= 1, then we log every time that a script is started.
        /// </remarks>
//        public int DebugLevel { get; set; }

        private SmartThreadPool m_ThreadPool;
        private int m_MaxScriptQueue;
        private Scene m_Scene;
        private IConfig m_ScriptConfig = null;
        private IConfigSource m_ConfigSource = null;
        private ICompiler m_Compiler;
        private int m_MinThreads;
        private int m_MaxThreads;

        /// <summary>
        /// Amount of time to delay before starting.
        /// </summary>
        private int m_StartDelay;

        private int m_IdleTimeout;
        private int m_StackSize;
        private int m_SleepTime;
        private int m_SaveTime;
        private ThreadPriority m_Prio;
        private bool m_Enabled = false;
        private bool m_InitialStartup = true;
        private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
        private string m_ScriptErrorMessage;
        private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
        private bool m_AppDomainLoading;
        private Dictionary<UUID,ArrayList> m_ScriptErrors =
                new Dictionary<UUID,ArrayList>();

        // disable warning: need to keep a reference to XEngine.EventManager
        // alive to avoid it being garbage collected
#pragma warning disable 414
        private EventManager m_EventManager;
#pragma warning restore 414
        private IXmlRpcRouter m_XmlRpcRouter;
        private int m_EventLimit;
        private bool m_KillTimedOutScripts;

        /// <summary>
        /// Number of milliseconds we will wait for a script event to complete on script stop before we forcibly abort
        /// its thread.
        /// </summary>
        /// <remarks>
        /// It appears that if a script thread is aborted whilst it is holding ReaderWriterLockSlim (possibly the write
        /// lock) then the lock is not properly released.  This causes mono 2.6, 2.10 and possibly
        /// later to crash, sometimes with symptoms such as a leap to 100% script usage and a vm thead dump showing
        /// all threads waiting on release of ReaderWriterLockSlim write thread which none of the threads listed 
        /// actually hold.
        /// 
        /// Pausing for event completion reduces the risk of this happening.  However, it may be that aborting threads
        /// is not a mono issue per se but rather a risky activity in itself in an AppDomain that is not immediately
        /// shutting down.
        /// </remarks>
        private int m_WaitForEventCompletionOnScriptStop = 1000;

        private string m_ScriptEnginesPath = null;

        private ExpiringCache<UUID, bool> m_runFlags = new ExpiringCache<UUID, bool>();

        /// <summary>
        /// Is the entire simulator in the process of shutting down?
        /// </summary>
        private bool m_SimulatorShuttingDown;

        private static List<XEngine> m_ScriptEngines =
                new List<XEngine>();

        // Maps the local id to the script inventory items in it

        private Dictionary<uint, List<UUID> > m_PrimObjects =
                new Dictionary<uint, List<UUID> >();

        // Maps the UUID above to the script instance

        private Dictionary<UUID, IScriptInstance> m_Scripts =
                new Dictionary<UUID, IScriptInstance>();

        private OpenMetaverse.ReaderWriterLockSlim m_scriptsLock = new OpenMetaverse.ReaderWriterLockSlim();

        // Maps the asset ID to the assembly

        private Dictionary<UUID, string> m_Assemblies =
                new Dictionary<UUID, string>();

        private Dictionary<string, int> m_AddingAssemblies =
                new Dictionary<string, int>();

        // This will list AppDomains by script asset

        private Dictionary<UUID, AppDomain> m_AppDomains =
                new Dictionary<UUID, AppDomain>();

        // List the scripts running in each appdomain

        private Dictionary<UUID, List<UUID> > m_DomainScripts =
                new Dictionary<UUID, List<UUID> >();

        private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
        IWorkItemResult m_CurrentCompile = null;
        private Dictionary<UUID, int> m_CompileDict = new Dictionary<UUID, int>();

        private void lockScriptsForRead(bool locked)
        {
            if (locked)
            {
                if (m_scriptsLock.RecursiveReadCount > 0)
                {
                    m_log.Error("[XEngine.m_Scripts] Recursive read lock requested. This should not happen and means something needs to be fixed. For now though, it's safe to continue.");
                    m_scriptsLock.ExitReadLock();
                }
                if (m_scriptsLock.RecursiveWriteCount > 0)
                {
                    m_log.Error("[XEngine.m_Scripts] Recursive write lock requested. This should not happen and means something needs to be fixed.");
                    m_scriptsLock.ExitWriteLock();
                }

                while (!m_scriptsLock.TryEnterReadLock(60000))
                {
                    m_log.Error("[XEngine.m_Scripts] Thread lock detected while trying to aquire READ lock of m_scripts in XEngine. I'm going to try to solve the thread lock automatically to preserve region stability, but this needs to be fixed.");
                    if (m_scriptsLock.IsWriteLockHeld)
                    {
                        m_scriptsLock = new OpenMetaverse.ReaderWriterLockSlim();
                    }
                }
            }
            else
            {
                if (m_scriptsLock.RecursiveReadCount > 0)
                {
                    m_scriptsLock.ExitReadLock();
                }
            }
        }
        private void lockScriptsForWrite(bool locked)
        {
            if (locked)
            {
                if (m_scriptsLock.RecursiveReadCount > 0)
                {
                    m_log.Error("[XEngine.m_Scripts] Recursive read lock requested. This should not happen and means something needs to be fixed. For now though, it's safe to continue.");
                    m_scriptsLock.ExitReadLock();
                }
                if (m_scriptsLock.RecursiveWriteCount > 0)
                {
                    m_log.Error("[XEngine.m_Scripts] Recursive write lock requested. This should not happen and means something needs to be fixed.");
                    m_scriptsLock.ExitWriteLock();
                }

                while (!m_scriptsLock.TryEnterWriteLock(60000))
                {
                    m_log.Error("[XEngine.m_Scripts] Thread lock detected while trying to aquire WRITE lock of m_scripts in XEngine. I'm going to try to solve the thread lock automatically to preserve region stability, but this needs to be fixed.");
                    if (m_scriptsLock.IsWriteLockHeld)
                    {
                        m_scriptsLock = new OpenMetaverse.ReaderWriterLockSlim();
                    }
                }
            }
            else
            {
                if (m_scriptsLock.RecursiveWriteCount > 0)
                {
                    m_scriptsLock.ExitWriteLock();
                }
            }
        }

        public string ScriptEngineName
        {
            get { return "XEngine"; }
        }

        public Scene World
        {
            get { return m_Scene; }
        }

        public static List<XEngine> ScriptEngines
        {
            get { return m_ScriptEngines; }
        }

        public IScriptModule ScriptModule
        {
            get { return this; }
        }

        // private struct RezScriptParms
        // {
        //     uint LocalID;
        //     UUID ItemID;
        //     string Script;
        // }

        public IConfig Config
        {
            get { return m_ScriptConfig; }
        }

        public string ScriptEnginePath
        {
            get { return m_ScriptEnginesPath; }
        }

        public IConfigSource ConfigSource
        {
            get { return m_ConfigSource; }
        }

        /// <summary>
        /// Event fired after the script engine has finished removing a script.
        /// </summary>
        public event ScriptRemoved OnScriptRemoved;

        /// <summary>
        /// Event fired after the script engine has finished removing a script from an object.
        /// </summary>
        public event ObjectRemoved OnObjectRemoved;

        public void Initialise(IConfigSource configSource)
        {
            if (configSource.Configs["XEngine"] == null)
                return;

            m_ScriptConfig = configSource.Configs["XEngine"];
            m_ConfigSource = configSource;
        }

        public void AddRegion(Scene scene)
        {
            if (m_ScriptConfig == null)
                return;
            m_ScriptFailCount = 0;
            m_ScriptErrorMessage = String.Empty;

            if (m_ScriptConfig == null)
            {
//                m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
                return;
            }

            m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);

            if (!m_Enabled)
                return;

            AppDomain.CurrentDomain.AssemblyResolve +=
                OnAssemblyResolve;

            m_Scene = scene;
            m_log.InfoFormat("[XEngine]: Initializing scripts in region {0}", m_Scene.RegionInfo.RegionName);

            m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
            m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
            m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
            string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
            m_StartDelay = m_ScriptConfig.GetInt("StartDelay", 15000);
            m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
            m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
            m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
            m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);

            m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
            m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
            m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
            m_WaitForEventCompletionOnScriptStop 
                = m_ScriptConfig.GetInt("WaitForEventCompletionOnScriptStop", m_WaitForEventCompletionOnScriptStop);

            m_ScriptEnginesPath = m_ScriptConfig.GetString("ScriptEnginesPath", "ScriptEngines");

            m_Prio = ThreadPriority.BelowNormal;
            switch (priority)
            {
                case "Lowest":
                    m_Prio = ThreadPriority.Lowest;
                    break;
                case "BelowNormal":
                    m_Prio = ThreadPriority.BelowNormal;
                    break;
                case "Normal":
                    m_Prio = ThreadPriority.Normal;
                    break;
                case "AboveNormal":
                    m_Prio = ThreadPriority.AboveNormal;
                    break;
                case "Highest":
                    m_Prio = ThreadPriority.Highest;
                    break;
                default:
                    m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
                    break;
            }

            lock (m_ScriptEngines)
            {
                m_ScriptEngines.Add(this);
            }

            // Needs to be here so we can queue the scripts that need starting
            //
            m_Scene.EventManager.OnRezScript += OnRezScript;

            // Complete basic setup of the thread pool
            //
            SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
                        m_MaxScriptQueue, m_StackSize);

            m_Scene.StackModuleInterface<IScriptModule>(this);

            m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
            if (m_XmlRpcRouter != null)
            {
                OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
                OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
            }

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "xengine status", "xengine status", "Show status information",
                "Show status information on the script engine.",
                HandleShowStatus);

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "scripts show", "scripts show [<script-item-uuid>]", "Show script information",
                "Show information on all scripts known to the script engine.\n"
                    + "If a <script-item-uuid> is given then only information on that script will be shown.",
                HandleShowScripts);

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "show scripts", "show scripts [<script-item-uuid>]", "Show script information",
                "Synonym for scripts show command", HandleShowScripts);

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "scripts suspend", "scripts suspend [<script-item-uuid>]", "Suspends all running scripts",
                "Suspends all currently running scripts.  This only suspends event delivery, it will not suspend a"
                    + " script that is currently processing an event.\n"
                    + "Suspended scripts will continue to accumulate events but won't process them.\n"
                    + "If a <script-item-uuid> is given then only that script will be suspended.  Otherwise, all suitable scripts are suspended.",
                 (module, cmdparams) => HandleScriptsAction(cmdparams, HandleSuspendScript));

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "scripts resume", "scripts resume [<script-item-uuid>]", "Resumes all suspended scripts",
                "Resumes all currently suspended scripts.\n"
                    + "Resumed scripts will process all events accumulated whilst suspended.\n"
                    + "If a <script-item-uuid> is given then only that script will be resumed.  Otherwise, all suitable scripts are resumed.",
                (module, cmdparams) => HandleScriptsAction(cmdparams, HandleResumeScript));

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "scripts stop", "scripts stop [<script-item-uuid>]", "Stops all running scripts",
                "Stops all running scripts.\n"
                    + "If a <script-item-uuid> is given then only that script will be stopped.  Otherwise, all suitable scripts are stopped.",
                (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStopScript));

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "scripts start", "scripts start [<script-item-uuid>]", "Starts all stopped scripts",
                "Starts all stopped scripts.\n"
                    + "If a <script-item-uuid> is given then only that script will be started.  Otherwise, all suitable scripts are started.",
                (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStartScript));

            MainConsole.Instance.Commands.AddCommand(
                "Scripts", false, "debug script log", "debug scripts log <item-id> <log-level>", "Extra debug logging for a script",
                "Activates or deactivates extra debug logging for the given script.\n"
                    + "Level == 0, deactivate extra debug logging.\n"
                    + "Level >= 1, log state changes.\n"
                    + "Level >= 2, log event invocations.\n",
                HandleDebugScriptLogCommand);

//            MainConsole.Instance.Commands.AddCommand(
//                "Debug", false, "debug xengine", "debug xengine [<level>]",
//                "Turn on detailed xengine debugging.",
//                  "If level <= 0, then no extra logging is done.\n"
//                + "If level >= 1, then we log every time that a script is started.",
//                HandleDebugLevelCommand);
        }

        private void HandleDebugScriptLogCommand(string module, string[] args)
        {
            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
                return;

            if (args.Length != 5)
            {
                MainConsole.Instance.Output("Usage: debug script log <item-id> <log-level>");
                return;
            }

            UUID itemId;

            if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, args[3], out itemId))
                return;

            int newLevel;

            if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out newLevel))
                return;

            IScriptInstance si;

            lock (m_Scripts)
            {
                // XXX: We can't give the user feedback on a bad item id because this may apply to a different script
                // engine
                if (!m_Scripts.TryGetValue(itemId, out si))
                    return;
            }

            si.DebugLevel = newLevel;
            MainConsole.Instance.OutputFormat("Set debug level of {0} {1} to {2}", si.ScriptName, si.ItemID, newLevel);
        }

        /// <summary>
        /// Change debug level
        /// </summary>
        /// <param name="module"></param>
        /// <param name="args"></param>
//        private void HandleDebugLevelCommand(string module, string[] args)
//        {
//            if (args.Length == 3)
//            {
//                int newDebug;
//                if (int.TryParse(args[2], out newDebug))
//                {
//                    DebugLevel = newDebug;
//                    MainConsole.Instance.OutputFormat("Debug level set to {0}", newDebug);
//                }
//            }
//            else if (args.Length == 2)
//            {
//                MainConsole.Instance.OutputFormat("Current debug level is {0}", DebugLevel);
//            }
//            else
//            {
//                MainConsole.Instance.Output("Usage: debug xengine 0..1");
//            }
//        }

        /// <summary>
        /// Parse the raw item id into a script instance from the command params if it's present.
        /// </summary>
        /// <param name="cmdparams"></param>
        /// <param name="instance"></param>
        /// <param name="comparer">Basis on which to sort output.  Can be null if no sort needs to take place</param>
        private void HandleScriptsAction(string[] cmdparams, Action<IScriptInstance> action)
        {
            HandleScriptsAction<object>(cmdparams, action, null);
        }

        /// <summary>
        /// Parse the raw item id into a script instance from the command params if it's present.
        /// </summary>
        /// <param name="cmdparams"></param>
        /// <param name="instance"></param>
        /// <param name="keySelector">Basis on which to sort output.  Can be null if no sort needs to take place</param>
        private void HandleScriptsAction<TKey>(
            string[] cmdparams, Action<IScriptInstance> action, Func<IScriptInstance, TKey> keySelector)
        {
            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
                return;

            lock (m_Scripts)
            {
                string rawItemId;
                UUID itemId = UUID.Zero;
    
                if (cmdparams.Length == 2)
                {
                    IEnumerable<IScriptInstance> scripts = m_Scripts.Values;

                    if (keySelector != null)
                        scripts = scripts.OrderBy<IScriptInstance, TKey>(keySelector);

                    foreach (IScriptInstance instance in scripts)
                        action(instance);

                    return;
                }
    
                rawItemId = cmdparams[2];
    
                if (!UUID.TryParse(rawItemId, out itemId))
                {
                    MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid UUID", rawItemId);
                    return;
                }
    
                if (itemId != UUID.Zero)
                {
                    IScriptInstance instance = GetInstance(itemId);
                    if (instance == null)
                    {
                        // Commented out for now since this will cause false reports on simulators with more than
                        // one scene where the current command line set region is 'root' (which causes commands to
                        // go to both regions... (sigh)
//                        MainConsole.Instance.OutputFormat("Error - No item found with id {0}", itemId);
                        return;
                    }
                    else
                    {
                        action(instance);
                        return;
                    }
                }
            }
        }

        private void HandleShowStatus(string module, string[] cmdparams)
        {
            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
                return;

            MainConsole.Instance.OutputFormat(GetStatusReport());
        }

        public string GetStatusReport()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Status of XEngine instance for {0}\n", m_Scene.RegionInfo.RegionName);

            long scriptsLoaded, eventsQueued = 0, eventsProcessed = 0;

            lock (m_Scripts)
            {
                scriptsLoaded = m_Scripts.Count;

                foreach (IScriptInstance si in m_Scripts.Values)
                {
                    eventsQueued += si.EventsQueued;
                    eventsProcessed += si.EventsProcessed;
                }
            }

            sb.AppendFormat("Scripts loaded             : {0}\n", scriptsLoaded);
            sb.AppendFormat("Unique scripts             : {0}\n", m_uniqueScripts.Count);
            sb.AppendFormat("Scripts waiting for load   : {0}\n", m_CompileQueue.Count);
            sb.AppendFormat("Max threads                : {0}\n", m_ThreadPool.MaxThreads);
            sb.AppendFormat("Min threads                : {0}\n", m_ThreadPool.MinThreads);
            sb.AppendFormat("Allocated threads          : {0}\n", m_ThreadPool.ActiveThreads);
            sb.AppendFormat("In use threads             : {0}\n", m_ThreadPool.InUseThreads);
            sb.AppendFormat("Work items waiting         : {0}\n", m_ThreadPool.WaitingCallbacks);
//            sb.AppendFormat("Assemblies loaded          : {0}\n", m_Assemblies.Count);
            sb.AppendFormat("Events queued              : {0}\n", eventsQueued);
            sb.AppendFormat("Events processed           : {0}\n", eventsProcessed);

            SensorRepeat sr = AsyncCommandManager.GetSensorRepeatPlugin(this);
            sb.AppendFormat("Sensors                    : {0}\n", sr != null ? sr.SensorsCount : 0);

            Dataserver ds = AsyncCommandManager.GetDataserverPlugin(this);
            sb.AppendFormat("Dataserver requests        : {0}\n", ds != null ? ds.DataserverRequestsCount : 0);

            Timer t = AsyncCommandManager.GetTimerPlugin(this);
            sb.AppendFormat("Timers                     : {0}\n", t != null ? t.TimersCount : 0);

            Listener l = AsyncCommandManager.GetListenerPlugin(this);
            sb.AppendFormat("Listeners                  : {0}\n", l != null ? l.ListenerCount : 0);

            return sb.ToString();
        }

        public void HandleShowScripts(string module, string[] cmdparams)
        {
            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
                return;

            if (cmdparams.Length == 2)
            {
                lock (m_Scripts)
                {
                    MainConsole.Instance.OutputFormat(
                        "Showing {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
                }
            }

            HandleScriptsAction<long>(cmdparams, HandleShowScript, si => si.EventsProcessed);
        }

        private void HandleShowScript(IScriptInstance instance)
        {
            SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
            string status;

            if (instance.ShuttingDown)
            {
                status = "shutting down";
            }
            else if (instance.Suspended)
            {
                status = "suspended";
            }
            else if (!instance.Running)
            {
                status = "stopped";
            }
            else
            {
                status = "running";
            }

            StringBuilder sb = new StringBuilder();
            Queue eq = instance.EventQueue;

            sb.AppendFormat("Script name         : {0}\n", instance.ScriptName);
            sb.AppendFormat("Status              : {0}\n", status);
            sb.AppendFormat("Queued events       : {0}\n", instance.EventsQueued);
            sb.AppendFormat("Processed events    : {0}\n", instance.EventsProcessed);
            sb.AppendFormat("Item UUID           : {0}\n", instance.ItemID);
            sb.AppendFormat("Asset UUID          : {0}\n", instance.AssetID);
            sb.AppendFormat("Containing part name: {0}\n", instance.PrimName);
            sb.AppendFormat("Containing part UUID: {0}\n", instance.ObjectID);
            sb.AppendFormat("Position            : {0}\n", sop.AbsolutePosition);

            MainConsole.Instance.OutputFormat(sb.ToString());
        }

        private void HandleSuspendScript(IScriptInstance instance)
        {
            if (!instance.Suspended)
            {
                instance.Suspend();

                SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
                MainConsole.Instance.OutputFormat(
                    "Suspended {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
                    instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
            }
        }

        private void HandleResumeScript(IScriptInstance instance)
        {
            if (instance.Suspended)
            {
                instance.Resume();

                SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
                MainConsole.Instance.OutputFormat(
                    "Resumed {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
                    instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
            }
        }

        private void HandleStartScript(IScriptInstance instance)
        {
            if (!instance.Running)
            {
                instance.Start();

                SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
                MainConsole.Instance.OutputFormat(
                    "Started {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
                    instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
            }
        }

        private void HandleStopScript(IScriptInstance instance)
        {
            if (instance.Running)
            {
                instance.Stop(0);

                SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
                MainConsole.Instance.OutputFormat(
                    "Stopped {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
                    instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
            }
        }

        public void RemoveRegion(Scene scene)
        {
            if (!m_Enabled)
                return;
            lockScriptsForRead(true);

            List<IScriptInstance> instancesToDel = new List<IScriptInstance>(m_Scripts.Values);

//            foreach (IScriptInstance instance in m_Scripts.Values)
            foreach (IScriptInstance instance in instancesToDel)
            {
                // Force a final state save
                //
                if (m_Assemblies.ContainsKey(instance.AssetID))
                {
                    string assembly = m_Assemblies[instance.AssetID];

                    try
                    {
                        instance.SaveState(assembly);
                    }
                    catch (Exception e)
                    {
                        m_log.Error(
                            string.Format(
                                "[XEngine]: Failed final state save for script {0}.{1}, item UUID {2}, prim UUID {3} in {4}.  Exception ",
                                instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name)
                            , e);
                    }
                }

                // Clear the event queue and abort the instance thread
                //
                instance.ClearQueue();
                instance.Stop(0);

                // Release events, timer, etc
                //
                instance.DestroyScriptInstance();

                // Unload scripts and app domains
                // Must be done explicitly because they have infinite
                // lifetime
                //
//                if (!m_SimulatorShuttingDown)
                {
                    m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
                    if (m_DomainScripts[instance.AppDomain].Count == 0)
                    {
                        m_DomainScripts.Remove(instance.AppDomain);
                        UnloadAppDomain(instance.AppDomain);
                    }
                }

//                m_Scripts.Clear();
//                m_PrimObjects.Clear();
//                m_Assemblies.Clear();
//                m_DomainScripts.Clear();
            }
            lockScriptsForRead(false);
            lockScriptsForWrite(true);
            m_Scripts.Clear();
            lockScriptsForWrite(false);
            m_PrimObjects.Clear();
            m_Assemblies.Clear();
            m_DomainScripts.Clear();
           
            lock (m_ScriptEngines)
            {
                m_ScriptEngines.Remove(this);
            }
        }

        public void RegionLoaded(Scene scene)
        {
            if (!m_Enabled)
                return;

            m_EventManager = new EventManager(this);

            m_Compiler = new Compiler(this);

            m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
            m_Scene.EventManager.OnScriptReset += OnScriptReset;
            m_Scene.EventManager.OnStartScript += OnStartScript;
            m_Scene.EventManager.OnStopScript += OnStopScript;
            m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
            m_Scene.EventManager.OnShutdown += OnShutdown;

            // If region ready has been triggered, then the region had no scripts to compile and completed its other
            // work.
            m_Scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) m_InitialStartup = false; };

            if (m_SleepTime > 0)
            {
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
                                           new Object[]{ m_SleepTime });
            }

            if (m_SaveTime > 0)
            {
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
                                           new Object[] { m_SaveTime });
            }
        }

        public void StartProcessing()
        {
            m_ThreadPool.Start();
        }

        public void Close()
        {
            if (!m_Enabled)
                return;
            
            lock (m_ScriptEngines)
            {
                if (m_ScriptEngines.Contains(this))
                    m_ScriptEngines.Remove(this);
            }
        }

        public object DoBackup(object o)
        {
            Object[] p = (Object[])o;
            int saveTime = (int)p[0];

            if (saveTime > 0)
                System.Threading.Thread.Sleep(saveTime);

//            m_log.Debug("[XEngine] Backing up script states");

            List<IScriptInstance> instances = new List<IScriptInstance>();

            lockScriptsForRead(true);
                 foreach (IScriptInstance instance in m_Scripts.Values)
                    instances.Add(instance);
            lockScriptsForRead(false);

            foreach (IScriptInstance i in instances)
            {
                string assembly = String.Empty;

                
                    if (!m_Assemblies.ContainsKey(i.AssetID))
                        continue;
                    assembly = m_Assemblies[i.AssetID];
                

                try
                {
                    i.SaveState(assembly);
                }
                catch (Exception e)
                {
                    m_log.Error(
                        string.Format(
                            "[XEngine]: Failed to save state of script {0}.{1}, item UUID {2}, prim UUID {3} in {4}.  Exception ",
                            i.PrimName, i.ScriptName, i.ItemID, i.ObjectID, World.Name)
                        , e);
                }
            }

            instances.Clear();

            if (saveTime > 0)
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
                                           new Object[] { saveTime });

            return 0;
        }

        public void SaveAllState()
        {
            foreach (IScriptInstance inst in m_Scripts.Values)
            {
                if (inst.EventTime() > m_EventLimit)
                {
                    inst.Stop(100);
                    if (!m_KillTimedOutScripts)
                        inst.Start();
                }
            }
        }

        public object DoMaintenance(object p)
        {
            object[] parms = (object[])p;
            int sleepTime = (int)parms[0];

            SaveAllState();

            System.Threading.Thread.Sleep(sleepTime);

            m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
                                       new Object[]{ sleepTime });

            return 0;
        }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        public string Name
        {
            get { return "XEngine"; }
        }

        public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
        {
//            m_log.DebugFormat(
//                "[XEngine]: OnRezScript event triggered for script {0}, startParam {1}, postOnRez {2}, engine {3}, stateSource {4}, script\n{5}",
//                 itemID, startParam, postOnRez, engine, stateSource, script);

            if (script.StartsWith("//MRM:"))
                return;

            List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());

            List<string> names = new List<string>();
            foreach (IScriptModule m in engines)
                names.Add(m.ScriptEngineName);

            int lineEnd = script.IndexOf('\n');

            if (lineEnd > 1)
            {
                string firstline = script.Substring(0, lineEnd).Trim();

                int colon = firstline.IndexOf(':');
                if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
                {
                    string engineName = firstline.Substring(2, colon - 2);

                    if (names.Contains(engineName))
                    {
                        engine = engineName;
                        script = "//" + script.Substring(colon + 1);
                    }
                    else
                    {
                        if (engine == ScriptEngineName)
                        {
                            // If we are falling back on XEngine as the default engine, then only complain to the user
                            // if a script language has been explicitly set and it's one that we recognize or there are
                            // no non-whitespace characters after the colon.
                            //
                            // If the script is
                            // explicitly not allowed or the script is not in LSL then the user will be informed by a later compiler message.
                            //
                            // If the colon ends the line then we'll risk the false positive as this is more likely
                            // to signal a real scriptengine line where the user wants to use the default compile language.
                            //
                            // This avoids the overwhelming number of false positives where we're in this code because
                            // there's a colon in a comment in the first line of a script for entirely
                            // unrelated reasons (e.g. vim settings).
                            //
                            // TODO: A better fix would be to deprecate simple : detection and look for some less likely
                            // string to begin the comment (like #! in unix shell scripts).
                            bool warnRunningInXEngine = false;
                            string restOfFirstLine = firstline.Substring(colon + 1);

                            // FIXME: These are hardcoded because they are currently hardcoded in Compiler.cs
                            if (restOfFirstLine.StartsWith("c#")
                                || restOfFirstLine.StartsWith("vb")
                                || restOfFirstLine.StartsWith("lsl")
                                || restOfFirstLine.StartsWith("js")
                                || restOfFirstLine.StartsWith("yp")
                                || restOfFirstLine.Length == 0)
                                warnRunningInXEngine = true;

                            if (warnRunningInXEngine)
                            {
                                SceneObjectPart part =
                                        m_Scene.GetSceneObjectPart(
                                        localID);
                             
                                TaskInventoryItem item =
                                        part.Inventory.GetInventoryItem(itemID);
    
                                ScenePresence presence = 
                                        m_Scene.GetScenePresence(
                                        item.OwnerID);
    
                                if (presence != null)
                                {
                                   presence.ControllingClient.SendAgentAlertMessage(
                                            "Selected engine unavailable. "+
                                            "Running script on "+
                                            ScriptEngineName,
                                            false);
                                }
                            }
                        }
                    }
                }
            }

            if (engine != ScriptEngineName)
                return;

            // If we've seen this exact script text before, use that reference instead
            if (m_uniqueScripts.ContainsKey(script))
                script = m_uniqueScripts[script];
            else
                m_uniqueScripts[script] = script;

            Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};

            if (stateSource == (int)StateSource.ScriptedRez)
            {
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

                DoOnRezScript(parms);
            }
            else
            {
                m_CompileQueue.Enqueue(parms);
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

//                m_log.DebugFormat("[XEngine]: Added script {0} to compile queue", itemID);

                if (m_CurrentCompile == null)
                {
                    // NOTE: Although we use a lockless queue, the lock here
                    // is required. It ensures that there are never two
                    // compile threads running, which, due to a race
                    // conndition, might otherwise happen
                    //
                    lock (m_CompileQueue)
                    {
                        if (m_CurrentCompile == null)
                            m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
                    }
                }
            }
        }

        public Object DoOnRezScriptQueue(Object dummy)
        {
            if (m_InitialStartup)
            {
                // This delay exists to stop mono problems where script compilation and startup would stop the sim
                // working properly for the session.
                System.Threading.Thread.Sleep(m_StartDelay);

                m_log.InfoFormat("[XEngine]: Performing initial script startup on {0}", m_Scene.Name);
            }

            object[] o;

            int scriptsStarted = 0;

            while (m_CompileQueue.Dequeue(out o))
            {
                if (DoOnRezScript(o))
                {
                    scriptsStarted++;

                    if (m_InitialStartup)
                        if (scriptsStarted % 50 == 0)
                            m_log.InfoFormat(
                                "[XEngine]: Started {0} scripts in {1}", scriptsStarted, m_Scene.Name);
                }
            }

            if (m_InitialStartup)
                m_log.InfoFormat(
                    "[XEngine]: Completed starting {0} scripts on {1}", scriptsStarted, m_Scene.Name);

            // NOTE: Despite having a lockless queue, this lock is required
            // to make sure there is never no compile thread while there
            // are still scripts to compile. This could otherwise happen
            // due to a race condition
            //
            lock (m_CompileQueue)
                m_CurrentCompile = null;

            m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
                                                                m_ScriptErrorMessage);

            m_ScriptFailCount = 0;
            m_InitialStartup = false;

            return null;
        }

        private bool DoOnRezScript(object[] parms)
        {
            Object[] p = parms;
            uint localID = (uint)p[0];
            UUID itemID = (UUID)p[1];
            string script =(string)p[2];
            int startParam = (int)p[3];
            bool postOnRez = (bool)p[4];
            StateSource stateSource = (StateSource)p[5];

//            m_log.DebugFormat("[XEngine]: DoOnRezScript called for script {0}", itemID);

            lock (m_CompileDict)
            {
                if (!m_CompileDict.ContainsKey(itemID))
                    return false;
                m_CompileDict.Remove(itemID);
            }

            // Get the asset ID of the script, so we can check if we
            // already have it.

            // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
            // m_parts lock on SOG.  At the same time, a scene object that is being deleted will take the m_parts lock
            // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
            SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
            if (part == null)
            {
                m_log.ErrorFormat("[Script]: SceneObjectPart with localID {0} unavailable. Script NOT started.", localID);
                m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
                m_ScriptFailCount++;
                return false;
            }

            TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
            if (item == null)
            {
                m_ScriptErrorMessage += "Can't find script inventory item.\n";
                m_ScriptFailCount++;
                return false;
            }

            m_log.DebugFormat(
                "[XEngine] Loading script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
                part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
                part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);

            UUID assetID = item.AssetID;

            ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);

            string assembly = "";

            Culture.SetCurrentCulture();

            Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;

            lock (m_ScriptErrors)
            {
                try
                {
                    lock (m_AddingAssemblies)
                    {
                        m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
                        if (!m_AddingAssemblies.ContainsKey(assembly)) {
                            m_AddingAssemblies[assembly] = 1;
                        } else {
                            m_AddingAssemblies[assembly]++;
                        }
                    }

                    string[] warnings = m_Compiler.GetWarnings();

                    if (warnings != null && warnings.Length != 0)
                    {
                        foreach (string warning in warnings)
                        {
                            if (!m_ScriptErrors.ContainsKey(itemID))
                                m_ScriptErrors[itemID] = new ArrayList();

                            m_ScriptErrors[itemID].Add(warning);
    //                        try
    //                        {
    //                            // DISPLAY WARNING INWORLD
    //                            string text = "Warning:\n" + warning;
    //                            if (text.Length > 1000)
    //                                text = text.Substring(0, 1000);
    //                            if (!ShowScriptSaveResponse(item.OwnerID,
    //                                    assetID, text, true))
    //                            {
    //                                if (presence != null && (!postOnRez))
    //                                    presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
    //
    //                                World.SimChat(Utils.StringToBytes(text),
    //                                              ChatTypeEnum.DebugChannel, 2147483647,
    //                                              part.AbsolutePosition,
    //                                              part.Name, part.UUID, false);
    //                            }
    //                        }
    //                        catch (Exception e2) // LEGIT: User Scripting
    //                        {
    //                            m_log.Error("[XEngine]: " +
    //                                    "Error displaying warning in-world: " +
    //                                    e2.ToString());
    //                            m_log.Error("[XEngine]: " +
    //                                    "Warning:\r\n" +
    //                                    warning);
    //                        }
                        }
                    }
                }
                catch (Exception e)
                {
//                    m_log.ErrorFormat("[XEngine]: Exception when rezzing script {0}{1}", e.Message, e.StackTrace);

    //                try
    //                {
                        if (!m_ScriptErrors.ContainsKey(itemID))
                            m_ScriptErrors[itemID] = new ArrayList();
                        // DISPLAY ERROR INWORLD
    //                    m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
    //
                        m_ScriptFailCount++;
                        m_ScriptErrors[itemID].Add(e.Message.ToString());
    //                    string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
    //                    if (text.Length > 1000)
    //                        text = text.Substring(0, 1000);
    //                    if (!ShowScriptSaveResponse(item.OwnerID,
    //                            assetID, text, false))
    //                    {
    //                        if (presence != null && (!postOnRez))
    //                            presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
    //                        World.SimChat(Utils.StringToBytes(text),
    //                                      ChatTypeEnum.DebugChannel, 2147483647,
    //                                      part.AbsolutePosition,
    //                                      part.Name, part.UUID, false);
    //                    }
    //                }
    //                catch (Exception e2) // LEGIT: User Scripting
    //                {
    //                    m_log.Error("[XEngine]: "+
    //                            "Error displaying error in-world: " +
    //                            e2.ToString());
    //                    m_log.Error("[XEngine]: " +
    //                            "Errormessage: Error compiling script:\r\n" +
    //                            e.Message.ToString());
    //                }

                    return false;
                }
            }

            ScriptInstance instance = null;
            // Create the object record
            lockScriptsForRead(true);
            if ((!m_Scripts.ContainsKey(itemID)) ||
                (m_Scripts[itemID].AssetID != assetID))
            {
                lockScriptsForRead(false);

                UUID appDomain = assetID;

                if (part.ParentGroup.IsAttachment)
                    appDomain = part.ParentGroup.RootPart.UUID;

                if (!m_AppDomains.ContainsKey(appDomain))
                {
                    try
                    {
                        AppDomainSetup appSetup = new AppDomainSetup();
                        appSetup.PrivateBinPath = Path.Combine(
                                m_ScriptEnginesPath,
                                m_Scene.RegionInfo.RegionID.ToString());

                        Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
                        Evidence evidence = new Evidence(baseEvidence);

                        AppDomain sandbox;
                        if (m_AppDomainLoading)
                        {
                            sandbox = AppDomain.CreateDomain(
                                            m_Scene.RegionInfo.RegionID.ToString(),
                                            evidence, appSetup);
                            m_AppDomains[appDomain].AssemblyResolve +=
                                new ResolveEventHandler(
                                    AssemblyResolver.OnAssemblyResolve);
                        }
                        else
                        {
                            sandbox = AppDomain.CurrentDomain;
                        }

                        //PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
                        //AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
                        //PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
                        //PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
                        //CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
                        //sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
                        //sandbox.SetAppDomainPolicy(sandboxPolicy);

                        m_AppDomains[appDomain] = sandbox;

                        m_DomainScripts[appDomain] = new List<UUID>();
                    }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
                        m_ScriptErrorMessage += "Exception creating app domain:\n";
                        m_ScriptFailCount++;
                        lock (m_AddingAssemblies)
                        {
                            m_AddingAssemblies[assembly]--;
                        }
                        return false;
                    }
                }
                m_DomainScripts[appDomain].Add(itemID);

                instance = new ScriptInstance(this, part,
                                              itemID, assetID, assembly,
                                              m_AppDomains[appDomain],
                                              part.ParentGroup.RootPart.Name,
                                              item.Name, startParam, postOnRez,
                                              stateSource, m_MaxScriptQueue);

//                m_log.DebugFormat(
//                        "[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}.{5}",
//                        part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, 
//                        part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);

                if (presence != null)
                {
                    ShowScriptSaveResponse(item.OwnerID,
                            assetID, "Compile successful", true);
                }

                instance.AppDomain = appDomain;
                instance.LineMap = linemap;
                lockScriptsForWrite(true);
                m_Scripts[itemID] = instance;
                lockScriptsForWrite(false);
            }
            else
            {
                lockScriptsForRead(false);
            }
            lock (m_PrimObjects)
            {
                if (!m_PrimObjects.ContainsKey(localID))
                    m_PrimObjects[localID] = new List<UUID>();

                if (!m_PrimObjects[localID].Contains(itemID))
                    m_PrimObjects[localID].Add(itemID);
            }

            if (!m_Assemblies.ContainsKey(assetID))
                m_Assemblies[assetID] = assembly;

            lock (m_AddingAssemblies) 
            {
                m_AddingAssemblies[assembly]--;
            }

            if (instance!=null) 
                instance.Init();

            bool runIt;
            if (m_runFlags.TryGetValue(itemID, out runIt))
            {
                if (!runIt)
                    StopScript(itemID);
                m_runFlags.Remove(itemID);
            }

            return true;
        }

        public void OnRemoveScript(uint localID, UUID itemID)
        {
            // If it's not yet been compiled, make sure we don't try
            lock (m_CompileDict)
            {
                if (m_CompileDict.ContainsKey(itemID))
                    m_CompileDict.Remove(itemID);
            }

            lockScriptsForRead(true);
            // Do we even have it?
            if (!m_Scripts.ContainsKey(itemID))
            {
                // Do we even have it?
                if (!m_Scripts.ContainsKey(itemID))
                    return;

                lockScriptsForRead(false);
                lockScriptsForWrite(true);
                m_Scripts.Remove(itemID);
                lockScriptsForWrite(false);

                return;
            }
             

            IScriptInstance instance=m_Scripts[itemID];
            lockScriptsForRead(false);
            lockScriptsForWrite(true);
            m_Scripts.Remove(itemID);
            lockScriptsForWrite(false);
            instance.ClearQueue();

            instance.Stop(m_WaitForEventCompletionOnScriptStop);

//                bool objectRemoved = false;

            lock (m_PrimObjects)
            {
                // Remove the script from it's prim
                if (m_PrimObjects.ContainsKey(localID))
                {
                    // Remove inventory item record
                    if (m_PrimObjects[localID].Contains(itemID))
                        m_PrimObjects[localID].Remove(itemID);

                    // If there are no more scripts, remove prim
                    if (m_PrimObjects[localID].Count == 0)
                    {
                        m_PrimObjects.Remove(localID);
//                            objectRemoved = true;
                    }
                }
            }

            instance.RemoveState();
            instance.DestroyScriptInstance();

            m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
            if (m_DomainScripts[instance.AppDomain].Count == 0)
            {
                m_DomainScripts.Remove(instance.AppDomain);
                UnloadAppDomain(instance.AppDomain);
            }

            ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
            if (handlerObjectRemoved != null)
            {
                SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);                    
                handlerObjectRemoved(part.UUID);
            }

            CleanAssemblies();
            
            ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
            if (handlerScriptRemoved != null)
                handlerScriptRemoved(itemID);
        }

        public void OnScriptReset(uint localID, UUID itemID)
        {
            ResetScript(itemID);
        }

        public void OnStartScript(uint localID, UUID itemID)
        {
            StartScript(itemID);
        }

        public void OnStopScript(uint localID, UUID itemID)
        {
            StopScript(itemID);
        }

        private void CleanAssemblies()
        {
            List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);

            foreach (IScriptInstance i in m_Scripts.Values)
            {
                if (assetIDList.Contains(i.AssetID))
                    assetIDList.Remove(i.AssetID);
            }

            lock (m_AddingAssemblies)
            {
                foreach (UUID assetID in assetIDList)
                {
                    // Do not remove assembly files if another instance of the script
                    // is currently initialising
                    if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
                        || m_AddingAssemblies[m_Assemblies[assetID]] == 0) 
                    {
//                        m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
                        try
                        {
                            if (File.Exists(m_Assemblies[assetID]))
                                File.Delete(m_Assemblies[assetID]);
                            
                            if (File.Exists(m_Assemblies[assetID]+".text"))
                                File.Delete(m_Assemblies[assetID]+".text");
                            
                            if (File.Exists(m_Assemblies[assetID]+".mdb"))
                                File.Delete(m_Assemblies[assetID]+".mdb");
                            
                            if (File.Exists(m_Assemblies[assetID]+".map"))
                                File.Delete(m_Assemblies[assetID]+".map");
                        }
                        catch (Exception)
                        {
                        }
                        m_Assemblies.Remove(assetID);
                    }
                }
            }
        }

        private void UnloadAppDomain(UUID id)
        {
            if (m_AppDomains.ContainsKey(id))
            {
                AppDomain domain = m_AppDomains[id];
                m_AppDomains.Remove(id);

                if (domain != AppDomain.CurrentDomain)
                    AppDomain.Unload(domain);
                domain = null;
                // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
            }
        }

        //
        // Start processing
        //
        private void SetupEngine(int minThreads, int maxThreads,
                                 int idleTimeout, ThreadPriority threadPriority,
                                 int maxScriptQueue, int stackSize)
        {
            m_MaxScriptQueue = maxScriptQueue;

            STPStartInfo startInfo = new STPStartInfo();
            startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
            startInfo.MaxWorkerThreads = maxThreads;
            startInfo.MinWorkerThreads = minThreads;
            startInfo.ThreadPriority = threadPriority;;
            startInfo.StackSize = stackSize;
            startInfo.StartSuspended = true;

            m_ThreadPool = new SmartThreadPool(startInfo);
        }

        //
        // Used by script instances to queue event handler jobs
        //
        public IScriptWorkItem QueueEventHandler(object parms)
        {
            return new XWorkItem(m_ThreadPool.QueueWorkItem(
                                     new WorkItemCallback(this.ProcessEventHandler),
                                     parms));
        }
        
        /// <summary>
        /// Process a previously posted script event.
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        private object ProcessEventHandler(object parms)
        {
            Culture.SetCurrentCulture();

            IScriptInstance instance = (ScriptInstance) parms;
            
            //m_log.DebugFormat("[XEngine]: Processing event for {0}", instance);

            return instance.EventProcessor();
        }

        /// <summary>
        /// Post event to an entire prim
        /// </summary>
        /// <param name="localID"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public bool PostObjectEvent(uint localID, EventParams p)
        {
            bool result = false;
            List<UUID> uuids = null;

            lock (m_PrimObjects)
            {
                if (!m_PrimObjects.ContainsKey(localID))
                    return false;

                uuids = m_PrimObjects[localID];

                foreach (UUID itemID in uuids)
                {
                    IScriptInstance instance = null;
                    try
                    {
                        if (m_Scripts.ContainsKey(itemID))
                            instance = m_Scripts[itemID];
                    }
                    catch { /* ignore race conditions */ }
    
                    if (instance != null)
                    {
                        instance.PostEvent(p);
                        result = true;
                    }
                }
            }
            
            return result;
        }

        /// <summary>
        /// Post an event to a single script
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public bool PostScriptEvent(UUID itemID, EventParams p)
        {
            if (m_Scripts.ContainsKey(itemID))
            {
                IScriptInstance instance = m_Scripts[itemID];
                if (instance != null)
                    instance.PostEvent(p);
                return true;
            }
            return false;
        }

        public bool PostScriptEvent(UUID itemID, string name, Object[] p)
        {
            Object[] lsl_p = new Object[p.Length];
            for (int i = 0; i < p.Length ; i++)
            {
                if (p[i] is int)
                    lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
                else if (p[i] is string)
                    lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
                else if (p[i] is Vector3)
                    lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
                else if (p[i] is Quaternion)
                    lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
                else if (p[i] is float)
                    lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
                else
                    lsl_p[i] = p[i];
            }

            return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
        }

        public bool PostObjectEvent(UUID itemID, string name, Object[] p)
        {
            SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
            if (part == null)
                return false;

            Object[] lsl_p = new Object[p.Length];
            for (int i = 0; i < p.Length ; i++)
            {
                if (p[i] is int)
                    lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
                else if (p[i] is string)
                    lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
                else if (p[i] is Vector3)
                    lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
                else if (p[i] is Quaternion)
                    lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
                else if (p[i] is float)
                    lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
                else
                    lsl_p[i] = p[i];
            }

            return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
        }

        public Assembly OnAssemblyResolve(object sender,
                                          ResolveEventArgs args)
        {
            if (!(sender is System.AppDomain))
                return null;

            string[] pathList = new string[] {"bin", m_ScriptEnginesPath,
                                              Path.Combine(m_ScriptEnginesPath,
                                                           m_Scene.RegionInfo.RegionID.ToString())};

            string assemblyName = args.Name;
            if (assemblyName.IndexOf(",") != -1)
                assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));

            foreach (string s in pathList)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(),
                                           Path.Combine(s, assemblyName))+".dll";

//                Console.WriteLine("[XEngine]: Trying to resolve {0}", path);

                if (File.Exists(path))
                    return Assembly.LoadFrom(path);
            }

            return null;
        }

        private IScriptInstance GetInstance(UUID itemID)
        {
            IScriptInstance instance;
            lockScriptsForRead(true);
            if (!m_Scripts.ContainsKey(itemID))
            {
                lockScriptsForRead(false);
                return null;
            }
            instance = m_Scripts[itemID];
            lockScriptsForRead(false);
            return instance;
        }

        public void SetScriptState(UUID itemID, bool running)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
            {
                if (running)
                    instance.Start();
                else
                    instance.Stop(100);
            }
        }

        public bool GetScriptState(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.Running;
            return false;
        }

        [DebuggerNonUserCode]
        public void ApiResetScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.ApiResetScript();
        }

        public void ResetScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.ResetScript(m_WaitForEventCompletionOnScriptStop);
        }

        public void StartScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.Start();
            else
                m_runFlags.AddOrUpdate(itemID, true, 240);
        }

        public void StopScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);

            if (instance != null)
                instance.Stop(m_WaitForEventCompletionOnScriptStop);
            else
                m_runFlags.AddOrUpdate(itemID, false, 240);
        }

        public DetectParams GetDetectParams(UUID itemID, int idx)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.GetDetectParams(idx);
            return null;
        }

        public void SetMinEventDelay(UUID itemID, double delay)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.MinEventDelay = delay;
        }

        public UUID GetDetectID(UUID itemID, int idx)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.GetDetectID(idx);
            return UUID.Zero;
        }

        [DebuggerNonUserCode]
        public void SetState(UUID itemID, string newState)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return;
            instance.SetState(newState);
        }

        public int GetStartParameter(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return 0;
            return instance.StartParam;
        }

        public void OnShutdown()
        {
            m_SimulatorShuttingDown = true;

            List<IScriptInstance> instances = new List<IScriptInstance>();

            lockScriptsForRead(true);
            foreach (IScriptInstance instance in m_Scripts.Values)
                    instances.Add(instance);
            lockScriptsForRead(false);

            foreach (IScriptInstance i in instances)
            {
                // Stop the script, even forcibly if needed. Then flag
                // it as shutting down and restore the previous run state
                // for serialization, so the scripts don't come back
                // dead after region restart
                //
                bool prevRunning = i.Running;
                i.Stop(50);
                i.ShuttingDown = true;
                i.Running = prevRunning;
            }

            DoBackup(new Object[] {0});
        }

        public IScriptApi GetApi(UUID itemID, string name)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return null;
            return instance.GetApi(name);
        }

        public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return;
            IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
            if (eq == null)
            {
                controllingClient.SendScriptRunningReply(objectID, itemID,
                        GetScriptState(itemID));
            }
            else
            {
                eq.Enqueue(eq.ScriptRunningEvent(objectID, itemID, GetScriptState(itemID), true),
                           controllingClient.AgentId);
            }
        }

        public string GetXMLState(UUID itemID)
        {
//            m_log.DebugFormat("[XEngine]: Getting XML state for script instance {0}", itemID);

            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
            {
//                m_log.DebugFormat("[XEngine]: Found no script instance for {0}, returning empty string", itemID);
                return "";
            }

            string xml = instance.GetXMLState();

            XmlDocument sdoc = new XmlDocument();
            bool loadedState = true;
            try
            {
                sdoc.LoadXml(xml);
            }
            catch (System.Xml.XmlException)
            {
                loadedState = false;
            }

            XmlNodeList rootL = null;
            XmlNode rootNode = null;
            if (loadedState)
            {
                rootL = sdoc.GetElementsByTagName("ScriptState");
                rootNode = rootL[0];
            }

            // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
            XmlDocument doc = new XmlDocument();
            XmlElement stateData = doc.CreateElement("", "State", "");
            XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
            stateID.Value = itemID.ToString();
            stateData.Attributes.Append(stateID);
            XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
            assetID.Value = instance.AssetID.ToString();
            stateData.Attributes.Append(assetID);
            XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
            engineName.Value = ScriptEngineName;
            stateData.Attributes.Append(engineName);
            doc.AppendChild(stateData);

            XmlNode xmlstate = null;

            // Add <ScriptState>...</ScriptState>
            if (loadedState)
            {
                xmlstate = doc.ImportNode(rootNode, true);
            }
            else
            {
                xmlstate = doc.CreateElement("", "ScriptState", "");
            }

            stateData.AppendChild(xmlstate);

            string assemName = instance.GetAssemblyName();

            string fn = Path.GetFileName(assemName);

            string assem = String.Empty;

            if (File.Exists(assemName + ".text"))
            {
                FileInfo tfi = new FileInfo(assemName + ".text");

                if (tfi != null)
                {
                    Byte[] tdata = new Byte[tfi.Length];

                    try
                    {
                        using (FileStream tfs = File.Open(assemName + ".text",
                                FileMode.Open, FileAccess.Read))
                        {
                            tfs.Read(tdata, 0, tdata.Length);
                        }

                        assem = Encoding.ASCII.GetString(tdata);
                    }
                    catch (Exception e)
                    {
                         m_log.ErrorFormat(
                            "[XEngine]: Unable to open script textfile {0}{1}, reason: {2}",
                            assemName, ".text", e.Message);
                    }
                }
            }
            else
            {
                FileInfo fi = new FileInfo(assemName);

                if (fi != null)
                {
                    Byte[] data = new Byte[fi.Length];

                    try
                    {
                        using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
                        {
                            fs.Read(data, 0, data.Length);
                        }

                        assem = System.Convert.ToBase64String(data);
                    }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat(
                            "[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
                    }
                }
            }

            string map = String.Empty;

            if (File.Exists(fn + ".map"))
            {
                using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader msr = new StreamReader(mfs))
                    {
                        map = msr.ReadToEnd();
                    }
                }
            }

            XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
            XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");

            assemblyName.Value = fn;
            assemblyData.Attributes.Append(assemblyName);

            assemblyData.InnerText = assem;

            stateData.AppendChild(assemblyData);

            XmlElement mapData = doc.CreateElement("", "LineMap", "");
            XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");

            mapName.Value = fn + ".map";
            mapData.Attributes.Append(mapName);

            mapData.InnerText = map;

            stateData.AppendChild(mapData);

//            m_log.DebugFormat("[XEngine]: Got XML state for {0}", itemID);

            return doc.InnerXml;
        }

        private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
        {
            return false;
        }

        public bool SetXMLState(UUID itemID, string xml)
        {
//            m_log.DebugFormat("[XEngine]: Writing state for script item with ID {0}", itemID);

            if (xml == String.Empty)
                return false;

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.LoadXml(xml);
            }
            catch (Exception)
            {
                m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
                return false;
            }

            XmlNodeList rootL = doc.GetElementsByTagName("State");
            if (rootL.Count < 1)
                return false;

            XmlElement rootE = (XmlElement)rootL[0];

            if (rootE.GetAttribute("Engine") != ScriptEngineName)
                return false;

//          On rez from inventory, that ID will have changed. It was only
//          advisory anyway. So we don't check it anymore.
//
//            if (rootE.GetAttribute("UUID") != itemID.ToString())
//                return;

            XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");

            if (stateL.Count != 1)
                return false;

            XmlElement stateE = (XmlElement)stateL[0];

            if (World.m_trustBinaries)
            {
                XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");

                if (assemL.Count != 1)
                    return false;

                XmlElement assemE = (XmlElement)assemL[0];

                string fn = assemE.GetAttribute("Filename");
                string base64 = assemE.InnerText;

                string path = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
                path = Path.Combine(path, fn);

                if (!File.Exists(path))
                {
                    Byte[] filedata = Convert.FromBase64String(base64);

                    try
                    {
                        using (FileStream fs = File.Create(path))
                        {
//                            m_log.DebugFormat("[XEngine]: Writing assembly file {0}", path);

                            fs.Write(filedata, 0, filedata.Length);
                        }
                    }
                    catch (IOException ex)
                    {
                        // if there already exists a file at that location, it may be locked.
                        m_log.ErrorFormat("[XEngine]: Error whilst writing assembly file {0}, {1}", path, ex.Message);
                    }

                    string textpath = path + ".text";
                    try
                    {
                        using (FileStream fs = File.Create(textpath))
                        {
                            using (StreamWriter sw = new StreamWriter(fs))
                            {
//                                m_log.DebugFormat("[XEngine]: Writing .text file {0}", textpath);

                                sw.Write(base64);
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        // if there already exists a file at that location, it may be locked.
                        m_log.ErrorFormat("[XEngine]: Error whilst writing .text file {0}, {1}", textpath, ex.Message);
                    }
                }

                XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
                if (mapL.Count > 0)
                {
                    XmlElement mapE = (XmlElement)mapL[0];

                    string mappath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
                    mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));

                    try
                    {
                        using (FileStream mfs = File.Create(mappath))
                        {
                            using (StreamWriter msw = new StreamWriter(mfs))
                            {
    //                            m_log.DebugFormat("[XEngine]: Writing linemap file {0}", mappath);

                                msw.Write(mapE.InnerText);
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        // if there already exists a file at that location, it may be locked.
                        m_log.ErrorFormat("[XEngine]: Linemap file {0} already exists! {1}", mappath, ex.Message);
                    }
                }
            }

            string statepath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
            statepath = Path.Combine(statepath, itemID.ToString() + ".state");

            try
            {
                using (FileStream sfs = File.Create(statepath))
                {
                    using (StreamWriter ssw = new StreamWriter(sfs))
                    {
//                        m_log.DebugFormat("[XEngine]: Writing state file {0}", statepath);

                        ssw.Write(stateE.OuterXml);
                    }
                }
            }
            catch (IOException ex)
            {
                // if there already exists a file at that location, it may be locked.
                m_log.ErrorFormat("[XEngine]: Error whilst writing state file {0}, {1}", statepath, ex.Message);
            }

            return true;
        }

        public ArrayList GetScriptErrors(UUID itemID)
        {
            System.Threading.Thread.Sleep(1000);

            lock (m_ScriptErrors)
            {
                if (m_ScriptErrors.ContainsKey(itemID))
                {
                    ArrayList ret = m_ScriptErrors[itemID];
                    m_ScriptErrors.Remove(itemID);
                    return ret;
                }
                return new ArrayList();
            }
        }

        public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
        {
            long tickNow = Util.EnvironmentTickCount();
            Dictionary<uint, float> topScripts = new Dictionary<uint, float>();

            lock (m_Scripts)
            {
                foreach (IScriptInstance si in m_Scripts.Values)
                {
                    if (!topScripts.ContainsKey(si.LocalID))
                        topScripts[si.RootLocalID] = 0;

                    topScripts[si.RootLocalID] += CalculateAdjustedExectionTime(si, tickNow);
                }
            }

            return topScripts;
        }

        public float GetScriptExecutionTime(List<UUID> itemIDs)
        {
            if (itemIDs == null|| itemIDs.Count == 0)
            {
                return 0.0f;
            }
            float time = 0.0f;
            long tickNow = Util.EnvironmentTickCount();
            IScriptInstance si;
            // Calculate the time for all scripts that this engine is executing
            // Ignore any others
            foreach (UUID id in itemIDs)
            {
                si = GetInstance(id);
                if (si != null && si.Running)
                {
                    time += CalculateAdjustedExectionTime(si, tickNow);
                }
            }
            return time;
        }

        private float CalculateAdjustedExectionTime(IScriptInstance si, long tickNow)
        {
            long ticksElapsed = tickNow - si.MeasurementPeriodTickStart;

            // Avoid divide by zero
            if (ticksElapsed == 0)
                ticksElapsed = 1;

            // Scale execution time to the ideal 55 fps frame time for these reasons.
            //
            // 1) XEngine does not execute scripts per frame, unlike other script engines.  Hence, there is no
            // 'script execution time per frame', which is the original purpose of this value.
            //
            // 2) Giving the raw execution times is misleading since scripts start at different times, making
            // it impossible to compare scripts.
            //
            // 3) Scaling the raw execution time to the time that the script has been running is better but
            // is still misleading since a script that has just been rezzed may appear to have been running
            // for much longer.
            //
            // 4) Hence, we scale execution time to an idealised frame time (55 fps).  This is also not perfect
            // since the figure does not represent actual execution time and very hard running scripts will
            // never exceed 18ms (though this is a very high number for script execution so is a warning sign).
            return ((float)si.MeasurementPeriodExecutionTime / ticksElapsed) * 18.1818f;
        }

        public void SuspendScript(UUID itemID)
        {
//            m_log.DebugFormat("[XEngine]: Received request to suspend script with ID {0}", itemID);

            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.Suspend();
//            else
//                m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
        }

        public void ResumeScript(UUID itemID)
        {
//            m_log.DebugFormat("[XEngine]: Received request to resume script with ID {0}", itemID);

            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.Resume();
//            else
//                m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
        }

        public bool HasScript(UUID itemID, out bool running)
        {
            running = true;

            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return false;

            running = instance.Running;
            return true;
        }
    }
}