aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework/Util.cs
blob: 83d9df19bbbb92389c7cd2b07c828a86a84b51d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
/*
 * 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.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Threading;
using log4net;
using log4net.Appender;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Amib.Threading;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Web;

namespace OpenSim.Framework
{
    [Flags]
    public enum PermissionMask : uint
    {
        None = 0,

        // folded perms
        FoldedTransfer = 1,
        FoldedModify = 1 << 1,
        FoldedCopy = 1 << 2,
        FoldedExport = 1 << 3,

        // DO NOT USE THIS FOR NEW WORK. IT IS DEPRECATED AND
        // EXISTS ONLY TO REACT TO EXISTING OBJECTS HAVING IT.
        // NEW CODE SHOULD NEVER SET THIS BIT!
        // Use InventoryItemFlags.ObjectSlamPerm in the Flags field of
        // this legacy slam bit. It comes from prior incomplete
        // understanding of the code and the prohibition on
        // reading viewer code that used to be in place.
        Slam = (1 << 4),

        FoldedMask = 0x0f,

        FoldingShift = 13 ,  // number of bit shifts from normal perm to folded or back (same as Transfer shift below)
                             // when doing as a block

        Transfer = 1 << 13, // 0x02000
        Modify = 1 << 14,   // 0x04000
        Copy = 1 << 15,     // 0x08000
        Export = 1 << 16,   // 0x10000
        Move = 1 << 19,     // 0x80000
        Damage = 1 << 20,   // 0x100000 does not seem to be in use
        // All does not contain Export, which is special and must be
        // explicitly given
        All = 0x8e000,
        AllAndExport = 0x9e000,
        AllEffective = 0x9e000,
        UnfoldedMask = 0x1e000
    }

    /// <summary>
    /// The method used by Util.FireAndForget for asynchronously firing events
    /// </summary>
    /// <remarks>
    /// None is used to execute the method in the same thread that made the call.  It should only be used by regression
    /// test code that relies on predictable event ordering.
    /// RegressionTest is used by regression tests.  It fires the call synchronously and does not catch any exceptions.
    /// </remarks>
    public enum FireAndForgetMethod
    {
        None,
        RegressionTest,
        UnsafeQueueUserWorkItem,
        QueueUserWorkItem,
        BeginInvoke,
        SmartThreadPool,
        Thread,
    }

    /// <summary>
    /// Class for delivering SmartThreadPool statistical information
    /// </summary>
    /// <remarks>
    /// We do it this way so that we do not directly expose STP.
    /// </remarks>
    public class STPInfo
    {
        public string Name { get; set; }
        public STPStartInfo STPStartInfo { get; set; }
        public WIGStartInfo WIGStartInfo { get; set; }
        public bool IsIdle { get; set; }
        public bool IsShuttingDown { get; set; }
        public int MaxThreads { get; set; }
        public int MinThreads { get; set; }
        public int InUseThreads { get; set; }
        public int ActiveThreads { get; set; }
        public int WaitingCallbacks { get; set; }
        public int MaxConcurrentWorkItems { get; set; }
    }

    /// <summary>
    /// Miscellaneous utility functions
    /// </summary>
    public static class Util
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Log-level for the thread pool:
        /// 0 = no logging
        /// 1 = only first line of stack trace; don't log common threads
        /// 2 = full stack trace; don't log common threads
        /// 3 = full stack trace, including common threads
        /// </summary>
        public static int LogThreadPool { get; set; }
        public static bool LogOverloads { get; set; }

        public static readonly int MAX_THREADPOOL_LEVEL = 3;

        public static double TimeStampClockPeriodMS;

        static Util()
        {
            LogThreadPool = 0;
            LogOverloads = true;
            TimeStampClockPeriodMS = 1000.0D / (double)Stopwatch.Frequency;
            m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero));
        }

        private static uint nextXferID = 5000;
        private static Random randomClass = new ThreadSafeRandom();

        // Get a list of invalid file characters (OS dependent)
        private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
        private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
        private static object XferLock = new object();

        /// <summary>
        /// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
        /// </summary>
        private static SmartThreadPool m_ThreadPool;

        // Watchdog timer that aborts threads that have timed-out
        private static Timer m_threadPoolWatchdog;

        // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
        public static readonly DateTime UnixEpoch =
            DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();

        private static readonly string rawUUIDPattern
            = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
        public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
        public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));

        public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
        public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;

        public static bool IsPlatformMono
        {
            get { return Type.GetType("Mono.Runtime") != null; }
        }

        /// <summary>
        /// Gets the name of the directory where the current running executable
        /// is located
        /// </summary>
        /// <returns>Filesystem path to the directory containing the current
        /// executable</returns>
        public static string ExecutingDirectory()
        {
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        }

        /// <summary>
        /// Linear interpolates B<->C using percent A
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static double lerp(double a, double b, double c)
        {
            return (b*a) + (c*(1 - a));
        }

        /// <summary>
        /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
        /// Layout:
        ///     A B
        ///     C D
        /// A<->C = Y
        /// C<->D = X
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        public static double lerp2D(double x, double y, double a, double b, double c, double d)
        {
            return lerp(y, lerp(x, a, b), lerp(x, c, d));
        }

        public static Encoding UTF8 = Encoding.UTF8;
        public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);

        /// <value>
        /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
        /// </value>
        public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");

        #region Vector Equations

        /// <summary>
        /// Get the distance between two 3d vectors
        /// </summary>
        /// <param name="a">A 3d vector</param>
        /// <param name="b">A 3d vector</param>
        /// <returns>The distance between the two vectors</returns>
        public static double GetDistanceTo(Vector3 a, Vector3 b)
        {
            float dx = a.X - b.X;
            float dy = a.Y - b.Y;
            float dz = a.Z - b.Z;
            return Math.Sqrt(dx * dx + dy * dy + dz * dz);
        }

        /// <summary>
        /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
        {
            float dx = a.X - b.X;
            float dy = a.Y - b.Y;
            float dz = a.Z - b.Z;
            return (dx*dx + dy*dy + dz*dz) < (amount*amount);
        }

        /// <summary>
        /// Get the magnitude of a 3d vector
        /// </summary>
        /// <param name="a">A 3d vector</param>
        /// <returns>The magnitude of the vector</returns>
        public static double GetMagnitude(Vector3 a)
        {
            return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
        }

        /// <summary>
        /// Get a normalized form of a 3d vector
        /// </summary>
        /// <param name="a">A 3d vector</param>
        /// <returns>A new vector which is normalized form of the vector</returns>

        public static Vector3 GetNormalizedVector(Vector3 a)
        {
            Vector3 v = new Vector3(a.X, a.Y, a.Z);
            v.Normalize();
            return v;
        }

        /// <summary>
        /// Returns if a vector is a zero vector (has all zero components)
        /// </summary>
        /// <returns></returns>
        public static bool IsZeroVector(Vector3 v)
        {
            if (v.X == 0 && v.Y == 0 && v.Z == 0)
            {
                return true;
            }

            return false;
        }

        # endregion

        public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
        {
            float s;
            float tr = (float) (fwd.X + left.Y + up.Z + 1.0);

            if (tr >= 1.0)
            {
                s = (float) (0.5 / Math.Sqrt(tr));
                return new Quaternion(
                        (left.Z - up.Y) * s,
                        (up.X - fwd.Z) * s,
                        (fwd.Y - left.X) * s,
                        (float) 0.25 / s);
            }
            else
            {
                float max = (left.Y > up.Z) ? left.Y : up.Z;

                if (max < fwd.X)
                {
                    s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
                    float x = (float) (s * 0.5);
                    s = (float) (0.5 / s);
                    return new Quaternion(
                            x,
                            (fwd.Y + left.X) * s,
                            (up.X + fwd.Z) * s,
                            (left.Z - up.Y) * s);
                }
                else if (max == left.Y)
                {
                    s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
                    float y = (float) (s * 0.5);
                    s = (float) (0.5 / s);
                    return new Quaternion(
                            (fwd.Y + left.X) * s,
                            y,
                            (left.Z + up.Y) * s,
                            (up.X - fwd.Z) * s);
                }
                else
                {
                    s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
                    float z = (float) (s * 0.5);
                    s = (float) (0.5 / s);
                    return new Quaternion(
                            (up.X + fwd.Z) * s,
                            (left.Z + up.Y) * s,
                            z,
                            (fwd.Y - left.X) * s);
                }
            }
        }

        public static Random RandomClass
        {
            get { return randomClass; }
        }

        public static ulong UIntsToLong(uint X, uint Y)
        {
            return Utils.UIntsToLong(X, Y);
        }

        // Regions are identified with a 'handle' made up of its world coordinates packed into a ulong.
        // Region handles are based on the coordinate of the region corner with lower X and Y
        // var regions need more work than this to get that right corner from a generic world position
        // this corner must be on a grid point
        public static ulong RegionWorldLocToHandle(uint X, uint Y)
        {
           ulong handle = X & 0xffffff00; // make sure it matchs grid coord points.
           handle <<= 32; // to higher half
           handle |= (Y & 0xffffff00);
           return handle;
        }

        public static ulong RegionGridLocToHandle(uint X, uint Y)
        {
            ulong handle = X;
            handle <<= 40; // shift to higher half and mult by 256)
            handle |= (Y << 8);  // mult by 256)
            return handle;
        }

        public static void RegionHandleToWorldLoc(ulong handle, out uint X, out uint Y)
        {
            X = (uint)(handle >> 32);
            Y = (uint)(handle & 0xfffffffful);
        }

        public static void RegionHandleToRegionLoc(ulong handle, out uint X, out uint Y)
        {
            X = (uint)(handle >> 40) & 0x00ffffffu; //  bring from higher half, divide by 256 and clean
            Y = (uint)(handle >> 8) & 0x00ffffffu; // divide by 256 and clean
            // if you trust the uint cast then the clean can be removed.
        }

        // A region location can be 'world coordinates' (meters) or 'region grid coordinates'
        // grid coordinates have a fixed step of 256m as defined by viewers
        public static uint WorldToRegionLoc(uint worldCoord)
        {
            return worldCoord >> 8;
        }

        // Convert a region's 'region grid coordinate' to its 'world coordinate'.
        public static uint RegionToWorldLoc(uint regionCoord)
        {
            return regionCoord << 8;
        }

        public static IPEndPoint getEndPoint(IPAddress ia, int port)
        {
            if(ia == null)
                return null;

            IPEndPoint newEP = null;
            try
            {
                newEP = new IPEndPoint(ia, port);
            }
            catch
            {
                newEP = null;
            }
            return newEP;
        }

        public static IPEndPoint getEndPoint(string hostname, int port)
        {
            IPAddress ia = null;
            // If it is already an IP, don't resolve it - just return directly
            // we should not need this
            if (IPAddress.TryParse(hostname, out ia))
            {
                if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
                    return null;
                return getEndPoint(ia, port);
            }
                    
            // Reset for next check
            ia = null;
            try
            {
                foreach (IPAddress Adr in Dns.GetHostAddresses(hostname))
                {
                    if (ia == null)
                        ia = Adr;

                    if (Adr.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ia = Adr;
                        break;
                    }
                }
            }
            catch // (SocketException e)
            {
                /*throw new Exception(
                    "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" +
                    e + "' attached to this exception", e);*/
                // Don't throw a fatal exception here, instead, return Null and handle it in the caller.
                // Reason is, on systems such as OSgrid it has occured that known hostnames stop
                // resolving and thus make surrounding regions crash out with this exception.
                return null;
            }

            return getEndPoint(ia,port);
        }

        public static bool checkServiceURI(string uristr, out string serviceURI)
        {
            serviceURI = string.Empty;
            try
            {
                Uri  uri = new Uri(uristr);
                serviceURI = uri.AbsoluteUri;
                if(uri.Port == 80)
                    serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":80/";
                else if(uri.Port == 443)
                    serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":443/";
                return true;
            }
            catch
            {
                serviceURI = string.Empty;
            }
            return false;
        }

        public static bool buildHGRegionURI(string inputName, out string serverURI, out string regionName)
        {
            serverURI = string.Empty;
            regionName = string.Empty;

            inputName = inputName.Trim();

            if (!inputName.StartsWith("http") && !inputName.StartsWith("https"))
            {
                // Formats: grid.example.com:8002:region name
                //          grid.example.com:region name
                //          grid.example.com:8002
                //          grid.example.com

                string host;
                uint port = 80;

                string[] parts = inputName.Split(new char[] { ':' });
                int indx;
                if(parts.Length == 0)
                    return false;
                if (parts.Length == 1)
                {
                    indx = inputName.IndexOf('/');
                    if (indx < 0)
                        serverURI = "http://"+ inputName + "/";
                    else
                    {
                        serverURI = "http://"+ inputName.Substring(0,indx + 1);
                        if(indx + 2 < inputName.Length)
                            regionName = inputName.Substring(indx + 1);
                    }
                }
                else
                {
                    host = parts[0];

                    if (parts.Length >= 2)
                    {
                        indx = parts[1].IndexOf('/');
                        if(indx < 0)
                        {
                            // If it's a number then assume it's a port. Otherwise, it's a region name.
                            if (!UInt32.TryParse(parts[1], out port))
                            {
                                port = 80;
                                regionName = parts[1];
                            }
                        }
                        else
                        {
                            string portstr = parts[1].Substring(0, indx);
                            if(indx + 2 < parts[1].Length)
                                regionName = parts[1].Substring(indx + 1);
                            if (!UInt32.TryParse(portstr, out port))
                                port = 80;
                        }
                    }
                    // always take the last one
                    if (parts.Length >= 3)
                    {
                       regionName = parts[2];
                    }

                    serverURI = "http://"+ host +":"+ port.ToString() + "/";
                }
            }
            else
            {
                // Formats: http://grid.example.com region name
                //          http://grid.example.com "region name"
                //          http://grid.example.com

                string[] parts = inputName.Split(new char[] { ' ' });

                if (parts.Length == 0)
                    return false;

                serverURI = parts[0];

                int indx = serverURI.LastIndexOf('/');
                if(indx > 10)
                {
                    if(indx + 2 < inputName.Length)
                        regionName = inputName.Substring(indx + 1);
                    serverURI = inputName.Substring(0, indx + 1);
                }
                else if (parts.Length >= 2)
                {
                    regionName = inputName.Substring(serverURI.Length);
                }
            }

            // use better code for sanity check
            Uri uri;
            try
            {
                    uri = new Uri(serverURI);
            }
            catch
            {
                return false;
            }

            if(!string.IsNullOrEmpty(regionName))
                regionName = regionName.Trim(new char[] { '"', ' ' });
            serverURI = uri.AbsoluteUri;
            if(uri.Port == 80)
                serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":80/";
            else if(uri.Port == 443)
                serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":443/";
            return true;
        }

        public static T Clamp<T>(T x, T min, T max)
            where T : IComparable<T>
        {
            return x.CompareTo(max) > 0 ? max :
                x.CompareTo(min) < 0 ? min :
                x;
        }

        // Clamp the maximum magnitude of a vector
        public static Vector3 ClampV(Vector3 x, float max)
        {
            float lenSq = x.LengthSquared();
            if (lenSq > (max * max))
            {
                x = x / x.Length() * max;
            }

            return x;
        }

        /// <summary>
        /// Check if any of the values in a Vector3 are NaN or Infinity
        /// </summary>
        /// <param name="v">Vector3 to check</param>
        /// <returns></returns>
        public static bool IsNanOrInfinity(Vector3 v)
        {
            if (float.IsNaN(v.X) || float.IsNaN(v.Y) || float.IsNaN(v.Z))
                return true;

            if (float.IsInfinity(v.X) || float.IsInfinity(v.Y) || float.IsNaN(v.Z))
                return true;

            return false;
        }

        // Inclusive, within range test (true if equal to the endpoints)
        public static bool InRange<T>(T x, T min, T max)
            where T : IComparable<T>
        {
            return x.CompareTo(max) <= 0 && x.CompareTo(min) >= 0;
        }

        public static uint GetNextXferID()
        {
            uint id = 0;
            lock (XferLock)
            {
                id = nextXferID;
                nextXferID++;
            }
            return id;
        }

        public static string GetFileName(string file)
        {
            // Return just the filename on UNIX platforms
            // TODO: this should be customisable with a prefix, but that's something to do later.
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                return file;
            }

            // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
            // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
                {
                    Directory.CreateDirectory("%APPDATA%\\OpenSim");
                }

                return "%APPDATA%\\OpenSim\\" + file;
            }

            // Catch all - covers older windows versions
            // (but those probably wont work anyway)
            return file;
        }

        /// <summary>
        /// Debug utility function to convert OSD into formatted XML for debugging purposes.
        /// </summary>
        /// <param name="osd">
        /// A <see cref="OSD"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.String"/>
        /// </returns>
        public static string GetFormattedXml(OSD osd)
        {
            return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
        }

        /// <summary>
        /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
        /// </summary>
        /// <remarks>
        /// Please don't delete me even if I appear currently unused!
        /// </remarks>
        /// <param name="rawXml"></param>
        /// <returns></returns>
        public static string GetFormattedXml(string rawXml)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(rawXml);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            XmlTextWriter xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;

            try
            {
                xd.WriteTo(xtw);
            }
            finally
            {
                xtw.Close();
            }

            return sb.ToString();
        }

        public static byte[] DocToBytes(XmlDocument doc)
        {
            using (MemoryStream ms = new MemoryStream())
            using (XmlTextWriter xw = new XmlTextWriter(ms, null))
            {
                xw.Formatting = Formatting.Indented;
                doc.WriteTo(xw);
                xw.Flush();

                return ms.ToArray();
            }
        }

        /// <summary>
        /// Is the platform Windows?
        /// </summary>
        /// <returns>true if so, false otherwise</returns>
        public static bool IsWindows()
        {
            PlatformID platformId = Environment.OSVersion.Platform;

            return (platformId == PlatformID.Win32NT
                || platformId == PlatformID.Win32S
                || platformId == PlatformID.Win32Windows
                || platformId == PlatformID.WinCE);
        }

        public static bool LoadArchSpecificWindowsDll(string libraryName)
        {
            return LoadArchSpecificWindowsDll(libraryName, string.Empty);
        }

        public static bool LoadArchSpecificWindowsDll(string libraryName, string path)
        {
            // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
            // it's running as a 32-bit process or a 64-bit one.  By invoking LoadLibary here, later DLLImports
            // will find it already loaded later on.
            //
            // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
            // controlled in config files.
            string nativeLibraryPath;

            if (Util.Is64BitProcess())
                nativeLibraryPath = Path.Combine(Path.Combine(path, "lib64"), libraryName);
            else
                nativeLibraryPath = Path.Combine(Path.Combine(path, "lib32"), libraryName);

            m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);

            if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
            {
                m_log.ErrorFormat(
                    "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);

                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool IsEnvironmentSupported(ref string reason)
        {
            // Must have .NET 2.0 (Generics / libsl)
            if (Environment.Version.Major < 2)
            {
                reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
                return false;
            }

            // Windows 95/98/ME are unsupported
            if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
                Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                reason = "Windows 95/98/ME will not run OpenSim";
                return false;
            }

            // Windows 2000 / Pre-SP2 XP
            if (Environment.OSVersion.Version.Major == 5 &&
                Environment.OSVersion.Version.Minor == 0)
            {
                reason = "Please update to Windows XP Service Pack 2 or Server2003";
                return false;
            }

            return true;
        }

        public static int UnixTimeSinceEpoch()
        {
            return ToUnixTime(DateTime.UtcNow);
        }

        public static int ToUnixTime(DateTime stamp)
        {
            TimeSpan t = stamp.ToUniversalTime() - UnixEpoch;
            return (int)t.TotalSeconds;
        }

        public static DateTime ToDateTime(ulong seconds)
        {
            return UnixEpoch.AddSeconds(seconds);
        }

        public static DateTime ToDateTime(int seconds)
        {
            return UnixEpoch.AddSeconds(seconds);
        }

        /// <summary>
        /// Return an md5 hash of the given string
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        public static string Md5Hash(string data)
        {
            return Md5Hash(data, Encoding.Default);
        }

        public static string Md5Hash(string data, Encoding encoding)
        {
            byte[] dataMd5 = ComputeMD5Hash(data, encoding);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dataMd5.Length; i++)
                sb.AppendFormat("{0:x2}", dataMd5[i]);
            return sb.ToString();
        }

        private static byte[] ComputeMD5Hash(string data, Encoding encoding)
        {
            MD5 md5 = MD5.Create();
            return md5.ComputeHash(encoding.GetBytes(data));
        }

        /// <summary>
        /// Return an SHA1 hash
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        public static string SHA1Hash(string data, Encoding enc)
        {
            return SHA1Hash(enc.GetBytes(data));
        }

        public static string SHA1Hash(string data)
        {
            return SHA1Hash(Encoding.Default.GetBytes(data));
        }

        /// <summary>
        /// Return an SHA1 hash
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string SHA1Hash(byte[] data)
        {
            byte[] hash = ComputeSHA1Hash(data);
            return BitConverter.ToString(hash).Replace("-", String.Empty);
        }

        private static byte[] ComputeSHA1Hash(byte[] src)
        {
            byte[] ret;
            using(SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider())
                 ret = SHA1.ComputeHash(src);
            return ret;
        }

        public static int fast_distance2d(int x, int y)
        {
            x = Math.Abs(x);
            y = Math.Abs(y);

            int min = Math.Min(x, y);

            return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
        }

        /// <summary>
        /// Determines whether a point is inside a bounding box.
        /// </summary>
        /// <param name='v'></param>
        /// <param name='min'></param>
        /// <param name='max'></param>
        /// <returns></returns>
        public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
        {
            return v.X >= min.X & v.Y >= min.Y && v.Z >= min.Z
                && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
        }

        /// <summary>
        /// Are the co-ordinates of the new region visible from the old region?
        /// </summary>
        /// <param name="oldx">Old region x-coord</param>
        /// <param name="newx">New region x-coord</param>
        /// <param name="oldy">Old region y-coord</param>
        /// <param name="newy">New region y-coord</param>
        /// <returns></returns>
        public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy,
            int oldsizex, int oldsizey, int newsizex, int newsizey)
        {
            // we still need to make sure we see new region  1stNeighbors
            drawdist--;
            oldx *= Constants.RegionSize;
            newx *= Constants.RegionSize;
            if (oldx + oldsizex + drawdist < newx)
                return true;
            if (newx + newsizex + drawdist < oldx)
                return true;

            oldy *= Constants.RegionSize;
            newy *= Constants.RegionSize;
            if (oldy + oldsizey + drawdist < newy)
                return true;
            if (newy + newsizey + drawdist < oldy)
                return true;

            return false;
        }

        public static string FieldToString(byte[] bytes)
        {
            return FieldToString(bytes, String.Empty);
        }

        /// <summary>
        /// Convert a variable length field (byte array) to a string, with a
        /// field name prepended to each line of the output
        /// </summary>
        /// <remarks>If the byte array has unprintable characters in it, a
        /// hex dump will be put in the string instead</remarks>
        /// <param name="bytes">The byte array to convert to a string</param>
        /// <param name="fieldName">A field name to prepend to each line of output</param>
        /// <returns>An ASCII string or a string containing a hex dump, minus
        /// the null terminator</returns>
        public static string FieldToString(byte[] bytes, string fieldName)
        {
            // Check for a common case
            if (bytes.Length == 0) return String.Empty;

            StringBuilder output = new StringBuilder();
            bool printable = true;

            for (int i = 0; i < bytes.Length; ++i)
            {
                // Check if there are any unprintable characters in the array
                if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
                    && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
                {
                    printable = false;
                    break;
                }
            }

            if (printable)
            {
                if (fieldName.Length > 0)
                {
                    output.Append(fieldName);
                    output.Append(": ");
                }

                output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
            }
            else
            {
                for (int i = 0; i < bytes.Length; i += 16)
                {
                    if (i != 0)
                        output.Append(Environment.NewLine);
                    if (fieldName.Length > 0)
                    {
                        output.Append(fieldName);
                        output.Append(": ");
                    }

                    for (int j = 0; j < 16; j++)
                    {
                        if ((i + j) < bytes.Length)
                            output.Append(String.Format("{0:X2} ", bytes[i + j]));
                        else
                            output.Append("   ");
                    }

                    for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
                    {
                        if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
                            output.Append((char) bytes[i + j]);
                        else
                            output.Append(".");
                    }
                }
            }

            return output.ToString();
        }

        /// <summary>
        /// Converts a URL to a IPAddress
        /// </summary>
        /// <param name="url">URL Standard Format</param>
        /// <returns>A resolved IP Address</returns>
        public static IPAddress GetHostFromURL(string url)
        {
            return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
        }

        /// <summary>
        /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
        /// </summary>
        /// <param name="dnsAddress">DNS Hostname</param>
        /// <returns>An IP address, or null</returns>
        public static IPAddress GetHostFromDNS(string dnsAddress)
        {
            // Is it already a valid IP? No need to look it up.
            IPAddress ipa;
            if (IPAddress.TryParse(dnsAddress, out ipa))
                return ipa;

            IPAddress[] hosts = null;

            // Not an IP, lookup required
            try
            {
                hosts = Dns.GetHostEntry(dnsAddress).AddressList;
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);

                // Still going to throw the exception on for now, since this was what was happening in the first place
                throw e;
            }

            foreach (IPAddress host in hosts)
            {
                if (host.AddressFamily == AddressFamily.InterNetwork)
                {
                    return host;
                }
            }

            if (hosts.Length > 0)
                return hosts[0];

            return null;
        }

        public static Uri GetURI(string protocol, string hostname, int port, string path)
        {
            return new UriBuilder(protocol, hostname, port, path).Uri;
        }

        /// <summary>
        /// Gets a list of all local system IP addresses
        /// </summary>
        /// <returns></returns>
        public static IPAddress[] GetLocalHosts()
        {
            return Dns.GetHostAddresses(Dns.GetHostName());
        }

        public static IPAddress GetLocalHost()
        {
            IPAddress[] iplist = GetLocalHosts();

            if (iplist.Length == 0) // No accessible external interfaces
            {
                IPAddress[] loopback = Dns.GetHostAddresses("localhost");
                IPAddress localhost = loopback[0];

                return localhost;
            }

            foreach (IPAddress host in iplist)
            {
                if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
                {
                    return host;
                }
            }

            if (iplist.Length > 0)
            {
                foreach (IPAddress host in iplist)
                {
                    if (host.AddressFamily == AddressFamily.InterNetwork)
                        return host;
                }
                // Well all else failed...
                return iplist[0];
            }

            return null;
        }

        /// <summary>
        /// Parses a foreign asset ID.
        /// </summary>
        /// <param name="id">A possibly-foreign asset ID: http://grid.example.com:8002/00000000-0000-0000-0000-000000000000 </param>
        /// <param name="url">The URL: http://grid.example.com:8002</param>
        /// <param name="assetID">The asset ID: 00000000-0000-0000-0000-000000000000. Returned even if 'id' isn't foreign.</param>
        /// <returns>True: this is a foreign asset ID; False: it isn't</returns>
        public static bool ParseForeignAssetID(string id, out string url, out string assetID)
        {
            url = String.Empty;
            assetID = String.Empty;

            UUID uuid;
            if (UUID.TryParse(id, out uuid))
            {
                assetID = uuid.ToString();
                return false;
            }

            if ((id.Length == 0) || (id[0] != 'h' && id[0] != 'H'))
                return false;

            Uri assetUri;
            if (!Uri.TryCreate(id, UriKind.Absolute, out assetUri) || assetUri.Scheme != Uri.UriSchemeHttp)
                return false;

            // Simian
            if (assetUri.Query != string.Empty)
            {
                NameValueCollection qscoll = HttpUtility.ParseQueryString(assetUri.Query);
                assetID = qscoll["id"];
                if (assetID != null)
                    url = id.Replace(assetID, ""); // Malformed again, as simian expects
                else
                    url = id; // !!! best effort
            }
            else // robust
            {
                url = "http://" + assetUri.Authority;
                assetID = assetUri.LocalPath.Trim(new char[] { '/' });
            }

            if (!UUID.TryParse(assetID, out uuid))
                return false;

            return true;
        }

        /// <summary>
        /// Removes all invalid path chars (OS dependent)
        /// </summary>
        /// <param name="path">path</param>
        /// <returns>safe path</returns>
        public static string safePath(string path)
        {
            return Regex.Replace(path, regexInvalidPathChars, String.Empty);
        }

        /// <summary>
        /// Removes all invalid filename chars (OS dependent)
        /// </summary>
        /// <param name="path">filename</param>
        /// <returns>safe filename</returns>
        public static string safeFileName(string filename)
        {
            return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
            ;
        }

        //
        // directory locations
        //

        public static string homeDir()
        {
            string temp;
            //            string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
            //            temp = Path.Combine(personal,".OpenSim");
            temp = ".";
            return temp;
        }

        public static string assetsDir()
        {
            return Path.Combine(configDir(), "assets");
        }

        public static string inventoryDir()
        {
            return Path.Combine(configDir(), "inventory");
        }

        public static string configDir()
        {
            return ".";
        }

        public static string dataDir()
        {
            return ".";
        }

        public static string logFile()
        {
            foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
            {
                if (appender is FileAppender && appender.Name == "LogFileAppender")
                {
                    return ((FileAppender)appender).File;
                }
            }

            return "./OpenSim.log";
        }

        public static string statsLogFile()
        {
            foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
            {
                if (appender is FileAppender && appender.Name == "StatsLogFileAppender")
                {
                    return ((FileAppender)appender).File;
                }
            }

            return "./OpenSimStats.log";
        }

        public static string logDir()
        {
            return Path.GetDirectoryName(logFile());
        }

        // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
        public static string GetUniqueFilename(string FileName)
        {
            int count = 0;
            string Name;

            if (File.Exists(FileName))
            {
                FileInfo f = new FileInfo(FileName);

                if (!String.IsNullOrEmpty(f.Extension))
                {
                    Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
                }
                else
                {
                    Name = f.FullName;
                }

                while (File.Exists(FileName))
                {
                    count++;
                    FileName = Name + count + f.Extension;
                }
            }
            return FileName;
        }

        #region Nini (config) related Methods

        public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
        {
            if (!File.Exists(fileName))
            {
                // create new file
            }
            XmlConfigSource config = new XmlConfigSource(fileName);
            AddDataRowToConfig(config, row);
            config.Save();

            return config;
        }

        public static void AddDataRowToConfig(IConfigSource config, DataRow row)
        {
            config.Configs.Add((string) row[0]);
            for (int i = 0; i < row.Table.Columns.Count; i++)
            {
                config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
            }
        }

        public static string GetConfigVarWithDefaultSection(IConfigSource config, string varname, string section)
        {
            // First, check the Startup section, the default section
            IConfig cnf = config.Configs["Startup"];
            if (cnf == null)
                return string.Empty;
            string val = cnf.GetString(varname, string.Empty);

            // Then check for an overwrite of the default in the given section
            if (!string.IsNullOrEmpty(section))
            {
                cnf = config.Configs[section];
                if (cnf != null)
                    val = cnf.GetString(varname, val);
            }

            return val;
        }

        /// <summary>
        /// Gets the value of a configuration variable by looking into
        /// multiple sections in order. The latter sections overwrite
        /// any values previously found.
        /// </summary>
        /// <typeparam name="T">Type of the variable</typeparam>
        /// <param name="config">The configuration object</param>
        /// <param name="varname">The configuration variable</param>
        /// <param name="sections">Ordered sequence of sections to look at</param>
        /// <returns></returns>
        public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections)
        {
            return GetConfigVarFromSections<T>(config, varname, sections, default(T));
        }

        /// <summary>
        /// Gets the value of a configuration variable by looking into
        /// multiple sections in order. The latter sections overwrite
        /// any values previously found.
        /// </summary>
        /// <remarks>
        /// If no value is found then the given default value is returned
        /// </remarks>
        /// <typeparam name="T">Type of the variable</typeparam>
        /// <param name="config">The configuration object</param>
        /// <param name="varname">The configuration variable</param>
        /// <param name="sections">Ordered sequence of sections to look at</param>
        /// <param name="val">Default value</param>
        /// <returns></returns>
        public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections, object val)
        {
            foreach (string section in sections)
            {
                IConfig cnf = config.Configs[section];
                if (cnf == null)
                    continue;

                if (typeof(T) == typeof(String))
                    val = cnf.GetString(varname, (string)val);
                else if (typeof(T) == typeof(Boolean))
                    val = cnf.GetBoolean(varname, (bool)val);
                else if (typeof(T) == typeof(Int32))
                    val = cnf.GetInt(varname, (int)val);
                else if (typeof(T) == typeof(float))
                    val = cnf.GetFloat(varname, (float)val);
                else
                    m_log.ErrorFormat("[UTIL]: Unhandled type {0}", typeof(T));
            }

            return (T)val;
        }

        public static void MergeEnvironmentToConfig(IConfigSource ConfigSource)
        {
            IConfig enVars = ConfigSource.Configs["Environment"];
            // if section does not exist then user isn't expecting them, so don't bother.
            if( enVars != null )
            {
                // load the values from the environment
                EnvConfigSource envConfigSource = new EnvConfigSource();
                // add the requested keys
                string[] env_keys = enVars.GetKeys();
                foreach ( string key in env_keys )
                {
                    envConfigSource.AddEnv(key, string.Empty);
                }
                // load the values from environment
                envConfigSource.LoadEnv();
                // add them in to the master
                ConfigSource.Merge(envConfigSource);
                ConfigSource.ExpandKeyValues();
            }
        }

        public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
        {
            Type settingsType = settingsClass.GetType();

            FieldInfo[] fieldInfos = settingsType.GetFields();
            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                if (!fieldInfo.IsStatic)
                {
                    if (fieldInfo.FieldType == typeof(System.String))
                    {
                        fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
                    }
                    else if (fieldInfo.FieldType == typeof(System.Boolean))
                    {
                        fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
                    }
                    else if (fieldInfo.FieldType == typeof(System.Int32))
                    {
                        fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
                    }
                    else if (fieldInfo.FieldType == typeof(System.Single))
                    {
                        fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
                    }
                    else if (fieldInfo.FieldType == typeof(System.UInt32))
                    {
                        fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
                    }
                }
            }

            PropertyInfo[] propertyInfos = settingsType.GetProperties();
            foreach (PropertyInfo propInfo in propertyInfos)
            {
                if ((propInfo.CanRead) && (propInfo.CanWrite))
                {
                    if (propInfo.PropertyType == typeof(System.String))
                    {
                        propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
                    }
                    else if (propInfo.PropertyType == typeof(System.Boolean))
                    {
                        propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
                    }
                    else if (propInfo.PropertyType == typeof(System.Int32))
                    {
                        propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
                    }
                    else if (propInfo.PropertyType == typeof(System.Single))
                    {
                        propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
                    }
                    if (propInfo.PropertyType == typeof(System.UInt32))
                    {
                        propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
                    }
                }
            }

            return settingsClass;
        }

        /// <summary>
        /// Reads a configuration file, configFile, merging it with the main configuration, config.
        /// If the file doesn't exist, it copies a given exampleConfigFile onto configFile, and then
        /// merges it.
        /// </summary>
        /// <param name="config">The main configuration data</param>
        /// <param name="configFileName">The name of a configuration file in ConfigDirectory variable, no path</param>
        /// <param name="exampleConfigFile">Full path to an example configuration file</param>
        /// <param name="configFilePath">Full path ConfigDirectory/configFileName</param>
        /// <param name="created">True if the file was created in ConfigDirectory, false if it existed</param>
        /// <returns>True if success</returns>
        public static bool MergeConfigurationFile(IConfigSource config, string configFileName, string exampleConfigFile, out string configFilePath, out bool created)
        {
            created = false;
            configFilePath = string.Empty;

            IConfig cnf = config.Configs["Startup"];
            if (cnf == null)
            {
                m_log.WarnFormat("[UTILS]: Startup section doesn't exist");
                return false;
            }

            string configDirectory = cnf.GetString("ConfigDirectory", ".");
            string configFile = Path.Combine(configDirectory, configFileName);

            if (!File.Exists(configFile) && !string.IsNullOrEmpty(exampleConfigFile))
            {
                // We need to copy the example onto it

                if (!Directory.Exists(configDirectory))
                    Directory.CreateDirectory(configDirectory);

                try
                {
                    File.Copy(exampleConfigFile, configFile);
                    created = true;
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[UTILS]: Exception copying configuration file {0} to {1}: {2}", configFile, exampleConfigFile, e.Message);
                    return false;
                }
            }

            if (File.Exists(configFile))
            {
                // Merge
                config.Merge(new IniConfigSource(configFile));
                config.ExpandKeyValues();
                configFilePath = configFile;
                return true;
            }
            else
                return false;
        }

        #endregion

        public static float Clip(float x, float min, float max)
        {
            return Math.Min(Math.Max(x, min), max);
        }

        public static int Clip(int x, int min, int max)
        {
            return Math.Min(Math.Max(x, min), max);
        }

        public static Vector3 Clip(Vector3 vec, float min, float max)
        {
            return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
                Clip(vec.Z, min, max));
        }

        /// <summary>
        /// Convert an UUID to a raw uuid string.  Right now this is a string without hyphens.
        /// </summary>
        /// <param name="UUID"></param>
        /// <returns></returns>
        public static String ToRawUuidString(UUID UUID)
        {
            return UUID.Guid.ToString("n");
        }

        public static string CleanString(string input)
        {
            if (input.Length == 0)
                return input;

            int clip = input.Length;

            // Test for ++ string terminator
            int pos = input.IndexOf("\0");
            if (pos != -1 && pos < clip)
                clip = pos;

            // Test for CR
            pos = input.IndexOf("\r");
            if (pos != -1 && pos < clip)
                clip = pos;

            // Test for LF
            pos = input.IndexOf("\n");
            if (pos != -1 && pos < clip)
                clip = pos;

            // Truncate string before first end-of-line character found
            return input.Substring(0, clip);
        }

        /// <summary>
        /// returns the contents of /etc/issue on Unix Systems
        /// Use this for where it's absolutely necessary to implement platform specific stuff
        /// </summary>
        /// <returns></returns>
        public static string ReadEtcIssue()
        {
            try
            {
                StreamReader sr = new StreamReader("/etc/issue.net");
                string issue = sr.ReadToEnd();
                sr.Close();
                return issue;
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static void SerializeToFile(string filename, Object obj)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;

            try
            {
                stream = new FileStream(
                    filename, FileMode.Create,
                    FileAccess.Write, FileShare.None);

                formatter.Serialize(stream, obj);
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }

        public static Object DeserializeFromFile(string filename)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;
            Object ret = null;

            try
            {
                stream = new FileStream(
                    filename, FileMode.Open,
                    FileAccess.Read, FileShare.None);

                ret = formatter.Deserialize(stream);
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            return ret;
        }

        public static string Compress(string text)
        {
            byte[] buffer = Util.UTF8.GetBytes(text);
            MemoryStream memory = new MemoryStream();
            using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
            {
                compressor.Write(buffer, 0, buffer.Length);
            }

            memory.Position = 0;

            byte[] compressed = new byte[memory.Length];
            memory.Read(compressed, 0, compressed.Length);

            byte[] compressedBuffer = new byte[compressed.Length + 4];
            Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
            return Convert.ToBase64String(compressedBuffer);
        }

        public static string Decompress(string compressedText)
        {
            byte[] compressedBuffer = Convert.FromBase64String(compressedText);
            using (MemoryStream memory = new MemoryStream())
            {
                int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
                memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);

                byte[] buffer = new byte[msgLength];

                memory.Position = 0;
                using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
                {
                    decompressor.Read(buffer, 0, buffer.Length);
                }

                return Util.UTF8.GetString(buffer);
            }
        }

        /// <summary>
        /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
        /// </summary>
        /// <param name='inputStream'>
        /// Input stream.  Must be seekable.
        /// </param>
        /// <exception cref='ArgumentException'>
        /// Thrown if the input stream is not seekable.
        /// </exception>
        public static Stream Copy(Stream inputStream)
        {
            if (!inputStream.CanSeek)
                throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");

            const int readSize = 256;
            byte[] buffer = new byte[readSize];
            MemoryStream ms = new MemoryStream();

            int count = inputStream.Read(buffer, 0, readSize);

            while (count > 0)
            {
                ms.Write(buffer, 0, count);
                count = inputStream.Read(buffer, 0, readSize);
            }

            ms.Position = 0;
            inputStream.Position = 0;

            return ms;
        }

        public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
        {
            return SendXmlRpcCommand(url, methodName, args);
        }

        public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
        {
            XmlRpcRequest client = new XmlRpcRequest(methodName, args);
            return client.Send(url, 6000);
        }

        /// <summary>
        /// Returns an error message that the user could not be found in the database
        /// </summary>
        /// <returns>XML string consisting of a error element containing individual error(s)</returns>
        public static XmlRpcResponse CreateUnknownUserErrorResponse()
        {
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData = new Hashtable();
            responseData["error_type"] = "unknown_user";
            responseData["error_desc"] = "The user requested is not in the database";

            response.Value = responseData;
            return response;
        }

        /// <summary>
        /// Converts a byte array in big endian order into an ulong.
        /// </summary>
        /// <param name="bytes">
        /// The array of bytes
        /// </param>
        /// <returns>
        /// The extracted ulong
        /// </returns>
        public static ulong BytesToUInt64Big(byte[] bytes)
        {
            if (bytes.Length < 8) return 0;
            return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
                ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
        }

        // used for RemoteParcelRequest (for "About Landmark")
        public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
        {
            byte[] bytes =
            {
                (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
                (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
                (byte)x, (byte)(x >> 8), 0, 0,
                (byte)y, (byte)(y >> 8), 0, 0 };
            return new UUID(bytes, 0);
        }

        public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
        {
            byte[] bytes =
            {
                (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
                (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
                (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
                (byte)y, (byte)(y >> 8), 0, 0 };
            return new UUID(bytes, 0);
        }

        public static bool ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
        {
            byte[] bytes = parcelID.GetBytes();
            regionHandle = Utils.BytesToUInt64(bytes);
            x = Utils.BytesToUInt(bytes, 8) & 0xffff;
            y = Utils.BytesToUInt(bytes, 12) & 0xffff;
            // validation may fail, just reducing the odds of using a real UUID as encoded parcel
            return  ( bytes[0] == 0 && bytes[4] == 0 && // handler x,y multiples of 256
                         bytes[9] < 64 && bytes[13] < 64 && // positions < 16km
                         bytes[14] == 0 && bytes[15] == 0);
        }

        public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
        {
            byte[] bytes = parcelID.GetBytes();
            regionHandle = Utils.BytesToUInt64(bytes);
            x = Utils.BytesToUInt(bytes, 8) & 0xffff;
            z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
            y = Utils.BytesToUInt(bytes, 12) & 0xffff;
        }

        public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
        {
            ulong regionHandle;
            uint rx, ry;

            ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
            Utils.LongToUInts(regionHandle, out rx, out ry);

            x += rx;
            y += ry;
        }

        /// <summary>
        /// Get operating system information if available.  Returns only the first 45 characters of information
        /// </summary>
        /// <returns>
        /// Operating system information.  Returns an empty string if none was available.
        /// </returns>
        public static string GetOperatingSystemInformation()
        {
            string os = String.Empty;

//            if (Environment.OSVersion.Platform != PlatformID.Unix)
//            {
//                os = Environment.OSVersion.ToString();
//            }
//            else
//            {
//                os = ReadEtcIssue();
//            }
//
//            if (os.Length > 45)
//            {
//                os = os.Substring(0, 45);
//            }

            return os;
        }

        public static string GetRuntimeInformation()
        {
            string ru = String.Empty;

            if (Environment.OSVersion.Platform == PlatformID.Unix)
                ru = "Unix/Mono";
            else
                if (Environment.OSVersion.Platform == PlatformID.MacOSX)
                    ru = "OSX/Mono";
                else
                {
                    if (IsPlatformMono)
                        ru = "Win/Mono";
                    else
                        ru = "Win/.NET";
                }

            return ru;
        }

        /// <summary>
        /// Is the given string a UUID?
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool isUUID(string s)
        {
            return UUIDPattern.IsMatch(s);
        }

        public static string GetDisplayConnectionString(string connectionString)
        {
            int passPosition = 0;
            int passEndPosition = 0;
            string displayConnectionString = null;

            // hide the password in the connection string
            passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
            if (passPosition == -1)
                return connectionString;
            passPosition = connectionString.IndexOf("=", passPosition);
            if (passPosition < connectionString.Length)
                passPosition += 1;
            passEndPosition = connectionString.IndexOf(";", passPosition);

            displayConnectionString = connectionString.Substring(0, passPosition);
            displayConnectionString += "***";
            displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);

            return displayConnectionString;
        }

        public static string Base64ToString(string str)
        {
            Decoder utf8Decode = Encoding.UTF8.GetDecoder();

            byte[] todecode_byte = Convert.FromBase64String(str);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }

        public static void BinaryToASCII(char[] chars)
        {
            for (int i = 0; i < chars.Length; i++)
            {
                char ch = chars[i];
                if (ch < 32 || ch > 127)
                    chars[i] = '.';
            }
        }

        public static string BinaryToASCII(string src)
        {
            char[] chars = src.ToCharArray();
            BinaryToASCII(chars);
            return new String(chars);
        }

        /// <summary>
        /// Reads a known number of bytes from a stream.
        /// Throws EndOfStreamException if the stream doesn't contain enough data.
        /// </summary>
        /// <param name="stream">The stream to read data from</param>
        /// <param name="data">The array to write bytes into. The array
        /// will be completely filled from the stream, so an appropriate
        /// size must be given.</param>
        public static void ReadStream(Stream stream, byte[] data)
        {
            int offset = 0;
            int remaining = data.Length;

            while (remaining > 0)
            {
                int read = stream.Read(data, offset, remaining);
                if (read <= 0)
                    throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
                remaining -= read;
                offset += read;
            }
        }

        public static Guid GetHashGuid(string data, string salt)
        {
            byte[] hash = ComputeMD5Hash(data + salt, Encoding.Default);

            //string s = BitConverter.ToString(hash);

            Guid guid = new Guid(hash);

            return guid;
        }

        public static byte ConvertMaturityToAccessLevel(uint maturity)
        {
            byte retVal = 0;
            switch (maturity)
            {
                case 0: //PG
                    retVal = 13;
                    break;
                case 1: //Mature
                    retVal = 21;
                    break;
                case 2: // Adult
                    retVal = 42;
                    break;
            }

            return retVal;

        }

        public static uint ConvertAccessLevelToMaturity(byte maturity)
        {
            if (maturity <= 13)
                return 0;
            else if (maturity <= 21)
                return 1;
            else
                return 2;
        }

        /// <summary>
        /// Produces an OSDMap from its string representation on a stream
        /// </summary>
        /// <param name="data">The stream</param>
        /// <param name="length">The size of the data on the stream</param>
        /// <returns>The OSDMap or an exception</returns>
        public static OSDMap GetOSDMap(Stream stream, int length)
        {
            byte[] data = new byte[length];
            stream.Read(data, 0, length);
            string strdata = Util.UTF8.GetString(data);
            OSDMap args = null;
            OSD buffer;
            buffer = OSDParser.DeserializeJson(strdata);
            if (buffer.Type == OSDType.Map)
            {
                args = (OSDMap)buffer;
                return args;
            }
            return null;
        }

        public static OSDMap GetOSDMap(string data)
        {
            OSDMap args = null;
            try
            {
                OSD buffer;
                // We should pay attention to the content-type, but let's assume we know it's Json
                buffer = OSDParser.DeserializeJson(data);
                if (buffer.Type == OSDType.Map)
                {
                    args = (OSDMap)buffer;
                    return args;
                }
                else
                {
                    // uh?
                    m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
                    return null;
                }
            }
            catch (Exception ex)
            {
                m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
                return null;
            }
        }

        public static string[] Glob(string path)
        {
            string vol=String.Empty;

            if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
            {
                string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);

                if (vcomps.Length > 1)
                {
                    path = vcomps[1];
                    vol = vcomps[0];
                }
            }

            string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);

            // Glob

            path = vol;
            if (vol != String.Empty)
                path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
            else
                path = new String(new char[] {Path.DirectorySeparatorChar});

            List<string> paths = new List<string>();
            List<string> found = new List<string>();
            paths.Add(path);

            int compIndex = -1;
            foreach (string c in comps)
            {
                compIndex++;

                List<string> addpaths = new List<string>();
                foreach (string p in paths)
                {
                    string[] dirs = Directory.GetDirectories(p, c);

                    if (dirs.Length != 0)
                    {
                        foreach (string dir in dirs)
                            addpaths.Add(Path.Combine(path, dir));
                    }

                    // Only add files if that is the last path component
                    if (compIndex == comps.Length - 1)
                    {
                        string[] files = Directory.GetFiles(p, c);
                        foreach (string f in files)
                            found.Add(f);
                    }
                }
                paths = addpaths;
            }

            return found.ToArray();
        }

        public static string ServerURI(string uri)
        {
            if (uri == string.Empty)
                return string.Empty;

            // Get rid of eventual slashes at the end
            uri = uri.TrimEnd('/');

            IPAddress ipaddr1 = null;
            string port1 = "";
            try
            {
                ipaddr1 = Util.GetHostFromURL(uri);
            }
            catch { }

            try
            {
                port1 = uri.Split(new char[] { ':' })[2];
            }
            catch { }

            // We tried our best to convert the domain names to IP addresses
            return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to 256 bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <param name="args">
        /// Arguments to substitute into the string via the {} mechanism.
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes256(string str, params object[] args)
        {
            return StringToBytes256(string.Format(str, args));
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to 256 bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes256(string str)
        {
            if (String.IsNullOrEmpty(str))
                return Utils.EmptyBytes;

            if (!str.EndsWith("\0"))
                str += "\0";

            // Because this is UTF-8 encoding and not ASCII, it's possible we
            // might have gotten an oversized array even after the string trim
            byte[] data = UTF8.GetBytes(str);

            if (data.Length > 256)
            {
                int cut = 255;
                if((data[cut] & 0x80 ) != 0 )
                    {
                    while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
                        cut--;
                    }
                Array.Resize<byte>(ref data, cut + 1);
                data[cut] = 0;
            }

            return data;
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to 1024 bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <param name="args">
        /// Arguments to substitute into the string via the {} mechanism.
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes1024(string str, params object[] args)
        {
            return StringToBytes1024(string.Format(str, args));
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to 1024 bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes1024(string str)
        {
            if (String.IsNullOrEmpty(str))
                return Utils.EmptyBytes;

            if (!str.EndsWith("\0"))
                 str += "\0";

            // Because this is UTF-8 encoding and not ASCII, it's possible we
            // might have gotten an oversized array even after the string trim
            byte[] data = UTF8.GetBytes(str);

            if (data.Length > 1024)
            {
                int cut = 1023;
                if((data[cut] & 0x80 ) != 0 )
                    {
                    while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
                        cut--;
                    }
                Array.Resize<byte>(ref data, cut + 1);
                data[cut] = 0;
            }

            return data;
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to MaxLength bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <param name="args">
        /// Arguments to substitute into the string via the {} mechanism.
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes(string str, int MaxLength, params object[] args)
        {
            return StringToBytes1024(string.Format(str, args), MaxLength);
        }

        /// <summary>
        /// Convert a string to a byte format suitable for transport in an LLUDP packet.  The output is truncated to MaxLength bytes if necessary.
        /// </summary>
        /// <param name="str">
        /// If null or empty, then an bytes[0] is returned.
        /// Using "\0" will return a conversion of the null character to a byte.  This is not the same as bytes[0]
        /// </param>
        /// <returns></returns>
        public static byte[] StringToBytes(string str, int MaxLength)
        {
            if (String.IsNullOrEmpty(str))
                return Utils.EmptyBytes;

            if (!str.EndsWith("\0"))
                 str += "\0";

            // Because this is UTF-8 encoding and not ASCII, it's possible we
            // might have gotten an oversized array even after the string trim
            byte[] data = UTF8.GetBytes(str);

            if (data.Length > MaxLength)
            {
                int cut = MaxLength -1 ;
                if((data[cut] & 0x80 ) != 0 )
                    {
                    while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
                        cut--;
                    }
                Array.Resize<byte>(ref data, cut + 1);
                data[cut] = 0;
            }

            return data;
        }
        /// <summary>
        /// Pretty format the hashtable contents to a single line.
        /// </summary>
        /// <remarks>
        /// Used for debugging output.
        /// </remarks>
        /// <param name='ht'></param>
        public static string PrettyFormatToSingleLine(Hashtable ht)
        {
            StringBuilder sb = new StringBuilder();

            int i = 0;

            foreach (string key in ht.Keys)
            {
                sb.AppendFormat("{0}:{1}", key, ht[key]);

                if (++i < ht.Count)
                    sb.AppendFormat(", ");
            }

            return sb.ToString();
        }

        /// <summary>
        /// Used to trigger an early library load on Windows systems.
        /// </summary>
        /// <remarks>
        /// Required to get 32-bit and 64-bit processes to automatically use the
        /// appropriate native library.
        /// </remarks>
        /// <param name="dllToLoad"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string dllToLoad);

        /// <summary>
        /// Determine whether the current process is 64 bit
        /// </summary>
        /// <returns>true if so, false if not</returns>
        public static bool Is64BitProcess()
        {
            return IntPtr.Size == 8;
        }

        #region FireAndForget Threading Pattern

        /// <summary>
        /// Created to work around a limitation in Mono with nested delegates
        /// </summary>
        private sealed class FireAndForgetWrapper
        {
            private static volatile FireAndForgetWrapper instance;
            private static object syncRoot = new Object();

            public static FireAndForgetWrapper Instance {
                get {

                    if (instance == null)
                    {
                        lock (syncRoot)
                        {
                            if (instance == null)
                            {
                                instance = new FireAndForgetWrapper();
                            }
                        }
                    }

                    return instance;
                }
            }

            public void FireAndForget(System.Threading.WaitCallback callback)
            {
                callback.BeginInvoke(null, EndFireAndForget, callback);
            }

            public void FireAndForget(System.Threading.WaitCallback callback, object obj)
            {
                callback.BeginInvoke(obj, EndFireAndForget, callback);
            }

            private static void EndFireAndForget(IAsyncResult ar)
            {
                System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;

                try { callback.EndInvoke(ar); }
                catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }

                ar.AsyncWaitHandle.Close();
            }
        }

        public static void InitThreadPool(int minThreads, int maxThreads)
        {
            if (maxThreads < 2)
                throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");

            if (minThreads > maxThreads || minThreads < 2)
                throw new ArgumentOutOfRangeException("minThreads", "minThreads must be greater than 2 and less than or equal to maxThreads");

            if (m_ThreadPool != null)
            {
                m_log.Warn("SmartThreadPool is already initialized.  Ignoring request.");
                return;
            }

            STPStartInfo startInfo = new STPStartInfo();
            startInfo.ThreadPoolName = "Util";
            startInfo.IdleTimeout = 20000;
            startInfo.MaxWorkerThreads = maxThreads;
            startInfo.MinWorkerThreads = minThreads;

            m_ThreadPool = new SmartThreadPool(startInfo);
            m_threadPoolWatchdog = new Timer(ThreadPoolWatchdog, null, 0, 1000);
        }

        public static int FireAndForgetCount()
        {
            const int MAX_SYSTEM_THREADS = 200;

            switch (FireAndForgetMethod)
            {
                case FireAndForgetMethod.UnsafeQueueUserWorkItem:
                case FireAndForgetMethod.QueueUserWorkItem:
                case FireAndForgetMethod.BeginInvoke:
                    int workerThreads, iocpThreads;
                    ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
                    return workerThreads;
                case FireAndForgetMethod.SmartThreadPool:
                    return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
                case FireAndForgetMethod.Thread:
                    return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
                default:
                    throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Additional information about threads in the main thread pool. Used to time how long the
        /// thread has been running, and abort it if it has timed-out.
        /// </summary>
        private class ThreadInfo
        {
            public long ThreadFuncNum { get; set; }
            public string StackTrace { get; set; }
            private string context;
            public bool LogThread { get; set; }

            public IWorkItemResult WorkItem { get; set; }
            public Thread Thread { get; set; }
            public bool Running { get; set; }
            public bool Aborted { get; set; }
            private int started;

            public ThreadInfo(long threadFuncNum, string context)
            {
                ThreadFuncNum = threadFuncNum;
                this.context = context;
                LogThread = false;
                Thread = null;
                Running = false;
                Aborted = false;
            }

            public void Started()
            {
                Thread = Thread.CurrentThread;
                started = EnvironmentTickCount();
                Running = true;
            }

            public void Ended()
            {
                Running = false;
            }

            public int Elapsed()
            {
                return EnvironmentTickCountSubtract(started);
            }

            public void Abort()
            {
                Aborted = true;
                WorkItem.Cancel(true);
            }

            /// <summary>
            /// Returns the thread's stack trace.
            /// </summary>
            /// <remarks>
            /// May return one of two stack traces. First, tries to get the thread's active stack
            /// trace. But this can fail, so as a fallback this method will return the stack
            /// trace that was active when the task was queued.
            /// </remarks>
            public string GetStackTrace()
            {
                string ret = (context == null) ? "" : ("(" + context + ") ");

                StackTrace activeStackTrace = Util.GetStackTrace(Thread);
                if (activeStackTrace != null)
                    ret += activeStackTrace.ToString();
                else if (StackTrace != null)
                    ret += "(Stack trace when queued) " + StackTrace;
                // else, no stack trace available

                return ret;
            }
        }

        private static long nextThreadFuncNum = 0;
        private static long numQueuedThreadFuncs = 0;
        private static long numRunningThreadFuncs = 0;
        private static long numTotalThreadFuncsCalled = 0;
        private static Int32 threadFuncOverloadMode = 0;

        public static long TotalQueuedFireAndForgetCalls { get { return numQueuedThreadFuncs; } }
        public static long TotalRunningFireAndForgetCalls { get { return numRunningThreadFuncs; } }

        // Maps (ThreadFunc number -> Thread)
        private static ConcurrentDictionary<long, ThreadInfo> activeThreads = new ConcurrentDictionary<long, ThreadInfo>();

        private static readonly int THREAD_TIMEOUT = 10 * 60 * 1000;    // 10 minutes

        /// <summary>
        /// Finds threads in the main thread pool that have timed-out, and aborts them.
        /// </summary>
        private static void ThreadPoolWatchdog(object state)
        {
            foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads)
            {
                ThreadInfo t = entry.Value;
                if (t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
                {
                    m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
                    t.Abort();

                    ThreadInfo dummy;
                    activeThreads.TryRemove(entry.Key, out dummy);

                    // It's possible that the thread won't abort. To make sure the thread pool isn't
                    // depleted, increase the pool size.
//                    m_ThreadPool.MaxThreads++;
                }
            }
        }

        public static long TotalFireAndForgetCallsMade { get { return numTotalThreadFuncsCalled; } }

        public static Dictionary<string, int> GetFireAndForgetCallsMade()
        {
            return new Dictionary<string, int>(m_fireAndForgetCallsMade);
        }

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

        public static Dictionary<string, int> GetFireAndForgetCallsInProgress()
        {
            return new Dictionary<string, int>(m_fireAndForgetCallsInProgress);
        }

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

        public static void FireAndForget(System.Threading.WaitCallback callback)
        {
            FireAndForget(callback, null, null);
        }

        public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
        {
            FireAndForget(callback, obj, null);
        }

        public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context)
        {
            Interlocked.Increment(ref numTotalThreadFuncsCalled);

            if (context != null)
            {
                if (!m_fireAndForgetCallsMade.ContainsKey(context))
                    m_fireAndForgetCallsMade[context] = 1;
                else
                    m_fireAndForgetCallsMade[context]++;

                if (!m_fireAndForgetCallsInProgress.ContainsKey(context))
                    m_fireAndForgetCallsInProgress[context] = 1;
                else
                    m_fireAndForgetCallsInProgress[context]++;
            }

            WaitCallback realCallback;

            bool loggingEnabled = LogThreadPool > 0;

            long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
            ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context);

            if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
            {
                // If we're running regression tests, then we want any exceptions to rise up to the test code.
                realCallback =
                    o =>
                    {
                        Culture.SetCurrentCulture();
                        callback(o);

                        if (context != null)
                            m_fireAndForgetCallsInProgress[context]--;
                    };
            }
            else
            {
                // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
                // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
                // for decimals places but is read by a culture that treats commas as number seperators.
                realCallback = o =>
                {
                    long numQueued1 = Interlocked.Decrement(ref numQueuedThreadFuncs);
                    long numRunning1 = Interlocked.Increment(ref numRunningThreadFuncs);
                    threadInfo.Started();
                    activeThreads[threadFuncNum] = threadInfo;

                    try
                    {
                        if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
                            m_log.DebugFormat("Run threadfunc {0} (Queued {1}, Running {2})", threadFuncNum, numQueued1, numRunning1);

                        Culture.SetCurrentCulture();

                        callback(o);
                    }
                    catch (ThreadAbortException e)
                    {
                    }
                    catch (Exception e)
                    {
                        m_log.Error(string.Format("[UTIL]: Util STP threadfunc {0} terminated with error ", threadFuncNum), e);
                    }
                    finally
                    {
                        Interlocked.Decrement(ref numRunningThreadFuncs);
                        threadInfo.Ended();
                        ThreadInfo dummy;
                        activeThreads.TryRemove(threadFuncNum, out dummy);
                        if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
                            m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));

                        if (context != null)
                            m_fireAndForgetCallsInProgress[context]--;
                    }
                };
            }

            long numQueued = Interlocked.Increment(ref numQueuedThreadFuncs);
            try
            {
/*
                long numRunning = numRunningThreadFuncs;

                if (m_ThreadPool != null && LogOverloads)
                {
                    if ((threadFuncOverloadMode == 0) && (numRunning >= m_ThreadPool.MaxThreads))
                    {
                        if (Interlocked.CompareExchange(ref threadFuncOverloadMode, 1, 0) == 0)
                            m_log.DebugFormat("Threadfunc: enable overload mode (Queued {0}, Running {1})", numQueued, numRunning);
                    }
                    else if ((threadFuncOverloadMode == 1) && (numRunning <= (m_ThreadPool.MaxThreads * 2) / 3))
                    {
                        if (Interlocked.CompareExchange(ref threadFuncOverloadMode, 0, 1) == 1)
                            m_log.DebugFormat("Threadfunc: disable overload mode (Queued {0}, Running {1})", numQueued, numRunning);
                    }
                }

                if (loggingEnabled || (threadFuncOverloadMode == 1))
                {
                    string full, partial;
                    GetFireAndForgetStackTrace(out full, out partial);
                    threadInfo.StackTrace = full;
                    threadInfo.LogThread = ShouldLogThread(partial);

                    if (threadInfo.LogThread)
                    {
                        m_log.DebugFormat("Queue threadfunc {0} (Queued {1}, Running {2}) {3}{4}",
                            threadFuncNum, numQueued, numRunningThreadFuncs,
                            (context == null) ? "" : ("(" + context + ") "),
                            (LogThreadPool >= 2) ? full : partial);
                    }
                }
                else
*/
                {
                    // Since we didn't log "Queue threadfunc", don't log "Run threadfunc" or "End threadfunc" either.
                    // Those log lines aren't useful when we don't know which function is running in the thread.
                    threadInfo.LogThread = false;
                }

                switch (FireAndForgetMethod)
                {
                    case FireAndForgetMethod.RegressionTest:
                    case FireAndForgetMethod.None:
                        realCallback.Invoke(obj);
                        break;
                    case FireAndForgetMethod.UnsafeQueueUserWorkItem:
                        ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
                        break;
                    case FireAndForgetMethod.QueueUserWorkItem:
                        ThreadPool.QueueUserWorkItem(realCallback, obj);
                        break;
                    case FireAndForgetMethod.BeginInvoke:
                        FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
                        wrapper.FireAndForget(realCallback, obj);
                        break;
                    case FireAndForgetMethod.SmartThreadPool:
                        if (m_ThreadPool == null)
                            InitThreadPool(2, 15);
                        threadInfo.WorkItem = m_ThreadPool.QueueWorkItem((cb, o) => cb(o), realCallback, obj);
                        break;
                    case FireAndForgetMethod.Thread:
                        Thread thread = new Thread(delegate(object o) { realCallback(o); });
                        thread.Start(obj);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            catch (Exception)
            {
                Interlocked.Decrement(ref numQueuedThreadFuncs);
                ThreadInfo dummy;
                activeThreads.TryRemove(threadFuncNum, out dummy);
                throw;
            }
        }

        /// <summary>
        /// Returns whether the thread should be logged. Some very common threads aren't logged,
        /// to avoid filling up the log.
        /// </summary>
        /// <param name="stackTrace">A partial stack trace of where the thread was queued</param>
        /// <returns>Whether to log this thread</returns>
        private static bool ShouldLogThread(string stackTrace)
        {
            if (LogThreadPool < 3)
            {
                if (stackTrace.Contains("BeginFireQueueEmpty"))
                    return false;
            }

            return true;
        }

        /// <summary>
        /// Returns a stack trace for a thread added using FireAndForget().
        /// </summary>
        /// <param name="full">Will contain the full stack trace</param>
        /// <param name="partial">Will contain only the first frame of the stack trace</param>
        private static void GetFireAndForgetStackTrace(out string full, out string partial)
        {
            string src = Environment.StackTrace;
            string[] lines = src.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            StringBuilder dest = new StringBuilder(src.Length);

            bool started = false;
            bool first = true;
            partial = "";

            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];

                if (!started)
                {
                    // Skip the initial stack frames, because they're of no interest for debugging
                    if (line.Contains("StackTrace") || line.Contains("FireAndForget"))
                        continue;
                    started = true;
                }

                if (first)
                {
                    line = line.TrimStart();
                    first = false;
                    partial = line;
                }

                bool last = (i == lines.Length - 1);
                if (last)
                    dest.Append(line);
                else
                    dest.AppendLine(line);
            }

            full = dest.ToString();
        }

#pragma warning disable 0618
        /// <summary>
        /// Return the stack trace of a different thread.
        /// </summary>
        /// <remarks>
        /// This is complicated because the thread needs to be paused in order to get its stack
        /// trace. And pausing another thread can cause a deadlock. This method attempts to
        /// avoid deadlock by using a short timeout (200ms), after which it gives up and
        /// returns 'null' instead of the stack trace.
        ///
        /// Take from: http://stackoverflow.com/a/14935378
        ///
        /// WARNING: this doesn't work in Mono. See https://bugzilla.novell.com/show_bug.cgi?id=571691
        ///
        /// </remarks>
        /// <returns>The stack trace, or null if failed to get it</returns>
        private static StackTrace GetStackTrace(Thread targetThread)
        {
            if (IsPlatformMono)
            {
                // This doesn't work in Mono
                return null;
            }

            ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim();
            ManualResetEventSlim exitedSafely = new ManualResetEventSlim();

            try
            {
                new Thread(delegate()
                {
                    fallbackThreadReady.Set();
                    while (!exitedSafely.Wait(200))
                    {
                        try
                        {
                            targetThread.Resume();
                        }
                        catch (Exception)
                        {
                            // Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely.
                        }
                    }
                }).Start();

                fallbackThreadReady.Wait();
                // From here, you have about 200ms to get the stack-trace

                targetThread.Suspend();

                StackTrace trace = null;
                try
                {
                    trace = new StackTrace(targetThread, true);
                }
                catch (ThreadStateException)
                {
                    //failed to get stack trace, since the fallback-thread resumed the thread
                    //possible reasons:
                    //1.) This thread was just too slow
                    //2.) A deadlock ocurred
                    //Automatic retry seems too risky here, so just return null.
                }

                try
                {
                    targetThread.Resume();
                }
                catch (ThreadStateException)
                {
                    // Thread is running again already
                }

                return trace;
            }
            finally
            {
                // Signal the fallack-thread to stop
                exitedSafely.Set();
            }
        }
#pragma warning restore 0618

        /// <summary>
        /// Get information about the current state of the smart thread pool.
        /// </summary>
        /// <returns>
        /// null if this isn't the pool being used for non-scriptengine threads.
        /// </returns>
        public static STPInfo GetSmartThreadPoolInfo()
        {
            if (m_ThreadPool == null)
                return null;

            STPInfo stpi = new STPInfo();
            stpi.Name = m_ThreadPool.Name;
            stpi.STPStartInfo = m_ThreadPool.STPStartInfo;
            stpi.IsIdle = m_ThreadPool.IsIdle;
            stpi.IsShuttingDown = m_ThreadPool.IsShuttingdown;
            stpi.MaxThreads = m_ThreadPool.MaxThreads;
            stpi.MinThreads = m_ThreadPool.MinThreads;
            stpi.InUseThreads = m_ThreadPool.InUseThreads;
            stpi.ActiveThreads = m_ThreadPool.ActiveThreads;
            stpi.WaitingCallbacks = m_ThreadPool.WaitingCallbacks;
            stpi.MaxConcurrentWorkItems = m_ThreadPool.Concurrency;

            return stpi;
        }

        public static void StopThreadPool()
        {
            if (m_ThreadPool == null)
                return;
            SmartThreadPool pool = m_ThreadPool;
            m_ThreadPool = null;

            try { pool.Shutdown(); } catch {}          
        }

        #endregion FireAndForget Threading Pattern

        /// <summary>
        /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
        /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
        /// for the callers.
        /// This trims it to a 12 day interval so don't let your frame time get too long.
        /// </summary>
        /// <returns></returns>
        public static Int32 EnvironmentTickCount()
        {
            return Environment.TickCount & EnvironmentTickCountMask;
        }
        const Int32 EnvironmentTickCountMask = 0x3fffffff;

        /// <summary>
        /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
        /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
        /// 'EnvironmentTickCount()') and accounts for any wrapping.
        /// </summary>
        /// <param name="newValue"></param>
        /// <param name="prevValue"></param>
        /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
        public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
        {
            Int32 diff = newValue - prevValue;
            return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
        }

        /// <summary>
        /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
        /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
        /// 'EnvironmentTickCount()') and accounts for any wrapping.
        /// </summary>
        /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
        public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
        {
            return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
        }

        // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
        // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
        // A positive return value indicates A occured later than B
        public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
        {
            // A, B and TC are all between 0 and 0x3fffffff
            int tc = EnvironmentTickCount();

            if (tc - tcA >= 0)
                tcA += EnvironmentTickCountMask + 1;

            if (tc - tcB >= 0)
                tcB += EnvironmentTickCountMask + 1;

            return tcA - tcB;
        }

        // returns a timestamp in ms as double
        // using the time resolution avaiable to StopWatch
        public static double GetTimeStampMS()
        {
            return (double)Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
        }

        /// <summary>
        /// Formats a duration (given in milliseconds).
        /// </summary>
        public static string FormatDuration(int ms)
        {
            TimeSpan span = new TimeSpan(ms * TimeSpan.TicksPerMillisecond);

            string str = "";
            string suffix = null;

            int hours = (int)span.TotalHours;
            if (hours > 0)
            {
                str += hours.ToString(str.Length == 0 ? "0" : "00");
                suffix = "hours";
            }

            if ((hours > 0) || (span.Minutes > 0))
            {
                if (str.Length > 0)
                    str += ":";
                str += span.Minutes.ToString(str.Length == 0 ? "0" : "00");
                if (suffix == null)
                    suffix = "min";
            }

            if ((hours > 0) || (span.Minutes > 0) || (span.Seconds > 0))
            {
                if (str.Length > 0)
                    str += ":";
                str += span.Seconds.ToString(str.Length == 0 ? "0" : "00");
                if (suffix == null)
                    suffix = "sec";
            }

            if (suffix == null)
                suffix = "ms";

            if (span.TotalMinutes < 1)
            {
                int ms1 = span.Milliseconds;
                if (str.Length > 0)
                {
                    ms1 /= 100;
                    str += ".";
                }
                str += ms1.ToString("0");
            }

            str += " " + suffix;

            return str;
        }

        /// <summary>
        /// Prints the call stack at any given point. Useful for debugging.
        /// </summary>
        public static void PrintCallStack()
        {
            PrintCallStack(m_log.DebugFormat);
        }

        public delegate void DebugPrinter(string msg, params Object[] parm);
        public static void PrintCallStack(DebugPrinter printer)
        {
            StackTrace stackTrace = new StackTrace(true);           // get call stack
            StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

            // write call stack method names
            foreach (StackFrame stackFrame in stackFrames)
            {
                MethodBase mb = stackFrame.GetMethod();
                printer("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
            }
        }

        /// <summary>
        /// Gets the client IP address
        /// </summary>
        /// <param name="xff"></param>
        /// <returns></returns>
        public static IPEndPoint GetClientIPFromXFF(string xff)
        {
            if (xff == string.Empty)
                return null;

            string[] parts = xff.Split(new char[] { ',' });
            if (parts.Length > 0)
            {
                try
                {
                    return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
                }
            }

            return null;
        }

        public static string GetCallerIP(Hashtable req)
        {
            if (req.ContainsKey("headers"))
            {
                try
                {
                    Hashtable headers = (Hashtable)req["headers"];
                    if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
                        return headers["remote_addr"].ToString();
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
                }
            }
            return string.Empty;
        }

        #region Xml Serialization Utilities
        public static bool ReadBoolean(XmlReader reader)
        {
            // AuroraSim uses "int" for some fields that are boolean in OpenSim, e.g. "PassCollisions". Don't fail because of this.
            reader.ReadStartElement();
            string val = reader.ReadContentAsString().ToLower();
            bool result = val.Equals("true") || val.Equals("1");
            reader.ReadEndElement();

            return result;
        }

        public static UUID ReadUUID(XmlReader reader, string name)
        {
            UUID id;
            string idStr;

            reader.ReadStartElement(name);

            if (reader.Name == "Guid")
                idStr = reader.ReadElementString("Guid");
            else if (reader.Name == "UUID")
                idStr = reader.ReadElementString("UUID");
            else // no leading tag
                idStr = reader.ReadContentAsString();
            UUID.TryParse(idStr, out id);
            reader.ReadEndElement();

            return id;
        }

        public static Vector3 ReadVector(XmlReader reader, string name)
        {
            Vector3 vec;

            reader.ReadStartElement(name);
            vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
            vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
            vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
            reader.ReadEndElement();

            return vec;
        }

        public static Quaternion ReadQuaternion(XmlReader reader, string name)
        {
            Quaternion quat = new Quaternion();

            reader.ReadStartElement(name);
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                switch (reader.Name.ToLower())
                {
                    case "x":
                        quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
                        break;
                    case "y":
                        quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
                        break;
                    case "z":
                        quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
                        break;
                    case "w":
                        quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
                        break;
                }
            }

            reader.ReadEndElement();

            return quat;
        }

        public static T ReadEnum<T>(XmlReader reader, string name)
        {
            string value = reader.ReadElementContentAsString(name, String.Empty);
            // !!!!! to deal with flags without commas
            if (value.Contains(" ") && !value.Contains(","))
                value = value.Replace(" ", ", ");

            return (T)Enum.Parse(typeof(T), value); ;
        }
        #endregion

        #region Universal User Identifiers

        /// <summary>
        /// Attempts to parse a UUI into its components: UUID, name and URL.
        /// </summary>
        /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
        /// <param name="uuid">the uuid part</param>
        /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
        /// <param name="firstname">the first name part (e.g. Test)</param>
        /// <param name="lastname">the last name part (e.g User)</param>
        /// <param name="secret">the secret part</param>
        public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
        {
            uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "UserUPUUI"; secret = string.Empty;

            string[] parts = value.Split(';');
            if (parts.Length >= 1)
                if (!UUID.TryParse(parts[0], out uuid))
                    return false;

            if (parts.Length >= 2)
                url = parts[1];

            if (parts.Length >= 3)
            {
                string[] name = parts[2].Split();
                if (name.Length == 2)
                {
                    firstname = name[0];
                    lastname = name[1];
                }
            }
            if (parts.Length >= 4)
                secret = parts[3];

            return true;
        }

        /// <summary>
        /// For foreign avatars, extracts their original name and Server URL from their First Name and Last Name.
        /// </summary>
        public static bool ParseForeignAvatarName(string firstname, string lastname,
            out string realFirstName, out string realLastName, out string serverURI)
        {
            realFirstName = realLastName = serverURI = string.Empty;

            if (!lastname.Contains("@"))
                return false;

            if (!firstname.Contains("."))
                return false;

            realFirstName = firstname.Split('.')[0];
            realLastName = firstname.Split('.')[1];
            serverURI = new Uri("http://" + lastname.Replace("@", "")).ToString();

            return true;
        }

        /// <summary>
        /// Produces a universal (HG) system-facing identifier given the information
        /// </summary>
        /// <param name="acircuit"></param>
        /// <returns>uuid[;homeURI[;first last]]</returns>
        public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
        {
            if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
                return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
            else
                return acircuit.AgentID.ToString();
        }

        /// <summary>
        /// Produces a universal (HG) system-facing identifier given the information
        /// </summary>
        /// <param name="id">UUID of the user</param>
        /// <param name="firstName">first name (e.g Test)</param>
        /// <param name="lastName">last name (e.g. User)</param>
        /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
        /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
        public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
        {
            string agentsURI = homeURI;
            if (!agentsURI.EndsWith("/"))
                agentsURI += "/";

            // This is ugly, but there's no other way, given that the name is changed
            // in the agent circuit data for foreigners
            if (lastName.Contains("@"))
            {
                string[] parts = firstName.Split(new char[] { '.' });
                if (parts.Length == 2)
                    return CalcUniversalIdentifier(id, agentsURI, parts[0] + " " + parts[1]);
            }

            return CalcUniversalIdentifier(id, agentsURI, firstName + " " + lastName);
        }

        private static string CalcUniversalIdentifier(UUID id, string agentsURI, string name)
        {
            return id.ToString() + ";" + agentsURI + ";" + name;
        }

        /// <summary>
        /// Produces a universal (HG) user-facing name given the information
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="homeURI"></param>
        /// <returns>string of the form first.last @foo.com or first last</returns>
        public static string UniversalName(String firstName, String lastName, String homeURI)
        {
            Uri uri = null;
            try
            {
                uri = new Uri(homeURI);
            }
            catch (UriFormatException)
            {
                return firstName + " " + lastName;
            }
            return firstName + "." + lastName + " " + "@" + uri.Authority;
        }
        #endregion

        /// <summary>
        /// Escapes the special characters used in "LIKE".
        /// </summary>
        /// <remarks>
        /// For example: EscapeForLike("foo_bar%baz") = "foo\_bar\%baz"
        /// </remarks>
        public static string EscapeForLike(string str)
        {
            return str.Replace("_", "\\_").Replace("%", "\\%");
        }

        /// <summary>
        /// Returns the name of the user's viewer.
        /// </summary>
        /// <remarks>
        /// This method handles two ways that viewers specify their name:
        /// 1. Viewer = "Firestorm-Release 4.4.2.34167", Channel = "(don't care)" -> "Firestorm-Release 4.4.2.34167"
        /// 2. Viewer = "4.5.1.38838", Channel = "Firestorm-Beta" -> "Firestorm-Beta 4.5.1.38838"
        /// </remarks>
        public static string GetViewerName(AgentCircuitData agent)
        {
            string name = agent.Viewer;
            if (name == null)
                name = "";
            else
                name = name.Trim();

            // Check if 'Viewer' is just a version number. If it's *not*, then we
            // assume that it contains the real viewer name, and we return it.
            foreach (char c in name)
            {
                if (Char.IsLetter(c))
                    return name;
            }

            // The 'Viewer' string contains just a version number. If there's anything in
            // 'Channel' then assume that it's the viewer name.
            if ((agent.Channel != null) && (agent.Channel.Length > 0))
                name = agent.Channel.Trim() + " " + name;

            return name;
        }

        public static void LogFailedXML(string message, string xml)
        {
            int length = xml.Length;
            if (length > 2000)
                xml = xml.Substring(0, 2000) + "...";

            m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml);
        }

    }

/*  don't like this code
    public class DoubleQueue<T> where T:class
    {
        private Queue<T> m_lowQueue = new Queue<T>();
        private Queue<T> m_highQueue = new Queue<T>();

        private object m_syncRoot = new object();
        private Semaphore m_s = new Semaphore(0, 1);

        public DoubleQueue()
        {
        }

        public virtual int Count
        {
            get
            {
                lock (m_syncRoot)
                    return m_highQueue.Count + m_lowQueue.Count;
            }
        }

        public virtual void Enqueue(T data)
        {
            Enqueue(m_lowQueue, data);
        }

        public virtual void EnqueueLow(T data)
        {
            Enqueue(m_lowQueue, data);
        }

        public virtual void EnqueueHigh(T data)
        {
            Enqueue(m_highQueue, data);
        }

        private void Enqueue(Queue<T> q, T data)
        {
            lock (m_syncRoot)
            {
                q.Enqueue(data);
                m_s.WaitOne(0);
                m_s.Release();
            }
        }

        public virtual T Dequeue()
        {
            return Dequeue(Timeout.Infinite);
        }

        public virtual T Dequeue(int tmo)
        {
            return Dequeue(TimeSpan.FromMilliseconds(tmo));
        }

        public virtual T Dequeue(TimeSpan wait)
        {
            T res = null;

            if (!Dequeue(wait, ref res))
                return null;

            return res;
        }

        public bool Dequeue(int timeout, ref T res)
        {
            return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res);
        }

        public bool Dequeue(TimeSpan wait, ref T res)
        {
            if (!m_s.WaitOne(wait))
                return false;

            lock (m_syncRoot)
            {
                if (m_highQueue.Count > 0)
                    res = m_highQueue.Dequeue();
                else if (m_lowQueue.Count > 0)
                    res = m_lowQueue.Dequeue();

                if (m_highQueue.Count == 0 && m_lowQueue.Count == 0)
                    return true;

                try
                {
                    m_s.Release();
                }
                catch
                {
                }

                return true;
            }
        }

        public virtual void Clear()
        {

            lock (m_syncRoot)
            {
                // Make sure sem count is 0
                m_s.WaitOne(0);

                m_lowQueue.Clear();
                m_highQueue.Clear();
            }
        }
    }
*/
    public class BetterRandom
    {
        private const int BufferSize = 1024;  // must be a multiple of 4
        private byte[] RandomBuffer;
        private int BufferOffset;
        private RNGCryptoServiceProvider rng;
        public BetterRandom()
        {
            RandomBuffer = new byte[BufferSize];
            rng = new RNGCryptoServiceProvider();
            BufferOffset = RandomBuffer.Length;
        }
        private void FillBuffer()
        {
            rng.GetBytes(RandomBuffer);
            BufferOffset = 0;
        }
        public int Next()
        {
            if (BufferOffset >= RandomBuffer.Length)
            {
                FillBuffer();
            }
            int val = BitConverter.ToInt32(RandomBuffer, BufferOffset) & 0x7fffffff;
            BufferOffset += sizeof(int);
            return val;
        }
        public int Next(int maxValue)
        {
            return Next() % maxValue;
        }
        public int Next(int minValue, int maxValue)
        {
            if (maxValue < minValue)
            {
                throw new ArgumentOutOfRangeException("maxValue must be greater than or equal to minValue");
            }
            int range = maxValue - minValue;
            return minValue + Next(range);
        }
        public double NextDouble()
        {
            int val = Next();
            return (double)val / int.MaxValue;
        }
        public void GetBytes(byte[] buff)
        {
            rng.GetBytes(buff);
        }
    }
}