arzmq-sys 0.5.2

Low-level bindings to the zeromq library
Documentation
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
#define _NORM_API_BUILD	// force 'dllexport' in "normApi.h"
#include "normApi.h"
#include "normSession.h"

#ifdef WIN32
#ifndef _WIN32_WCE
#include <io.h>  // for _mktemp()
#endif // !_WIN32_WCE
#endif // WIN32

// const defs
extern NORM_API_LINKAGE
const NormInstanceHandle NORM_INSTANCE_INVALID = ((NormInstanceHandle)0);
extern NORM_API_LINKAGE
const NormSessionHandle NORM_SESSION_INVALID = ((NormSessionHandle)0);
extern NORM_API_LINKAGE
const NormNodeHandle NORM_NODE_INVALID = ((NormNodeHandle)0);
extern NORM_API_LINKAGE
const NormNodeId NORM_NODE_NONE = ((NormNodeId)0x00000000);
extern NORM_API_LINKAGE
const NormNodeId NORM_NODE_ANY = ((NormNodeId)0xffffffff);
extern NORM_API_LINKAGE
const NormObjectHandle NORM_OBJECT_INVALID = ((NormObjectHandle)0);
extern NORM_API_LINKAGE
const NormDescriptor NORM_DESCRIPTOR_INVALID = ProtoDispatcher::INVALID_DESCRIPTOR;


/** The "NormInstance" class is a C++ helper class that keeps
 *  state for an instance of the NORM API.  It acts as a
 *  "go between" the API's procedural function calls and
 *  the underlying NORM C++ implementation
 */
class NormInstance : public NormController
{
    public:
        NormInstance();
        virtual ~NormInstance();
        
        void Notify(NormController::Event   event,
                    class NormSessionMgr*   sessionMgr,
                    class NormSession*      session,
                    class NormNode*         node,
                    class NormObject*       object);
        
        bool Startup(bool priorityBoost = false);
        void Shutdown();
        
        void Stop()  // pause NORM protocol engine
        {
            dispatcher.Stop();
            Notify(NormController::EVENT_INVALID, &session_mgr, NULL, NULL, NULL);
        }
        bool Start()
        {
            if (dispatcher.StartThread(priority_boost))
            {
                return true;
            }
            else
            {
                PLOG(PL_FATAL, "NormInstance::Resume() error restarting NORM thread\n");
                return false;
            }
        }
        
        bool WaitForEvent();
        bool GetNextEvent(NormEvent* theEvent);
        bool SetCacheDirectory(const char* cachePath);
        
        void SetAllocationFunctions(NormAllocFunctionHandle allocFunc, 
                                    NormFreeFunctionHandle  freeFunc)
        {
            data_alloc_func = allocFunc;
            session_mgr.SetDataFreeFunction(freeFunc);
        }
        
        void ReleasePreviousEvent();
        
        bool NotifyQueueIsEmpty() const 
            {return notify_queue.IsEmpty();}
        
        void PurgeSessionNotifications(NormSessionHandle sessionHandle);
        void PurgeNodeNotifications(NormNodeHandle nodeHandle);
        void PurgeObjectNotifications(NormObjectHandle objectHandle);
        void PurgeNotifications(NormSessionHandle sessionHandle, NormEventType eventType);
        
        UINT32 CountCompletedObjects(NormSession* theSession);
        
        ProtoDispatcher::Descriptor GetDescriptor() const
        {
#ifdef WIN32
            return notify_event;
#else
            return notify_fd[0];
#endif // if/else WIN32/UNIX            
        }
        
        static NormInstance* GetInstanceFromSession(NormSessionHandle sessionHandle)
        {
            if (NORM_SESSION_INVALID == sessionHandle) return ((NormInstance*)NULL);
            NormSession* session = (NormSession*)sessionHandle;
            NormInstance* theInstance = static_cast<NormInstance*>(session->GetSessionMgr().GetController());
            return theInstance;
        }
        static NormInstance* GetInstanceFromNode(NormNodeHandle nodeHandle)
        {
            if (NORM_NODE_INVALID == nodeHandle) return ((NormInstance*)NULL);
            NormSession& session = ((NormNode*)nodeHandle)->GetSession();
            return static_cast<NormInstance*>(session.GetSessionMgr().GetController());   
        }
        static NormInstance* GetInstanceFromObject(NormObjectHandle objectHandle)
        {
            if (NORM_OBJECT_INVALID == objectHandle) return ((NormInstance*)NULL);
            NormSession& session = ((NormObject*)objectHandle)->GetSession();;
            return static_cast<NormInstance*>(session.GetSessionMgr().GetController());   
        }
        
        class Notification : public ProtoList::Item
        {
            public:
                NormEvent   event;
            
            class Queue : public ProtoListTemplate<Notification> {};
        };  // end class NormInstance::Notification
        
        ProtoDispatcher             dispatcher;
        bool                        priority_boost;
        NormSessionMgr              session_mgr;   
        NormAllocFunctionHandle     data_alloc_func;
        
    private:
        void ResetNotificationEvent()
        {
#ifdef WIN32
            if (0 == ResetEvent(notify_event))
                PLOG(PL_ERROR, "NormInstance::ResetNotificationEvent() ResetEvent error: %s\n", GetErrorString());
#else
           char byte[32];
           while (read(notify_fd[0], byte, 32) > 0);  // TBD - error check
#endif // if/else WIN32/UNIX
        }  
         
        Notification::Queue         notify_pool;
        Notification::Queue         notify_queue; 
        Notification*               previous_notification;
        
        const char*                 rx_cache_path;
        
#ifdef WIN32
        HANDLE                      notify_event;
#else
        int                         notify_fd[2];  // TBD - use eventfd on Linux for this, may EVT_USER on MacOS
#endif // if/else WIN32/UNIX
};  // end class NormInstance


////////////////////////////////////////////////////
// NormInstance implementation
NormInstance::NormInstance()
 : priority_boost(false),
   session_mgr(static_cast<ProtoTimerMgr&>(dispatcher), 
               static_cast<ProtoSocket::Notifier&>(dispatcher),
               static_cast<ProtoChannel::Notifier*>(&dispatcher)),
   data_alloc_func(NULL), previous_notification(NULL), rx_cache_path(NULL)
{
#ifdef WIN32
    notify_event = NULL;
#else
    notify_fd[0] = notify_fd[1] = -1;
#endif // if/else WIN32/UNIX
    dispatcher.SetUserData(&session_mgr);  // for debugging
    session_mgr.SetController(static_cast<NormController*>(this));
}

NormInstance::~NormInstance()
{
    Shutdown();
}

bool NormInstance::SetCacheDirectory(const char* cachePath)
{
    // (TBD) verify that we can _write_ to this directory!
    bool result = false;
    if (dispatcher.SuspendThread())
    {
        size_t length = strlen(cachePath);
        if (PROTO_PATH_DELIMITER != cachePath[length-1]) 
            length += 2;
        else
            length += 1;
        length = (length < PATH_MAX) ? length : PATH_MAX;
        char* pathStorage = new char[length];
        if (pathStorage)
        {
            strncpy(pathStorage, cachePath, length);
            pathStorage[length - 2] = PROTO_PATH_DELIMITER;
            pathStorage[length - 1] = '\0';
            if (rx_cache_path) delete[] (char*)rx_cache_path;
            rx_cache_path = pathStorage;
            result = true;
        }
        else
        {
            PLOG(PL_ERROR, "NormInstance::SetCacheDirectory() new pathStorage error: %s\n",
                    GetErrorString());
        }
        dispatcher.ResumeThread();
    }
    return result;
}  // end NormInstance::SetCacheDirectory()

void NormInstance::Notify(NormController::Event   event,
                          class NormSessionMgr*   sessionMgr,
                          class NormSession*      session,
                          class NormNode*         node,
                          class NormObject*       object)
{
    switch (event)
    {
        case SEND_OK:
            // Purge any pending NORM_SEND_ERROR notifications for session
            PurgeNotifications(session, NORM_SEND_ERROR);
            return;
        default:
            break;
    }
    
    // (TBD) set a limit on how many pending notifications
    // we allow to queue up (it could be large and probably
    // we could base it on how much memory space the pending
    // notifications are allowed to consume.
    Notification* next = notify_pool.RemoveHead();
    if (NULL == next)
    {
        if (NULL == (next = new Notification))
        {
            PLOG(PL_FATAL, "NormInstance::Notify() new Notification error: %s\n", GetErrorString());
            return;   
        }
    }
    
    switch (event)
    { 
        case RX_OBJECT_NEW:
        {
            // new recv object "Accept()" policy implemented here
            switch (object->GetType())
            {
                case NormObject::STREAM:
                {
                    NormStreamObject* stream = static_cast<NormStreamObject*>(object);
                    // (TBD) implement silent_receiver accept differently
                    NormObjectSize size = stream->GetSize();
                    // We double the stream buffer to prevent unecessary data loss
                    // for our threaded API
                    if (!stream->Accept(size.LSB(), true))
                    {
                        PLOG(PL_FATAL, "NormInstance::Notify() stream accept error\n");
                        notify_pool.Append(*next);
                        return;   
                    }
                    // By setting a non-zero "block pool threshold", this
                    // gives the API a chance to "catch up" on reading
                    // when the receive stream becomes buffer-constrained
                    UINT32 blockPoolCount = stream->GetBlockPoolCount();
                    stream->SetBlockPoolThreshold(blockPoolCount / 2);
                    break;
                }
                case NormObject::FILE:
                {
                    if (NULL != rx_cache_path)
                    {
                        char fileName[PATH_MAX];
                        strncpy(fileName, rx_cache_path, PATH_MAX);
                        size_t catMax = strlen(fileName);
                        if (catMax > PATH_MAX) 
                            catMax = 0;
                        else
                            catMax = PATH_MAX - catMax;
                        strncat(fileName, "normTempXXXXXX", catMax);
                        
#ifdef WIN32
#ifdef _WIN32_WCE
                        bool tempFileOK = false;
                        for (int i = 0; i < 255; i++)
                        {
                            strncpy(fileName, rx_cache_path, PATH_MAX);
                            catMax = strlen(fileName);
                            if (catMax > PATH_MAX) 
                                catMax = 0;
                            else
                                catMax = PATH_MAX - catMax;
                            strncat(fileName, "normTempXXXXXX", catMax);
                            char tempName[16];
                            sprintf(tempName, "normTemp%06u", i);
                            strcat(fileName, tempName);
                            if(!NormFile::IsLocked(fileName))
                            {
                                tempFileOK = true;
                                break;
                            }
                        }
                        if (!tempFileOK)
#else
                        if (!_mktemp(fileName))
#endif // if/else _WIN32_WCE
#else
                        int fd = mkstemp(fileName); 
                        if (fd >= 0)
                        {
                            close(fd);
                        }
                        else   
#endif // if/else WIN32         
                        {
                            PLOG(PL_ERROR, "NormInstance::Notify(RX_OBJECT_NEW) Warning: mkstemp() error: %s\n",
                                    GetErrorString());  
                        } 
                        if (!static_cast<NormFileObject*>(object)->Accept(fileName))
                        {
                            PLOG(PL_ERROR, "NormInstance::Notify(RX_OBJECT_NEW) file object accept error!\n");
                        }
                    }   
                    else
                    {
                        // we're ignoring files
                        PLOG(PL_DETAIL, "NormInstance::Notify() warning: receive file but no cache directory set, so ignoring file\n");
                        notify_pool.Append(*next);
                        return;    
                    }                
                    break;
                }
                case NormObject::DATA:
                {
                    NormDataObject* dataObj = static_cast<NormDataObject*>(object);
                    unsigned int dataLen = (unsigned int)(object->GetSize().GetOffset());
                    char* dataPtr = (NULL != data_alloc_func) ? data_alloc_func(dataLen) : new char[dataLen];
                    if (NULL == dataPtr)
                    {
                        PLOG(PL_FATAL, "NormInstance::Notify(RX_OBJECT_NEW) new dataPtr error: %s\n",
                                       GetErrorString());
                        notify_pool.Append(*next);
                        return;   
                    }
                    // Note that the "true" parameter means the
                    // NORM protocol engine will free the allocated
                    // data on object deletion, so the app should
                    // use NormDataDetachData() to keep the received
                    // data (or copy it before the data object is deleted)
                    if (!dataObj->Accept(dataPtr, dataLen, true))
                    {
                        PLOG(PL_FATAL, "NormInstance::Notify() data object accept error\n");
                        notify_pool.Append(*next);
                        return;   
                    }
                    break;
                }
                default:
                    // This shouldn't occur
                    notify_pool.Append(*next);
                    return;
            }  // end switch(object->GetType())
            break;
        }  // end case RX_OBJECT_NEW
        
        default:
            break;
    }  // end switch(event)
    
    // "Retain" any valid "object" or "sender" handles for API access
    if (NORM_OBJECT_INVALID != object)
        ((NormObject*)object)->Retain();
    else if (NORM_NODE_INVALID != node)
        ((NormNode*)node)->Retain();
    
    bool doNotify = notify_queue.IsEmpty();
    next->event.type = (NormEventType)event;
    next->event.session = session;
    next->event.sender = node;
    next->event.object = object;
    notify_queue.Append(*next);
    
    if (doNotify)
    {
#ifdef WIN32
        if (0 == SetEvent(notify_event))
        {
            PLOG(PL_ERROR, "NormInstance::Notify() SetEvent() error: %s\n",
                           GetErrorString());
        }
#else
        char byte = 0;
        while (1 != write(notify_fd[1], &byte, 1))
        {
            if ((EINTR != errno) && (EAGAIN != errno))
            {
                PLOG(PL_FATAL, "NormInstance::Notify() write() error: %s\n",
                               GetErrorString());
                break;
            }
        }    
#endif // if/else WIN32/UNIX  
    }  
}  // end NormInstance::Notify()

// Purge any notifications associated with a specific object
void NormInstance::PurgeObjectNotifications(NormObjectHandle objectHandle)
{
    if (NORM_OBJECT_INVALID == objectHandle) return;
    
    Notification::Queue::Iterator iterator(notify_queue);
    Notification* next;
    while (NULL != (next = iterator.GetNextItem()))
    {
        if (objectHandle == next->event.object)
        {
            // "Release" the previously-retained object handle
            ((NormObject*)objectHandle)->Release();
            // Remove from queue and put in pool
            notify_queue.Remove(*next);
            notify_pool.Append(*next);
        }
    }
    if ((NULL != previous_notification) && (objectHandle == previous_notification->event.object))
    {
        // "Release" any previously-retained object or node handle
        ((NormObject*)(previous_notification->event.object))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
    // TBD - check if event queue is emptied and reset event/fd
}  // end NormInstance::PurgeObjectNotifications()

// Purge any notifications associated with a specific remote sender node
void NormInstance::PurgeNodeNotifications(NormNodeHandle nodeHandle)
{
    if (NORM_NODE_INVALID == nodeHandle) return;
    Notification::Queue::Iterator iterator(notify_queue);
    Notification* next;
    while (NULL != (next = iterator.GetNextItem()))
    {
        if (nodeHandle == next->event.sender)
        {
            // "Release" the previously-retained object handle
            ((NormNode*)nodeHandle)->Release();
            // Remove this notification from queue and return to pool
            notify_queue.Remove(*next);
            notify_pool.Append(*next);
        }
    }
    if ((NULL != previous_notification) && (nodeHandle == previous_notification->event.sender))
    {
        // "Release" any previously-retained object or node handle
        if (NORM_OBJECT_INVALID != previous_notification->event.object)
            ((NormObject*)(previous_notification->event.object))->Release();
        else
            ((NormNode*)(previous_notification->event.sender))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
    if (notify_queue.IsEmpty()) ResetNotificationEvent();
}  // end NormInstance::PurgeNodeNotifications()

void NormInstance::PurgeSessionNotifications(NormSessionHandle sessionHandle)
{
    if (NORM_SESSION_INVALID == sessionHandle) return;
    Notification::Queue::Iterator iterator(notify_queue);
    Notification* next;
    while (NULL != (next = iterator.GetNextItem()))
    {
        if (next->event.session == sessionHandle)
        {
             if (NORM_OBJECT_INVALID != next->event.object)
                ((NormObject*)next->event.object)->Release();
            else if (NORM_NODE_INVALID != next->event.sender)
                ((NormNode*)next->event.sender)->Release();
            // Remove this notification from queue and return to pool
            notify_queue.Remove(*next);
            notify_pool.Append(*next);
        }   
    }
    if ((NULL != previous_notification) && (sessionHandle == previous_notification->event.session))
    {
        // "Release" any previously-retained object or node handle
        if (NORM_OBJECT_INVALID != previous_notification->event.object)
            ((NormObject*)(previous_notification->event.object))->Release();
        else if (NORM_NODE_INVALID != previous_notification->event.sender)
            ((NormNode*)(previous_notification->event.sender))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
    if (notify_queue.IsEmpty()) ResetNotificationEvent();
}  // end NormInstance::PurgeSessionNotifications()

// Purges notifications of a specific type for a specific session
void NormInstance::PurgeNotifications(NormSessionHandle sessionHandle, NormEventType eventType)
{
    if (NORM_SESSION_INVALID == sessionHandle) return;
    Notification::Queue::Iterator iterator(notify_queue);
    Notification* next;
    while (NULL != (next = iterator.GetNextItem()))
    {
        if ((next->event.session == sessionHandle) &&
            (next->event.type == eventType))
        {
            if (NORM_OBJECT_INVALID != next->event.object)
                ((NormObject*)next->event.object)->Release();
            else if (NORM_NODE_INVALID != next->event.sender)
                ((NormNode*)next->event.sender)->Release();
            // Remove this notification from queue and return to pool
            notify_queue.Remove(*next);
            notify_pool.Append(*next);
        }
    }
    if (notify_queue.IsEmpty()) ResetNotificationEvent();
}  // end NormInstance::PurgeNotifications()

// NormInstance::dispatcher MUST be suspended _before_ calling this
bool NormInstance::GetNextEvent(NormEvent* theEvent)
{
    // First, do any garbage collection for "previous_notification"
    if (NULL != previous_notification)
    {
        // "Release" any previously-retained object or node handle
        if (NORM_OBJECT_INVALID != previous_notification->event.object)
            ((NormObject*)(previous_notification->event.object))->Release();
        else if (NORM_NODE_INVALID != previous_notification->event.sender)
            ((NormNode*)(previous_notification->event.sender))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
    Notification* next;
    while (NULL != (next = notify_queue.RemoveHead()))
    {
        switch (next->event.type)
        {
            case NORM_EVENT_INVALID:
                if (!notify_queue.IsEmpty())
                {
                    // Discard this invalid event and get next one
                    notify_pool.Append(*next);
                    continue;
                }
                break;
            case NORM_RX_OBJECT_UPDATED:
            {
                // reset update event notification for non-streams
                // (NormStreamRead() takes care of streams)
                NormObject* obj = ((NormObject*)next->event.object);
                if (!obj->IsStream()) obj->SetNotifyOnUpdate(true);
                break;
            }
            case NORM_SEND_ERROR:
            {
                NormSession* session = (NormSession*)next->event.session;
                session->ClearSendError();
                break;
            }
            default:
                break;   
        }
	    break;
    }
    if (NULL != next)
    {
        previous_notification = next;  // keep dispatched event for garbage collection
        if (NULL != theEvent) *theEvent = next->event;
    }
    else if (NULL != theEvent)
    {
    	theEvent->type = NORM_EVENT_INVALID;
	    theEvent->session = NORM_SESSION_INVALID;
	    theEvent->sender = NORM_NODE_INVALID;
	    theEvent->object = NORM_OBJECT_INVALID;
    }
    if (notify_queue.IsEmpty()) ResetNotificationEvent();
    return (NULL != next); 
}  // end NormInstance::GetNextEvent()

bool NormInstance::WaitForEvent()
{
    if (!dispatcher.IsThreaded()) 
    {
        PLOG(PL_FATAL, "NormInstance::WaitForEvent() warning: NORM thread not running!\n");
        return false;
    }
#ifdef WIN32
    WaitForSingleObject(notify_event, INFINITE);
#else
    fd_set fdSet;
    FD_ZERO(&fdSet);
    FD_SET(notify_fd[0], &fdSet);
    while (1)
    {
        if (0 > select(notify_fd[0] + 1, &fdSet, (fd_set*)NULL, 
                       (fd_set*)NULL, (struct timeval*)NULL))
        {
            if (EINTR != errno)
            {
                PLOG(PL_FATAL, "NormInstance::WaitForEvent() select() error: %s\n",
                        GetErrorString());
                return false;   
            }
        }
        else
        {
            break;       
        }
    }        
#endif 
    return true;
}  // end NormInstance::WaitForEvent()


bool NormInstance::Startup(bool priorityBoost)
{
    // 1) Create descriptor to use for event notification
#ifdef WIN32
    // Create initially non-signalled, manual reset event
    notify_event = CreateEvent(NULL, TRUE, FALSE, NULL);  
    if (NULL == notify_event)
    {
        PLOG(PL_FATAL, "NormInstance::Startup() CreateEvent() error: %s\n", GetErrorString());
        return false;
    }
#else
    if (0 != pipe(notify_fd))
    {
        PLOG(PL_FATAL, "NormInstance::Startup() pipe() error: %s\n", GetErrorString());
        return false;
    }
    // make reading non-blocking
    if(-1 == fcntl(notify_fd[0], F_SETFL, fcntl(notify_fd[0], F_GETFL, 0)  | O_NONBLOCK))
    {
        PLOG(PL_FATAL, "NormInstance::Startup() fcntl(F_SETFL(O_NONBLOCK)) error: %s\n", GetErrorString());
        close(notify_fd[0]);
        close(notify_fd[1]);
        notify_fd[0] = notify_fd[1] = -1;
        return false;
    }
#endif // if/else WIN32/UNIX
    // 2) Start thread
    priority_boost = priorityBoost;
    return dispatcher.StartThread(priorityBoost);
}  // end NormInstance::Startup()



void NormInstance::ReleasePreviousEvent()
{
    // Garbage collect our "previous_notification"
    if (NULL != previous_notification)
    {
        // Release any previously-retained object or node handles
        if (NORM_OBJECT_INVALID != previous_notification->event.object)
            ((NormObject*)(previous_notification->event.object))->Release();
        else if (NORM_NODE_INVALID != previous_notification->event.sender)
            ((NormNode*)(previous_notification->event.sender))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
}  // end NormInstance::ReleasePreviousEvent()

NORM_API_LINKAGE
void NormReleasePreviousEvent(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance && instance->dispatcher.SuspendThread())
    {
        instance->ReleasePreviousEvent();
        instance->dispatcher.ResumeThread();
    }
}  // end NormReleasePreviousEvent()


void NormInstance::Shutdown()
{
    dispatcher.Stop();
#ifdef WIN32
    if (NULL != notify_event)
    {
        CloseHandle(notify_event);
        notify_event = NULL;
    }
#else
    if (notify_fd[0] >= 0)
    {
        close(notify_fd[0]);  // close read end of pipe
        close(notify_fd[1]);  // close write end of pipe
        notify_fd[0] = notify_fd[1] = -1;
    }
#endif // if/else WIN32/UNIX
    if (rx_cache_path)
    {
        delete[] (char*)rx_cache_path;
        rx_cache_path = NULL;   
    }
    
    // Garbage collect our "previous_notification"
    if (NULL != previous_notification)
    {
        // Release any previously-retained object or node handles
        if (NORM_OBJECT_INVALID != previous_notification->event.object)
            ((NormObject*)(previous_notification->event.object))->Release();
        else if (NORM_NODE_INVALID != previous_notification->event.sender)
            ((NormNode*)(previous_notification->event.sender))->Release();
        notify_pool.Append(*previous_notification);   
        previous_notification = NULL;   
    }
    
    Notification* next;
    while (NULL != (next = notify_queue.RemoveHead()))
    {
        switch (next->event.type)
        {
            case NORM_RX_OBJECT_NEW:
            {
                NormObject* obj = (NormObject*)next->event.object;
                switch (obj->GetType())
                {
                    case NormObject::FILE:
                        // (TBD) unlink temp file?
                        break;
                    default:
                        break;
                }
                break;
            }
            default:
                break;
        }   
        if (NORM_OBJECT_INVALID != next->event.object)
            ((NormObject*)(next->event.object))->Release();
        else if (NORM_NODE_INVALID != next->event.sender)
            ((NormNode*)(next->event.sender))->Release();
        delete next;        
    }
    notify_pool.Destroy();
}  // end NormInstance::Shutdown()

// This function doesn't make sense?
UINT32 NormInstance::CountCompletedObjects(NormSession* session)
{
	UINT32 result = 0UL;
    Notification::Queue::Iterator iterator(notify_queue);
    Notification* next;
    while (NULL != (next = iterator.GetNextItem()))
    {
		if ((session == next->event.session) &&
			(NORM_RX_OBJECT_COMPLETED == next->event.type))
        {
			result ++;
        }
	}
	return result;
} // end NormInstance::CountCompletedObjects()

//////////////////////////////////////////////////////////////////////////
// NORM API FUNCTION IMPLEMENTATIONS
//

NORM_API_LINKAGE 
int NormGetVersion(int* major, int* minor, int* patch)
{
    // TBD - use normVersion.h info instead
    if (NULL != major) *major = NORM_VERSION_MAJOR; 
    if (NULL != minor) *minor = NORM_VERSION_MINOR;
    if (NULL != patch) *patch = NORM_VERSION_PATCH; 
    return NORM_VERSION_MAJOR;
}  // end NormGetVersion()

/** NORM API Initialization */

NORM_API_LINKAGE
NormInstanceHandle NormCreateInstance(bool priorityBoost)
{
    NormInstance* normInstance = new NormInstance;
    if (normInstance)
    {
        if (normInstance->Startup(priorityBoost))
            return ((NormInstanceHandle)normInstance); 
        else
            delete normInstance;
    }
    return NORM_INSTANCE_INVALID;  
}  // end NormCreateInstance()

NORM_API_LINKAGE
void NormDestroyInstance(NormInstanceHandle instanceHandle)
{
    delete ((NormInstance*)instanceHandle);   
}  // end NormDestroyInstance()

NORM_API_LINKAGE
void NormStopInstance(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance) instance->Stop();  // stops NORM protocol thread
}  // end NormStopInstance()

NORM_API_LINKAGE
bool NormRestartInstance(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance)
    {
        if (instance->dispatcher.IsThreaded())
            instance->Stop();
        return instance->Start();
    }
    return false;  // invalid instanceHandle
}  // end NormStartInstance()


NORM_API_LINKAGE
bool NormSuspendInstance(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance) 
        return instance->dispatcher.SuspendThread();  // stops NORM protocol thread
    else
        return false;
}  // end NormSuspendInstance()

NORM_API_LINKAGE
void NormResumeInstance(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance) instance->dispatcher.ResumeThread();  
}  // end NormResumeInstance()


NORM_API_LINKAGE
bool NormSetCacheDirectory(NormInstanceHandle instanceHandle, 
                           const char*        cachePath)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance)
        return instance->SetCacheDirectory(cachePath);
    else
        return false;
} // end NormSetCacheDirectory()

NORM_API_LINKAGE
NormDescriptor NormGetDescriptor(NormInstanceHandle instanceHandle)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance)
        return (instance->GetDescriptor());
    else
        return NORM_DESCRIPTOR_INVALID;
}  // end NormGetDescriptor()


NORM_API_LINKAGE
void NormSetAllocationFunctions(NormInstanceHandle      instanceHandle, 
                                NormAllocFunctionHandle allocFunc, 
                                NormFreeFunctionHandle  freeFunc)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    instance->SetAllocationFunctions(allocFunc, freeFunc);
}  // end NormSetAllocationFunctions()


// if "waitForEvent" is false, this is a non-blocking call
// (TBD) add a timeout option to this?

NORM_API_LINKAGE
bool NormGetNextEvent(NormInstanceHandle instanceHandle, NormEvent* theEvent, bool waitForEvent)
{
    NormInstance* instance = (NormInstance*)instanceHandle;
    bool result = false;
    if (instance)
    {
        if (instance->dispatcher.SuspendThread())
        {
            if (waitForEvent)
            {
                if (instance->NotifyQueueIsEmpty()) 
                {
                    // no pending events, so resume and wait
                    instance->dispatcher.ResumeThread();
                    if (!instance->WaitForEvent())
                    {
                        // Indication that NormInstance is dead
			            // TBD - how do we inform app although this shouldn't
			            // happen unless the app destroys the "instance"
                        return false;
                    }
                    // re-suspend thread after wait
                    if (!instance->dispatcher.SuspendThread()) return false;
                }
            }
            result = instance->GetNextEvent(theEvent);
            instance->dispatcher.ResumeThread();
        }
    }
    return result;  
}  // end NormGetNextEvent()


NORM_API_LINKAGE
bool NormIsUnicastAddress(const char* address)
{
    // TBD - is this really a thread-safe thing to do?
    ProtoAddress addr;
    if ((NULL != address) && addr.ResolveFromString(address))
        return addr.IsUnicast();
    else
        return false;  // not valid, so not unicast
}  // end NormIsUnicast()

/** NORM Session Creation and Control Functions */
NORM_API_LINKAGE
NormSessionHandle NormCreateSession(NormInstanceHandle instanceHandle,
                                    const char*        sessionAddr,
                                    UINT16             sessionPort,
                                    NormNodeId         localNodeId)
{
    // (TBD) wrap this with SuspendThread/ResumeThread ???
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = 
            instance->session_mgr.NewSession(sessionAddr, sessionPort, localNodeId);
        instance->dispatcher.ResumeThread();
        if (NULL != session) 
            return ((NormSessionHandle)session);
    }
    return NORM_SESSION_INVALID;
}  // end NormCreateSession()

NORM_API_LINKAGE
void NormDestroySession(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {    
        NormSession* session = (NormSession*)sessionHandle;
        if (NULL != session)
        {
            session->Close();
            session->GetSessionMgr().DeleteSession(session);
            instance->PurgeSessionNotifications(sessionHandle);
        }
        instance->dispatcher.ResumeThread();
    }
}  // end NormDestroySession()

NORM_API_LINKAGE 
NormInstanceHandle NormGetInstance(NormSessionHandle sessionHandle)
{
    
    return (NormInstanceHandle)NormInstance::GetInstanceFromSession(sessionHandle);
}  // end NormGetIntance()

NORM_API_LINKAGE
void NormSetUserData(NormSessionHandle sessionHandle, const void* userData)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {    
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetUserData(userData);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetUserData()

NORM_API_LINKAGE
const void* NormGetUserData(NormSessionHandle sessionHandle)
{
    const void* userData = NULL;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) 
                userData = session->GetUserData();
            instance->dispatcher.ResumeThread();
        }
    }
    return userData;
}  // end NormGetUserData()


NORM_API_LINKAGE 
void NormSetUserTimer(NormSessionHandle sessionHandle, double seconds)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) session->SetUserTimer(seconds);
            instance->PurgeNotifications(sessionHandle, NORM_USER_TIMEOUT);
            instance->dispatcher.ResumeThread();
        }
    }
}   // end NormSetUserTimer()

NORM_API_LINKAGE 
void NormCancelUserTimer(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) session->SetUserTimer(-1.0);  // interval less than zero cancels timer
            instance->PurgeNotifications(sessionHandle, NORM_USER_TIMEOUT);
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormCancelUserTimer()


NORM_API_LINKAGE
NormNodeId NormGetLocalNodeId(NormSessionHandle sessionHandle)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (NULL != session)
        return session->LocalNodeId();
    else
        return NORM_NODE_NONE;      
}  // end NormGetLocalNodeId()

NORM_API_LINKAGE
bool NormGetAddress(NormSessionHandle   sessionHandle,
                    char*               addrBuffer, 
                    unsigned int*       bufferLen,
                    UINT16*             port)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            const ProtoAddress& sessionAddr = session->Address();
            unsigned int addrLen = sessionAddr.GetLength();
            if (addrBuffer && bufferLen && (addrLen <= *bufferLen))
            {
                memcpy(addrBuffer, sessionAddr.GetRawHostAddress(), addrLen);
                result = true;
            } 
            else if (NULL == addrBuffer)
            {
                result = true; // just a query for addrLen and/or port
            }      
            if (bufferLen) *bufferLen = addrLen;
            if (port) *port = sessionAddr.GetPort();
            instance->dispatcher.ResumeThread();  
        }
    }
    return result;
}  // end NormGetAddress()

NORM_API_LINKAGE
UINT16 NormGetRxPort(NormSessionHandle sessionHandle)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (NULL != session)
        return session->GetRxPort();
    else
        return 0;      
}  // end NormGetRxPort()


NORM_API_LINKAGE
bool NormGetRxBindAddress(NormSessionHandle sessionHandle, char* addr, unsigned int& addrLen, UINT16& port)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if ((NULL != instance) && instance->dispatcher.SuspendThread())
    {    
        NormSession* session = (NormSession*)sessionHandle;
        port = session->GetRxPort();
        ProtoAddress bindAddr = session->GetRxBindAddr();
        if (!bindAddr.IsValid())
        {
            addrLen = 0;
            result = true;
        }
        else if (addrLen < bindAddr.GetLength())
        {
            addrLen = bindAddr.GetLength();
        }
        else
        {
            addrLen = bindAddr.GetLength();
            memcpy(addr, bindAddr.GetRawHostAddress(), addrLen);
            result = true;
        }    
        instance->dispatcher.ResumeThread();  
    }
    else
    {
        addrLen = port = 0;
    }    
    return result;
}  // end NormGetRxBindAddress()

NORM_API_LINKAGE
bool NormSetTxPort(NormSessionHandle sessionHandle,
                   UINT16            txPort,
                   bool              enableReuse,
                   const char*       txAddress)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (NULL != session) 
                result = session->SetTxPort(txPort, enableReuse, txAddress);
            instance->dispatcher.ResumeThread();
        }
    } 
    return result;
}  // end NormSetTxPort()

NORM_API_LINKAGE
UINT16 NormGetTxPort(NormSessionHandle sessionHandle)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (NULL != session)
        return session->GetTxPort();
    else
        return 0;
}  // end NormGetTxPort()

NORM_API_LINKAGE
void NormSetTxOnly(NormSessionHandle sessionHandle,
                   bool              txOnly,
                   bool              connectToSessionAddress)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetTxOnly(txOnly, connectToSessionAddress);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetTxOnly()

NORM_API_LINKAGE
bool NormPresetObjectInfo(NormSessionHandle  sessionHandle,
                          unsigned long      objectSize,
                          UINT16             segmentSize, 
                          UINT16             numData, 
                          UINT16             numParity)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) 
        {
            result = session->SetPresetFtiData((unsigned int)objectSize, segmentSize, numData, numParity);
            if (result) session->SenderSetFtiMode(NormSession::FTI_PRESET);
        }
        instance->dispatcher.ResumeThread();
    }
    return result;
} // end NormPresetObjectInfo()

NORM_API_LINKAGE
void NormLimitObjectInfo(NormSessionHandle sessionHandle, bool state)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) 
        {
            if (state)
                session->SenderSetFtiMode(NormSession::FTI_INFO);
            else
                session->SenderSetFtiMode(NormSession::FTI_ALWAYS);
        }
        instance->dispatcher.ResumeThread();
    }
} // end NormLimitObjectInfo()

// These functions are used internally by the NormSocket API extension

NORM_API_LINKAGE
void NormSetId(NormSessionHandle sessionHandle, NormNodeId normId)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (NULL != session) session->SetNodeId(normId);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetId()

NORM_API_LINKAGE
bool NormChangeDestination(NormSessionHandle sessionHandle,
	                       const char*       sessionAddress,
	                       UINT16            sessionPort,
	                       bool              connectToSessionAddress)
{
	NormSession* session = (NormSession*)sessionHandle;
	if (NULL == session) return false;
	// First, see if we can make a valid ProtoAddress
	ProtoAddress dest;
	if (NULL != sessionAddress)
	{
		if (!dest.ResolveFromString(sessionAddress))
			return false;
	}
	else
	{
		dest = session->Address();
	}
    dest.SetPort(sessionPort);
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        if (NULL != session) 
        {
            session->SetAddress(dest);
            if (connectToSessionAddress)
                session->SetTxOnly(session->GetTxOnly(), true);
        }
        instance->dispatcher.ResumeThread();
    }
    return true;
}  // end NormChangeDestination()

NORM_API_LINKAGE
void NormSetServerListener(NormSessionHandle sessionHandle, bool state)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) session->SetServerListener(state);
            instance->dispatcher.ResumeThread();
        }
    } 
}  // end NormSetServerListener()


NORM_API_LINKAGE
bool NormTransferSender(NormSessionHandle sessionHandle, NormNodeHandle senderHandle)
{
    // The NormSession::InsertRemoteSender() used below synthesizes a NORM_CMD(CC) that
    // is injected into the "sessionHandle" NormSession which results in a new remote
    // sender being established.  I.e., it basically "clones" the sender from another
    // NormSession into the target NormSession
	bool result = false;
    NormInstance* dstInstance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != dstInstance)
    {
        if (dstInstance->dispatcher.SuspendThread())
        {
            NormInstance* srcInstance = NormInstance::GetInstanceFromNode(senderHandle);
            if (srcInstance->dispatcher.SuspendThread())
            {
                NormSession* session = (NormSession*)sessionHandle;
                NormSenderNode* sender = (NormSenderNode*)senderHandle;
                if ((NULL != session) && (NULL != sender))
                    result = session->InsertRemoteSender(*sender);
                srcInstance->dispatcher.ResumeThread();
            }
            dstInstance->dispatcher.ResumeThread();
        }
    }
	return result;
}  // end NormTransferSender()

NORM_API_LINKAGE
void NormSetRxPortReuse(NormSessionHandle sessionHandle,
                        bool              enableReuse,
                        const char*       rxAddress,     // bind() to <rxAddress>/<sessionPort>
                        const char*       senderAddress, // connect() to <senderAddress>/<senderPort>
                        UINT16            senderPort)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) session->SetRxPortReuse(enableReuse, rxAddress, senderAddress, senderPort);
            instance->dispatcher.ResumeThread();
        }
    } 
}  // end NormSetRxPortReuse()


NORM_API_LINKAGE
void NormSetEcnSupport(NormSessionHandle sessionHandle, bool ecnEnable, bool ignoreLoss, bool tolerateLoss)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session) session->SetEcnSupport(ecnEnable, ignoreLoss, tolerateLoss);
            instance->dispatcher.ResumeThread();
        }
    } 
}  // end NormSetEcnSupport()

NORM_API_LINKAGE
bool NormSetMulticastInterface(NormSessionHandle sessionHandle,
                               const char*       interfaceName)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session)
                result = session->SetMulticastInterface(interfaceName);
            instance->dispatcher.ResumeThread();
        }
    }
    return result;     
}  // end NormSetMulticastInterface()

NORM_API_LINKAGE 
bool NormSetSSM(NormSessionHandle sessionHandle,
                const char*       sourceAddress)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session)
                result = session->SetSSM(sourceAddress);
            instance->dispatcher.ResumeThread();
        }
    }
    return result;     
}  // end NormSetSSM()

NORM_API_LINKAGE
bool NormSetTTL(NormSessionHandle sessionHandle,
                unsigned char     ttl)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (NULL != instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session)
                result = session->SetTTL(ttl);
            instance->dispatcher.ResumeThread();
        }
    }
    return result;     
}  // end NormSetTTL()

NORM_API_LINKAGE
bool NormSetTOS(NormSessionHandle sessionHandle,
                unsigned char     tos)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            NormSession* session = (NormSession*)sessionHandle;
            if (session)
                result = session->SetTOS(tos);
            instance->dispatcher.ResumeThread();
        }
    }
    return result;     
}  // end NormSetTOS()

/** Special test/debug support functions */

NORM_API_LINKAGE
bool NormSetLoopback(NormSessionHandle sessionHandle, bool state)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session)
        return session->SetLoopback(state);
    else
        return false;  
}  // end NormSetLoopback()


NORM_API_LINKAGE
bool NormSetMulticastLoopback(NormSessionHandle sessionHandle, bool state)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session)
        return session->SetMulticastLoopback(state);
    else
        return false;  
}  // end NormSetLoopback()

NORM_API_LINKAGE
bool NormSetFragmentation(NormSessionHandle sessionHandle, bool state)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session)
        return session->SetFragmentation(state);
    else
        return false;  
}  // end NormSetFragmentation()

NORM_API_LINKAGE
void NormSetMessageTrace(NormSessionHandle sessionHandle, bool state)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->SetTrace(state);
}  // end NormSetMessageTrace()

NORM_API_LINKAGE
void NormSetTxLoss(NormSessionHandle sessionHandle, double percent)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->SetTxLoss(percent);
}  // end NormSetTxLoss()

NORM_API_LINKAGE
void NormSetRxLoss(NormSessionHandle sessionHandle, double percent)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->SetRxLoss(percent);
}  // end NormSetRxLoss()

NORM_API_LINKAGE
bool NormOpenDebugLog(NormInstanceHandle instanceHandle, const char *path)
{
    /* NOTE: This only locks one thread.  Multiple NormInstances could
    cause problems with this. */
    bool result = false;
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance->dispatcher.SuspendThread()) {
        result = OpenDebugLog(path);
        instance->dispatcher.ResumeThread();
    }
    return result;
}

NORM_API_LINKAGE
void NormCloseDebugLog(NormInstanceHandle instanceHandle)
{
    /* NOTE: This only locks one thread.  Multiple NormInstances could
    cause problems with this. */
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance->dispatcher.SuspendThread()) {
        CloseDebugLog();
        instance->dispatcher.ResumeThread();
    }
}

NORM_API_LINKAGE
bool NormOpenDebugPipe(NormInstanceHandle instanceHandle, const char *pipeName)
{
    /* NOTE: This only locks one thread.  Multiple NormInstances could
    cause problems with this. */
    bool result = false;
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance->dispatcher.SuspendThread()) {
        result = OpenDebugPipe(pipeName);
        instance->dispatcher.ResumeThread();
    }
    return result;
}   // end NormOpenDebugPipe()

NORM_API_LINKAGE
void NormCloseDebugPipe(NormInstanceHandle instanceHandle)
{
    /* NOTE: This only locks one thread.  Multiple NormInstances could
    cause problems with this. */
    NormInstance* instance = (NormInstance*)instanceHandle;
    if (instance->dispatcher.SuspendThread()) {
        CloseDebugPipe();
        instance->dispatcher.ResumeThread();
    }
}  // end NormCloseDebugPipe()

NORM_API_LINKAGE
void NormSetDebugLevel(unsigned int level)
{
    // Sets underlying Protolib debug leve
    SetDebugLevel(level);
}

NORM_API_LINKAGE
unsigned int NormGetDebugLevel()
{
    return GetDebugLevel();
}

NORM_API_LINKAGE
void NormSetReportInterval(NormSessionHandle sessionHandle, double interval)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
            session->SetReportTimerInterval(interval);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetReportInterval()

NORM_API_LINKAGE
double NormGetReportInterval(NormSessionHandle sessionHandle)
{
    double result = 0;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
            result = session->GetReportTimerInterval();
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormGetReportInterval()

/** NORM Sender Functions */

NORM_API_LINKAGE
NormSessionId NormGetRandomSessionId()
{
    ProtoTime currentTime;
    currentTime.GetCurrentTime();
    srand((unsigned int)currentTime.usec());  // seed random number generator
    return (NormSessionId)rand();
}  // end NormGetRandomSessionId()

NORM_API_LINKAGE
bool NormStartSender(NormSessionHandle  sessionHandle,
                     NormSessionId      sessionId,
                     UINT32             bufferSpace,
                     UINT16             segmentSize,
                     UINT16             numData,
                     UINT16             numParity,
                     UINT8              fecId)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
            result = session->StartSender(sessionId, bufferSpace, segmentSize, numData, numParity, fecId);
        else
            result = false;
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStartSender()

NORM_API_LINKAGE
void NormStopSender(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->StopSender();
        instance->dispatcher.ResumeThread();
    }
}  // end NormStopSender()


NORM_API_LINKAGE
double NormGetTxRate(NormSessionHandle sessionHandle)
{
    if (NORM_SESSION_INVALID != sessionHandle)
        return (((NormSession*)sessionHandle)->GetTxRate());
    else
        return -1.0;
}  // end NormGetTxRate()

NORM_API_LINKAGE
void NormSetTxRate(NormSessionHandle sessionHandle,
                         double            bitsPerSecond)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetTxRate(bitsPerSecond);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetTxRate()

NORM_API_LINKAGE
bool NormSetTxSocketBuffer(NormSessionHandle sessionHandle, 
                           unsigned int      bufferSize)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) 
            result = session->SetTxSocketBuffer(bufferSize);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormSetTxSocketBuffer()

NORM_API_LINKAGE
void NormSetFlowControl(NormSessionHandle sessionHandle, double flowControlFactor)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetFlowControl(flowControlFactor);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetFlowControl()

NORM_API_LINKAGE
void NormSetCongestionControl(NormSessionHandle sessionHandle, bool enable, bool adjustRate)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetCongestionControl(enable, adjustRate);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetCongestionControl()

NORM_API_LINKAGE
void NormSetTxRateBounds(NormSessionHandle sessionHandle,
                         double            rateMin,
                         double            rateMax)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetTxRateBounds(rateMin, rateMax);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetTxRateBounds()

NORM_API_LINKAGE
void NormSetTxCacheBounds(NormSessionHandle sessionHandle,
                          NormSize          sizeMax,
                          UINT32            countMin,
                          UINT32            countMax)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        NormObjectSize theSize(sizeMax);
        if (session) session->SetTxCacheBounds(theSize, countMin, countMax);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetTxCacheBounds()

NORM_API_LINKAGE
void NormSetAutoParity(NormSessionHandle sessionHandle, unsigned char autoParity)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SenderSetAutoParity(autoParity);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetAutoParity()

NORM_API_LINKAGE
void NormSetGrttEstimate(NormSessionHandle sessionHandle,
                         double            grttEstimate)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SenderSetGrtt(grttEstimate);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGrttEstimate()

NORM_API_LINKAGE
double NormGetGrttEstimate(NormSessionHandle sessionHandle)
{
    if (NORM_SESSION_INVALID != sessionHandle)
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->ResetGrttNotification();
        return (session->SenderGrtt());
    }
    else
    {
        return -1.0;
    }
}  // end NormGetGrttEstimate()

NORM_API_LINKAGE
void NormSetGrttMax(NormSessionHandle sessionHandle,
                    double            grttMax)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetGrttMax(grttMax);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGrttMax()

NORM_API_LINKAGE
void NormSetGrttProbingMode(NormSessionHandle sessionHandle,
                            NormProbingMode   probingMode)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SetGrttProbingMode((NormSession::ProbingMode)probingMode);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGrttProbingMode()

NORM_API_LINKAGE
void NormSetGrttProbingInterval(NormSessionHandle sessionHandle,
                                double            intervalMin,
                                double            intervalMax)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetGrttProbingInterval(intervalMin, intervalMax);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGrttProbingInterval()

NORM_API_LINKAGE
void NormSetGrttProbingTOS(NormSessionHandle sessionHandle,
                           UINT8              probeTOS)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SetProbeTOS(probeTOS);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGrttProbingTOS()

NORM_API_LINKAGE
void NormSetBackoffFactor(NormSessionHandle sessionHandle,
                          double            backoffFactor)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (backoffFactor >= 0.0)
            session->SetBackoffFactor(backoffFactor);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetBackoffFactor()

NORM_API_LINKAGE
void NormSetGroupSize(NormSessionHandle sessionHandle,
                      unsigned int      groupSize)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SenderSetGroupSize((double)groupSize);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetGroupSize()

NORM_API_LINKAGE 
void NormSetTxRobustFactor(NormSessionHandle sessionHandle,
                           int               robustFactor)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SetTxRobustFactor(robustFactor);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetTxRobustFactor()

NORM_API_LINKAGE
NormObjectHandle NormFileEnqueue(NormSessionHandle  sessionHandle,
                                 const char*        fileName,
                                 const char*        infoPtr, 
                                 unsigned int       infoLen)
{
    NormObjectHandle objectHandle = NORM_OBJECT_INVALID;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
        {
            NormObject* obj = 
                static_cast<NormObject*>(session->QueueTxFile(fileName, infoPtr, infoLen));
            if (obj) objectHandle = (NormObjectHandle)(obj);
        }
        instance->dispatcher.ResumeThread();
    }
    return objectHandle;
}  // end NormFileEnqueue()

NORM_API_LINKAGE
NormObjectHandle NormDataEnqueue(NormSessionHandle  sessionHandle,
                                 const char*        dataPtr,
                                 UINT32             dataLen,
                                 const char*        infoPtr, 
                                 unsigned int       infoLen)
{
    NormObjectHandle objectHandle = NORM_OBJECT_INVALID;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
        {
            NormObject* obj = 
                static_cast<NormObject*>(session->QueueTxData(dataPtr, dataLen, infoPtr, infoLen));
            if (NULL != obj) objectHandle = (NormObjectHandle)obj;
        }
        instance->dispatcher.ResumeThread();
    }
    return objectHandle;
}  // end NormDataEnqueue()


NORM_API_LINKAGE 
bool NormRequeueObject(NormSessionHandle sessionHandle, NormObjectHandle objectHandle)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
        {
            if (NORM_OBJECT_INVALID != objectHandle)
                result = session->RequeueTxObject((NormObject*)objectHandle);
        }
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormRequeueObject()

NORM_API_LINKAGE
NormObjectHandle NormStreamOpen(NormSessionHandle  sessionHandle,
                                UINT32             bufferSize,
                                const char*        infoPtr, 
                                unsigned int       infoLen)
{
    NormObjectHandle objectHandle = NORM_OBJECT_INVALID;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
        {
            NormStreamObject* streamObj = session->QueueTxStream(bufferSize, true, infoPtr, infoLen);
            NormObject* obj = 
                static_cast<NormObject*>(streamObj);
            if (obj) objectHandle = (NormObjectHandle)obj;
        }
        instance->dispatcher.ResumeThread();
    }
    return objectHandle;
}  // end NormStreamOpen()

NORM_API_LINKAGE
void NormStreamClose(NormObjectHandle streamHandle, bool graceful)
{
    NormStreamObject* stream =
        static_cast<NormStreamObject*>((NormObject*)streamHandle);
    if (NULL != stream)
    {
        if (graceful && (NULL == stream->GetSender()))
        {
            NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
            if (instance && instance->dispatcher.SuspendThread())
            {
                stream->Close(true);  // graceful stream closure
                instance->dispatcher.ResumeThread();
            }  
        }
        else
        {
            NormObjectCancel(streamHandle);
        }
    }
}  // end NormStreamClose()

NORM_API_LINKAGE
unsigned int NormGetStreamBufferSegmentCount(unsigned int bufferBytes, UINT16 segmentSize, UINT16 blockSize)
{
    // This same computation is performed in NormStreamObject::Open() in "normObject.cpp"
    // (Note the number of stream buffer segments is always smaller than the 
    //  blockSize*pending_mask.GetSize())
    unsigned int numBlocks = bufferBytes / (blockSize * segmentSize);
    if (numBlocks < 2) numBlocks = 2; // NORM enforces a 2-block minimum buffer size
    return (numBlocks * blockSize);
}  // end NormGetStreamBufferSegmentCount()

NORM_API_LINKAGE
unsigned int NormStreamWrite(NormObjectHandle   streamHandle,
                             const char*        buffer,
                             unsigned int       numBytes)
{
    // Note: Since an underlying issue with ProtoDispatcher::SignalThread() had been resolved,
    //       using  ProtoDispatcher::SuspendThread() should be sufficient since the underlying
    //       protolib time scheduling, etc. code actually invokes SignalThread() on an
    //       as-needed basis.  Thus, using SuspendThread() (lighter weight) should suffice
    unsigned int result = 0;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if ((NULL != instance) && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        result = stream->Write(buffer, numBytes, false);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStreamWrite()

NORM_API_LINKAGE
void NormStreamFlush(NormObjectHandle streamHandle, 
                     bool             eom,
                     NormFlushMode    flushMode)
{
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if ((NULL != instance) && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        NormStreamObject::FlushMode saveFlushMode = stream->GetFlushMode();
        stream->SetFlushMode((NormStreamObject::FlushMode)flushMode);
        stream->Flush(eom);
        stream->SetFlushMode(saveFlushMode);
        instance->dispatcher.ResumeThread();
    }
}  // end NormStreamFlush()

NORM_API_LINKAGE
void NormStreamSetAutoFlush(NormObjectHandle    streamHandle,
                            NormFlushMode       flushMode)
{
    NormStreamObject* stream = 
        static_cast<NormStreamObject*>((NormObject*)streamHandle);
    if (stream)
        stream->SetFlushMode((NormStreamObject::FlushMode)flushMode);
}  // end NormStreamSetAutoFlush()

NORM_API_LINKAGE
void NormStreamSetPushEnable(NormObjectHandle streamHandle, bool state)
{
    NormStreamObject* stream = 
        static_cast<NormStreamObject*>((NormObject*)streamHandle);
    if (stream) stream->SetPushMode(state);
}  // end NormStreamSetPushEnable()

NORM_API_LINKAGE
bool NormStreamHasVacancy(NormObjectHandle streamHandle)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        if (NULL != stream)
            result = stream->HasVacancy();
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStreamHasVacancy()

NORM_API_LINKAGE
unsigned int NormStreamGetVacancy(NormObjectHandle streamHandle, unsigned int bytesWanted)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        if (NULL != stream)
            result = stream->GetVacancy(bytesWanted);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStreamGetVacancy()

NORM_API_LINKAGE
void NormStreamMarkEom(NormObjectHandle streamHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        if (stream) stream->Write(NULL, 0, true);
        instance->dispatcher.ResumeThread();
    }
}  // end NormStreamMarkEom()

NORM_API_LINKAGE
bool NormSetWatermark(NormSessionHandle  sessionHandle,
                      NormObjectHandle   objectHandle,
                      bool               overrideFlush)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        NormObject* obj = (NormObject*)objectHandle;
        if (session && obj)
        {
            // Purge any existing NORM_TX_WATERMARK_COMPLETED notifications to be safe
            instance->PurgeNotifications(sessionHandle, NORM_TX_WATERMARK_COMPLETED);
            // (segmentId doesn't matter for non-stream)
            if (obj->IsStream())
            {
                NormStreamObject* stream = static_cast<NormStreamObject*>(obj);
                session->SenderSetWatermark(stream->GetId(), 
                                            stream->FlushBlockId(),
                                            stream->FlushSegmentId(),
                                            overrideFlush);  
            }
            else
            {
                NormBlockId blockId = obj->GetFinalBlockId();
                NormSegmentId segmentId = obj->GetBlockSize(blockId) - 1;
                session->SenderSetWatermark(obj->GetId(), 
                                            blockId,
                                            segmentId,
                                            overrideFlush);  
            }
            result = true;
        }        
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormSetWatermark()

NORM_API_LINKAGE 
bool NormSetWatermarkEx(NormSessionHandle  sessionHandle,
                        NormObjectHandle   objectHandle,
                        const char*        buffer,
                        unsigned int       numBytes,
                        bool               overrideFlush)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        NormObject* obj = (NormObject*)objectHandle;
        if (session && obj)
        {
            // Purge any existing NORM_TX_WATERMARK_COMPLETED notifications to be safe
            instance->PurgeNotifications(sessionHandle, NORM_TX_WATERMARK_COMPLETED);
            // (segmentId doesn't matter for non-stream)
            if (obj->IsStream())
            {
                NormStreamObject* stream = static_cast<NormStreamObject*>(obj);
                result = session->SenderSetWatermark(stream->GetId(), 
                                                     stream->FlushBlockId(),
                                                     stream->FlushSegmentId(),
                                                     overrideFlush,
                                                     buffer, numBytes);  
            }
            else
            {
                NormBlockId blockId = obj->GetFinalBlockId();
                NormSegmentId segmentId = obj->GetBlockSize(blockId) - 1;
                result = session->SenderSetWatermark(obj->GetId(), 
                                                     blockId,
                                                     segmentId,
                                                     overrideFlush,
                                                     buffer, numBytes);   
            }
        }        
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormSetWatermarkEx()

NORM_API_LINKAGE
bool NormResetWatermark(NormSessionHandle  sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        // Purge any existing NORM_TX_WATERMARK_COMPLETED notifications to be safe
        instance->PurgeNotifications(sessionHandle, NORM_TX_WATERMARK_COMPLETED);
        NormSession* session = (NormSession*)sessionHandle;
        session->SenderResetWatermark();
        instance->dispatcher.ResumeThread();
        return true;
    }
    else
    {
        return false;
    }
}  // end NormResetWatermark()

NORM_API_LINKAGE
void NormCancelWatermark(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SenderCancelWatermark();
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetWatermark()

NORM_API_LINKAGE
bool NormAddAckingNode(NormSessionHandle  sessionHandle,
                       NormNodeId         nodeId)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session)
            result = (NULL != session->SenderAddAckingNode(nodeId));
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormAddAckingNode()

NORM_API_LINKAGE
void NormRemoveAckingNode(NormSessionHandle  sessionHandle,
                          NormNodeId         nodeId)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SenderRemoveAckingNode(nodeId);
        instance->dispatcher.ResumeThread();
    }
}  // end NormRemoveAckingNode()

NORM_API_LINKAGE
NormNodeHandle NormGetAckingNodeHandle(NormSessionHandle  sessionHandle,
                                       NormNodeId         nodeId)
{
	if (NORM_SESSION_INVALID != sessionHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormSession* session = (NormSession*)sessionHandle;
            NormAckingNode* acker = session->SenderFindAckingNode(nodeId);
			instance->dispatcher.ResumeThread();
            if (NULL != acker)
                return ((NormNodeHandle)static_cast<NormNode*>(acker));
        }
    }
    return NORM_NODE_INVALID;
}  // end NormGetAckingNodeHandle()

NORM_API_LINKAGE
void NormSetAutoAckingNodes(NormSessionHandle   sessionHandle,
                            NormTrackingStatus  trackingStatus)
{
    NormSession* session = (NormSession*)sessionHandle;
    switch (trackingStatus)
    {
        case NORM_TRACK_NONE:
            session->SenderSetAutoAckingNodes(NormSession::TRACK_NONE);
            break;
        case NORM_TRACK_RECEIVERS:
            session->SenderSetAutoAckingNodes(NormSession::TRACK_RECEIVERS);
            break;
        case NORM_TRACK_SENDERS:
            session->SenderSetAutoAckingNodes(NormSession::TRACK_SENDERS);
            break;
        case NORM_TRACK_ALL:
            session->SenderSetAutoAckingNodes(NormSession::TRACK_ALL);
            break;
        default:
            break;
    }
}  // end NormSetAutoAckingNodes()

NORM_API_LINKAGE
NormAckingStatus NormGetAckingStatus(NormSessionHandle  sessionHandle,
                                     NormNodeId         nodeId)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        NormAckingStatus status = 
            (NormAckingStatus)session->SenderGetAckingStatus(nodeId);
        instance->dispatcher.ResumeThread();
        return status;
    }
    else
    {
        return NORM_ACK_INVALID;
    }
}  // end NormGetAckingNodeStatus()

NORM_API_LINKAGE 
bool NormGetNextAckingNode(NormSessionHandle    sessionHandle,
                           NormNodeId*          nodeId,   
                           NormAckingStatus*    ackingStatus)
{
    if (NULL == nodeId) return false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        bool result = session->SenderGetNextAckingNode(*nodeId, (NormSession::AckingStatus*)ackingStatus);
        instance->dispatcher.ResumeThread();
        return result;
    }
    else
    {
        return false;
    }
}   // end NormGetNextAckingNode()

NORM_API_LINKAGE
bool NormGetAckEx(NormSessionHandle sessionHandle,
                  NormNodeId        nodeId,   
                  char*             buffer,
                  unsigned int*     buflen)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        bool result = (NormAckingStatus)session->SenderGetAckEx(nodeId, buffer, buflen);
        instance->dispatcher.ResumeThread();
        return result;
    }
    if (NULL != buflen) *buflen = 0;
    return false;
}  // end NormGetAckEx()


NORM_API_LINKAGE 
bool NormSendCommand(NormSessionHandle  sessionHandle,
                     const char*        cmdBuffer, 
                     unsigned int       cmdLength, 
                     bool               robust)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        bool result = session->SenderSendCmd(cmdBuffer, cmdLength, robust);
        instance->dispatcher.ResumeThread();
        return result;
    }
    else
    {
        return false;
    }
}  // end NormSendCommand()

NORM_API_LINKAGE 
void NormCancelCommand(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SenderCancelCmd();
        // we purge in case command was already sent notification posted
        instance->PurgeNotifications(sessionHandle, NORM_TX_CMD_SENT);
        instance->dispatcher.ResumeThread();
    }
}  // end NormCancelCommand()


// This one is not part of the public API (for NormSocket use currently)
bool NormSendCommandTo(NormSessionHandle  sessionHandle,
                       const char*        cmdBuffer, 
                       unsigned int       cmdLength, 
                       const char*        addr,
                       UINT16             port)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        ProtoAddress dest;
        if (dest.ResolveFromString(addr))
        {
            dest.SetPort(port);
            result = session->SenderSendAppCmd(cmdBuffer, cmdLength, dest);
        }
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormSendCommandTo()


NORM_API_LINKAGE 
void NormSetSynStatus(NormSessionHandle sessionHandle, bool state)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SenderSetSynStatus(state);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetSynStatus()


/** NORM Receiver Functions */

NORM_API_LINKAGE
bool NormStartReceiver(NormSessionHandle  sessionHandle,
                       UINT32      bufferSpace)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        result = session->StartReceiver(bufferSpace);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStartReceiver()

NORM_API_LINKAGE
void NormStopReceiver(NormSessionHandle sessionHandle)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->StopReceiver();
        instance->dispatcher.ResumeThread();
    }
}  // end NormStopReceiver()


NORM_API_LINKAGE 
void NormSetRxCacheLimit(NormSessionHandle sessionHandle,
                         unsigned short    countMax)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) session->SetRxCacheMax(countMax);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetRxCacheLimit()

NORM_API_LINKAGE
bool NormSetRxSocketBuffer(NormSessionHandle sessionHandle, 
                           unsigned int      bufferSize)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        if (session) 
            result = session->SetRxSocketBuffer(bufferSize);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormSetRxSocketBuffer()

NORM_API_LINKAGE
void NormSetSilentReceiver(NormSessionHandle sessionHandle,
                           bool              silent,
                           INT32             maxDelay)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) 
    {
        session->ReceiverSetSilent(silent);
        session->RcvrSetMaxDelay(maxDelay);
    }
}  // end NormSetSilentReceiver()

NORM_API_LINKAGE
void NormSetDefaultUnicastNack(NormSessionHandle sessionHandle,
                               bool              unicastNacks)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->ReceiverSetUnicastNacks(unicastNacks);
}  // end NormSetDefaultUnicastNack()

NORM_API_LINKAGE
void NormNodeSetUnicastNack(NormNodeHandle   nodeHandle,
                            bool             unicastNacks)
{
    
    NormNode* node = (NormNode*)nodeHandle;
    if ((NULL != node) && (NormNode::SENDER == node->GetType()))
    {
        NormSenderNode* sender = static_cast<NormSenderNode*>(node);
        sender->SetUnicastNacks(unicastNacks);
    }
}  // end NormNodeSetUnicastNack()

NORM_API_LINKAGE 
void NormSetDefaultSyncPolicy(NormSessionHandle sessionHandle,
                              NormSyncPolicy    syncPolicy)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->ReceiverSetDefaultSyncPolicy((NormSenderNode::SyncPolicy)syncPolicy);
}  // end NormSetDefaultSyncPolicy()

NORM_API_LINKAGE
void NormSetDefaultNackingMode(NormSessionHandle sessionHandle,
                               NormNackingMode   nackingMode)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session) session->ReceiverSetDefaultNackingMode((NormObject::NackingMode)nackingMode);
}  // end NormSetDefaultNackingMode()

NORM_API_LINKAGE
void NormNodeSetNackingMode(NormNodeHandle   nodeHandle,
                            NormNackingMode  nackingMode)
{
     NormNode* node = (NormNode*)nodeHandle;
    if ((NULL != node) && (NormNode::SENDER == node->GetType()))
    {
        NormSenderNode* sender = static_cast<NormSenderNode*>(node);
        sender->SetDefaultNackingMode((NormObject::NackingMode)nackingMode);
    }
}  // end NormNodeSetNackingMode()

NORM_API_LINKAGE
void NormObjectSetNackingMode(NormObjectHandle objectHandle,
                              NormNackingMode  nackingMode)
{
    NormObject* object = (NormObject*)objectHandle;
    if (object) object->SetNackingMode((NormObject::NackingMode)nackingMode);
}  // end NormObjectSetNackingMode()

NORM_API_LINKAGE
void NormSetDefaultRepairBoundary(NormSessionHandle  sessionHandle,
                                  NormRepairBoundary repairBoundary)
{
    NormSession* session = (NormSession*)sessionHandle;
    if (session)
        session->ReceiverSetDefaultRepairBoundary((NormSenderNode::RepairBoundary)repairBoundary);
}  // end NormSetDefaultRepairBoundary()

NORM_API_LINKAGE
void NormNodeSetRepairBoundary(NormNodeHandle     nodeHandle,
                               NormRepairBoundary repairBoundary)
{
    NormNode* node = (NormNode*)nodeHandle;
    if ((NULL != node) && (NormNode::SENDER == node->GetType()))
    {
        NormSenderNode* sender = static_cast<NormSenderNode*>(node);
        sender->SetRepairBoundary((NormSenderNode::RepairBoundary)repairBoundary);
    }
}  // end NormNodeSetRepairBoundary()


NORM_API_LINKAGE 
void NormSetDefaultRxRobustFactor(NormSessionHandle sessionHandle,
                                  int               robustFactor)
{
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        session->SetRxRobustFactor(robustFactor);
        instance->dispatcher.ResumeThread();
    }
}  // end NormSetDefaultRxRobustFactor()

NORM_API_LINKAGE 
void NormNodeSetRxRobustFactor(NormNodeHandle   nodeHandle,
                               int              robustFactor)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);        
                sender->SetRobustFactor(robustFactor);
            }
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormNodeSetRxRobustFactor()

NORM_API_LINKAGE
bool NormPreallocateRemoteSender(NormSessionHandle  sessionHandle,
                                 unsigned long      bufferSize,
                                 UINT16             segmentSize, 
                                 UINT16             numData, 
                                 UINT16             numParity,
                                 unsigned int       streamBufferSize)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormSession* session = (NormSession*)sessionHandle;
        result = session->PreallocateRemoteSender((unsigned int)bufferSize, segmentSize, numData, numParity, streamBufferSize);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormPreallocateRemoteSender()

NORM_API_LINKAGE
bool NormStreamRead(NormObjectHandle   streamHandle,
                    char*              buffer,
                    unsigned int*      numBytes)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        result = stream->Read(buffer, numBytes);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStreamRead()

NORM_API_LINKAGE
bool NormStreamSeekMsgStart(NormObjectHandle streamHandle)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        unsigned int numBytes = 0;
        result = stream->Read(NULL, &numBytes, true);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormStreamSeekMsgStart()


NORM_API_LINKAGE
UINT32 NormStreamGetReadOffset(NormObjectHandle streamHandle)
{
    NormStreamObject* stream = static_cast<NormStreamObject*>((NormObject*)streamHandle);
    if (stream)
        return stream->GetCurrentReadOffset();
    else
        return 0;
}  // end NormStreamGetReadOffset()

NORM_API_LINKAGE 
unsigned int NormStreamGetBufferUsage(NormObjectHandle streamHandle)
{
    unsigned int usage = 0;
    NormInstance* instance = NormInstance::GetInstanceFromObject(streamHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormStreamObject* stream = 
            static_cast<NormStreamObject*>((NormObject*)streamHandle);
        usage = stream->GetCurrentBufferUsage() ;
        instance->dispatcher.ResumeThread();
    }
    return usage;
}  // end NormStreamGetBufferUsage()


/** NORM Object Functions */

NORM_API_LINKAGE
NormObjectType NormObjectGetType(NormObjectHandle objectHandle)
{
    if (NORM_OBJECT_INVALID != objectHandle)
        return ((NormObjectType)(((NormObject*)objectHandle)->GetType()));
    else
        return NORM_OBJECT_NONE;
}  // end NormObjectGetType()

NORM_API_LINKAGE
bool NormObjectHasInfo(NormObjectHandle objectHandle)
{
    return ((NormObject*)objectHandle)->HasInfo();
}  // end NormObjectHasInfo()

NORM_API_LINKAGE
UINT16 NormObjectGetInfoLength(NormObjectHandle objectHandle)
{
    return ((NormObject*)objectHandle)->GetInfoLength();
}  // end NormObjectGetInfoLength()

NORM_API_LINKAGE
UINT16 NormObjectGetInfo(NormObjectHandle objectHandle,
                         char*            buffer,
                         UINT16           bufferLen)
{
    UINT16 result = 0;
    if (NORM_OBJECT_INVALID != objectHandle)
    {
        NormObject* object =  (NormObject*)objectHandle;
        if (object->HaveInfo())
        {
            result = object->GetInfoLength();
            if (result < bufferLen) 
                bufferLen = result;
            if (buffer)             
                memcpy(buffer, object->GetInfo(), bufferLen);
        }  
    }
    return result;
}  // end NormObjectGetInfo()

NORM_API_LINKAGE
NormSize NormObjectGetSize(NormObjectHandle objectHandle)
{
    return ((NormSize)((NormObject*)objectHandle)->GetSize().GetOffset());
}  // end NormObjectGetSize()

NORM_API_LINKAGE
NormSize NormObjectGetBytesPending(NormObjectHandle objectHandle)
{
    NormSize bytesPending = 0;
    if (NORM_OBJECT_INVALID != objectHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromObject(objectHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            bytesPending = ((NormSize)((NormObject*)objectHandle)->GetBytesPending().GetOffset());
            instance->dispatcher.ResumeThread();
        }
    }
    return bytesPending;
}  // end NormObjectGetBytesPending()

NORM_API_LINKAGE
void NormObjectCancel(NormObjectHandle objectHandle)
{
    if (NORM_OBJECT_INVALID != objectHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromObject(objectHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormObject* obj = (NormObject*)objectHandle;
            NormSenderNode* sender = obj->GetSender();
            if (sender)
                sender->DeleteObject(obj); 
            else
                obj->GetSession().DeleteTxObject(obj, false);
            instance->PurgeObjectNotifications(objectHandle);
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormObjectCancel()

NORM_API_LINKAGE
void NormObjectSetUserData(NormObjectHandle objectHandle, const void* userData)
{
    NormInstance* instance = NormInstance::GetInstanceFromObject(objectHandle);
    if (instance)
    {
        if (instance->dispatcher.SuspendThread())
        {    
            ((NormObject*)objectHandle)->SetUserData(userData);
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormObjectSetUserData()

NORM_API_LINKAGE
const void* NormObjectGetUserData(NormObjectHandle objectHandle)
{
    return (((NormObject*)objectHandle)->GetUserData());
}  // end NormNormObjectGetUserData()


NORM_API_LINKAGE
void NormObjectRetain(NormObjectHandle objectHandle)
{
    if (NORM_OBJECT_INVALID != objectHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromObject(objectHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            ((NormObject*)objectHandle)->Retain();
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormRetainObject()

NORM_API_LINKAGE
void NormObjectRelease(NormObjectHandle objectHandle)
{
    // (TBD) we could maintain separate "app_retain" and "interval_retain"
    // counts to prevent bad apps from messing up NORM interval code ???
    if (NORM_OBJECT_INVALID != objectHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromObject(objectHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            ((NormObject*)objectHandle)->Release();
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormObjectRelease()

NORM_API_LINKAGE
bool NormFileGetName(NormObjectHandle   fileHandle,
                     char*              nameBuffer,
                     unsigned int       bufferLen)
{
    bool result = false;
    if (NORM_OBJECT_INVALID != fileHandle)
    {
        // (TBD) verify "fileHandle" is a NORM_FILE ?>??
        NormFileObject* file = 
            static_cast<NormFileObject*>((NormObject*)fileHandle);
        bufferLen = (bufferLen < PATH_MAX) ? bufferLen : PATH_MAX;
        strncpy(nameBuffer, file->GetPath(), bufferLen);
        nameBuffer[bufferLen - 1] = '\0';  // (TBD) should we always do this
        result = true;
    }
    return result;
}  // end NormFileGetName()

NORM_API_LINKAGE
bool NormFileRename(NormObjectHandle   fileHandle,
                    const char*        fileName)
{
    bool result = false;
    NormInstance* instance = NormInstance::GetInstanceFromObject(fileHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        // (TBD) verify "fileHandle" is a NORM_FILE ?>??
        NormFileObject* file = 
            static_cast<NormFileObject*>((NormObject*)fileHandle);
        result = file->Rename(fileName);
        instance->dispatcher.ResumeThread();
    }
    return result;
}  // end NormFileRename()

NORM_API_LINKAGE
const char* NormDataAccessData(NormObjectHandle dataHandle) 
{
    NormDataObject* dataObj = 
            static_cast<NormDataObject*>((NormObject*)dataHandle);
    return dataObj->GetData();
}  // end NormDataAccessData()

NORM_API_LINKAGE
char* NormDataDetachData(NormObjectHandle dataHandle) 
{
    char* ptr = NULL;
    NormInstance* instance = NormInstance::GetInstanceFromObject(dataHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        NormDataObject* dataObj = static_cast<NormDataObject*>((NormObject*)dataHandle);
        ptr = dataObj->DetachData();
        instance->dispatcher.ResumeThread();
    }
    return ptr;
}  // end NormDataDetachData()

NORM_API_LINKAGE 
char* NormAlloc(size_t numBytes)
{
    return new char[numBytes];
}  // end NormAlloc()

NORM_API_LINKAGE 
void NormFree(char* dataPtr)
{
    if (NULL != dataPtr)
        delete[] dataPtr;
}  // end NormFree()

NORM_API_LINKAGE
NormNodeHandle NormObjectGetSender(NormObjectHandle objectHandle)
{
    return (NormNodeHandle)(((NormObject*)objectHandle)->GetSender());
}  // end NormObjectGetSender()


/** NORM Node Functions */

NORM_API_LINKAGE
NormNodeId NormNodeGetId(NormNodeHandle nodeHandle)
{
    NormNode* node = (NormNode*)nodeHandle;
    if (NULL != node) 
        return node->GetId();
    else
        return NORM_NODE_NONE;
}  // end NormNodeGetId()

NORM_API_LINKAGE
bool NormNodeGetAddress(NormNodeHandle  nodeHandle,
                        char*           addrBuffer, 
                        unsigned int*   bufferLen,
                        UINT16*         port)
{
    bool result = false;
    if (NORM_NODE_INVALID != nodeHandle)
    {
        //NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        //if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            const ProtoAddress& nodeAddr = node->GetAddress();
            unsigned int addrLen = nodeAddr.GetLength();
            if (addrBuffer && bufferLen && (addrLen <= *bufferLen))
            {
                memcpy(addrBuffer, nodeAddr.GetRawHostAddress(), addrLen);
                result = true;
            } 
            else if (NULL == addrBuffer)
            {
                result = true; // just a query for addrLen and/or port
            }      
            if (bufferLen) *bufferLen = addrLen;
            if (port) *port = nodeAddr.GetPort();
            //instance->dispatcher.ResumeThread();  
        }
    }
    return result;
}  // end NormNodeGetAddress()

NORM_API_LINKAGE 
void NormNodeSetUserData(NormNodeHandle nodeHandle, const void* userData)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormNode* node = (NormNode*)nodeHandle;
        return node->SetUserData(userData);
    }
}

NORM_API_LINKAGE 
const void* NormNodeGetUserData(NormNodeHandle nodeHandle)
{
    NormNode* node = (NormNode*)nodeHandle;
    if (NULL != node) 
        return node->GetUserData();
    else
        return NULL;
}  // end NormNodeGetUserData()

NORM_API_LINKAGE
double NormNodeGetGrtt(NormNodeHandle nodeHandle)
{
    NormNode* node = (NormNode*)nodeHandle;
    if ((NULL != node) && (NormNode::SENDER == node->GetType()))
    {
        NormSenderNode* sender = static_cast<NormSenderNode*>(node);
        sender->ResetGrttNotification();
        return sender->GetGrttEstimate();
    }
    else
    {
        return -1.0;
    }
}  // end NormNodeGetGrtt()

NORM_API_LINKAGE
bool NormNodeGetCommand(NormNodeHandle nodeHandle,
                        char*          cmdBuffer,
                        unsigned int*  cmdLength)
{
    bool result = false;
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);
                result = sender->ReadNextCmd(cmdBuffer, cmdLength);
            }
            instance->dispatcher.ResumeThread();  
        }
    }
    return result;
}  // end NormNodeGetCommand()

NORM_API_LINKAGE
bool NormNodeSendAckEx(NormNodeHandle nodeHandle,
                       const char*    buffer,
                       unsigned int   numBytes)
{
    bool result = false;
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);
                result = sender->SendAckEx(buffer, numBytes);
            }
            instance->dispatcher.ResumeThread();  
        }
    }
    return result;
}  // end NormNodeSendAckEx()

NORM_API_LINKAGE
bool NormNodeGetWatermarkEx(NormNodeHandle nodeHandle,
                            char*          buffer,
                            unsigned int*  buflen)
{
    bool result = false;
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);
                result = sender->GetWatermarkEx(buffer, buflen);
            }
            instance->dispatcher.ResumeThread();  
        }
    }
    return result;
}  // end NormNodeGetWatermarkEx()

NORM_API_LINKAGE
void NormNodeFreeBuffers(NormNodeHandle nodeHandle)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);
                sender->FreeBuffers();
                // Since this results in aborted objects, should we purge those object notifications?
                // or let the be delivered since the app may have associate state
            }
            instance->dispatcher.ResumeThread(); 
        }
    }
}  // end NormNodeFreeBuffers()

NORM_API_LINKAGE
void NormNodeDelete(NormNodeHandle nodeHandle)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            NormNode* node = (NormNode*)nodeHandle;
            if (NormNode::SENDER == node->GetType())
            {
                NormSenderNode* sender = static_cast<NormSenderNode*>(node);
                sender->GetSession().DeleteRemoteSender(*sender);
            }
            // else if NormNode::ACKER, should we remove from acking node list???
            instance->PurgeNodeNotifications(nodeHandle);
            instance->dispatcher.ResumeThread(); 
        }
    }
}  // end NormNodeDelete()

NORM_API_LINKAGE
void NormNodeRetain(NormNodeHandle nodeHandle)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            ((NormNode*)nodeHandle)->Retain();
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormNodeRetain()

NORM_API_LINKAGE
void NormNodeRelease(NormNodeHandle nodeHandle)
{
    if (NORM_NODE_INVALID != nodeHandle)
    {
        NormInstance* instance = NormInstance::GetInstanceFromNode(nodeHandle);
        if (instance && instance->dispatcher.SuspendThread())
        {
            ((NormNode*)nodeHandle)->Release();
            instance->dispatcher.ResumeThread();
        }
    }
}  // end NormNodeRelease()

// (TBD) Some stream i/o performance improvement can be realized
//       if the option to make "NormWriteStream()" and 
//       "NormReadStream()" _blocking_ calls is implemented.
//        Right now, the stream read/write are non-blocking
//        so applications should use "NormGetNextEvent()" to
//        know when to read or write ... This results in the
//        underlying NORM thread to be suspended/resumed _twice_
//        per read or write ... It would be more efficient to
//        "suspend" the NORM thread while the application
//        processes all pending events and _then_ "resume" the
//        NORM thread ... an approach to this would be enable
//        the app to install an event handler callback and dispatch
//        events with a "NormDispatchEvents()" call ...
//        (Update: I've improved the way the NORM thread suspend/resume
//         is done so that this current approach is not very costly)
//

// Not sure why this function exists.  It just counts the number
// of RX_OBJECT_COMPLETED events currently in notification queue
// which is a temporary and transitory thing???
NORM_API_LINKAGE
UINT32 NormCountCompletedObjects(NormSessionHandle sessionHandle)
{
    UINT32 result = 0;
    NormSession* session = (NormSession*)sessionHandle;
	NormInstance* instance = NormInstance::GetInstanceFromSession(sessionHandle);
    if (instance && instance->dispatcher.SuspendThread())
    {
        result = instance->CountCompletedObjects(session);
        instance->dispatcher.ResumeThread();
    }
	return result;
}  // end NormCountCompletedObjects()