File: queue_manager.cc

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

#include "config.h"
#ifndef NO_QUEUE_MANAGER

#include <fstream.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <grp.h>
#include <string>
#include <map>
#include <list>
#include <vector>
#include <iterator>
#include <algorithm>
#include "queue_define.h"

/* VARIOUS STRUCTURES */

// packet used to keep track of the license(s) that we've confiscated
// from a low-priority running job
struct conflic_packet
{
   int job_pid;  // pid of the forked off queue daemon
   vector<string> license_vector;
};

// used to keep track of which queue the job is in and which host it is running on
struct task_packet
{
   int uid;  // user id of the job
   string queue_type;  // type of queue the job is in
   string hostname;  // host that job is running on
};

// contains all the information that we need for the communication mechanism
struct sockfd5_commun
{
   int counter;  // number of times that we've received the same information from the queue daemon in a row
   int startup;  // when the queue_manager starts up and hears from this queue daemon for the first time
   struct timeval time;  // stores the time
};

// contains all the information that we need about each job
struct job_info
{
   string host_running;  // host that job is running on
   string status;  // job is either running, waiting, or sleeping
   int job_pid;
   int batch_pid;  // child process id, so that we can do a waitpid() on it
   int sockfd;  // need to save socket connection if in interac. mode and no hosts
   string job_id;  // this is a unique id that identifies the job
   vector<string> license_vector;
   struct info_packet packet;
   map<string, conflic_packet> conf_license;  // contains confiscated license(s) info.
   list<string> avail_license_erase;  // pertains to confiscated license(s)
   int confiscated;  // tells us if this job has licenses confiscated or not
   vector<string> vec_arge;  // user's environment (for batch jobs)
};

/* GLOBAL VARIABLES */

// create available host names and available licenses data structures 
list<string> avail_hosts;   
list<string> valid_hosts;
map<string, int> avail_licenses;   
map<string, string> license_files;

// create the "queues"
map<string, job_info> high_running;
map<string, job_info> low_running;
map<string, job_info> intermediate; 
list<job_info> high_waiting;
list<job_info> low_waiting;

// a data structure to keep track of which queue the job belongs to and which host
// it is running on (used for book-keeping purposes for the task_usercontrol and 
// task_manager processes)
map<string, task_packet> job_find;    

// a list of defective servers (note: a server is defective if either its queue daemon or 
// its task_manager is down)
list<string> defective_hosts;

// a list of job messages from users that we can't process yet
list<sockfd4_packet> job_messages;

// a list of servers running the queue daemons for the communication mechanism
map<string, sockfd5_commun> communicate;

// host to run job on
char assigned_host[MAXHOSTNAMELEN];  

// counter used to ensure that the procedures after the "select" timeout will be
// executed (since it's possible that these procedures can starve without this counter)
int starve_counter = 0;

/* FUNCTIONS */

int hlavail_i(job_info temp_job, int new_sockfd, list<string>::iterator it_find );
int hlavail_b(job_info temp_job, int waitq, list<string>::iterator it_find );
int hl_unavail(job_info temp_job, int new_sockfd, int waitq, list<string>::iterator it_find);
int tm_connect(string hostname, struct tm_packet tmpacket);
int task_control(struct sockfd4_packet packet, map<string, task_packet>::iterator it_jobfind);
int defective_server(string server);
int unsuspend_jobs(map<string, int> unsuspend_servers);
int check_wait();
int check_queued();
int check_jobmsg();
int create_newjob(struct sockfd3_packet packet);
int move_job(map<string, job_info>::iterator it_find, struct sockfd3_packet packet);
void sigpipe_handler(int);
int lmleft (const char* given_licfile, const char* given_feature);

/* FILES */

#ifdef DEBUG
ofstream fout_debug;
int display_debug();
void hdisplay_debug(job_info);
#endif

// file that contains information about the status of jobs
FILE *fout_status;
int display_status();
void hdisplay_status(job_info);

// "temp" file is used to output and read in the pid values of batch jobs, so that if 
// we need to manually kill the job we can (otherwise, we run into the problem of 
// waiting forever for the child process to terminate)
ifstream fin;

int main()
{
   /* (1) Initialize the data structures. */

   // initialize: read the valid host names from the file into valid_hosts 
   {
	string temp;
	ifstream fin(AVAILHOSTS);

	if ( fin.bad() )
	{
	   cerr << "Can't open " << AVAILHOSTS << " ";
	   perror("for reading");
	   return -1;
 	}

	while ( fin >> temp )
  	{
	   valid_hosts.push_back(temp);
   	}

	fin.close();
   }

   // initialize: read the available licenses from the file into avail_licenses
   {
	string temp, i, licensefile;
	ifstream fin(AVAILLICENSES);

	if ( fin.bad() )
	{
	   cerr << "Can't open " << AVAILLICENSES << " ";
	   perror("for reading");
	   return -1;
 	}

	while ( fin >> temp >> i >> licensefile)
	{
	   // check if the license file and the license feature are valid
	   if ( lmleft(licensefile.c_str(), temp.c_str()) < 0 )
	   {
	      cerr << "Invalid license file or license feature" << endl;
	      return -1;
	   }

	   avail_licenses.insert( map<string, int>::
					value_type(temp, atoi(i.c_str())) );
	   license_files.insert( map<string, string>::value_type(temp, licensefile) );
	}

	fin.close();
   }

   // initialize: set up the communication data structure
   {
   	// get the current time
	struct timeval time;
	gettimeofday(&time, NULL);

	// temporary sockfd5_commun packet
	struct sockfd5_commun packet;
	packet.counter = 0;
	packet.startup = 1;
	packet.time = time;

	list<string>::iterator it_begin = valid_hosts.begin(), it_end = valid_hosts.end();
	while (it_begin != it_end)
	{
	   communicate.insert( map<string, sockfd5_commun>::value_type(*it_begin, packet) );
	   ++it_begin;
	}
   }

   /* (2) Open up four sockets to accept connections on: 
	  socket2 is from  queue.c for message bit, 
	  socket3 is from queued.c, socket4 is from task_usercontrol.cc,
	  socket5 is from queued.c for communication */

   int sockfd2, sockfd3, sockfd4, sockfd5; 
   struct sockaddr_in serv_addr2, serv_addr3, serv_addr4, serv_addr5, cli_addr;
   unsigned int clilen = sizeof(cli_addr);

   // Bind our local addresses so that the clients can send to us 
   serv_addr2.sin_family = AF_INET;
   serv_addr2.sin_port = htons(PORTNUM2);
   serv_addr2.sin_addr.s_addr = INADDR_ANY;

   serv_addr3.sin_family = AF_INET;
   serv_addr3.sin_port = htons(PORTNUM3);
   serv_addr3.sin_addr.s_addr = INADDR_ANY;

   serv_addr4.sin_family = AF_INET;
   serv_addr4.sin_port = htons(PORTNUM4);
   serv_addr4.sin_addr.s_addr = INADDR_ANY;

   serv_addr5.sin_family = AF_INET;
   serv_addr5.sin_port = htons(PORTNUM5);
   serv_addr5.sin_addr.s_addr = INADDR_ANY;

   // open up three TCP sockets
   if ( (sockfd2 = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
   {
   	perror("Error on second socket()"); 
	return -1;
   }

   if ( (sockfd3 = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
   {
   	perror("Error on third socket()");
	return -1;
   }

   if ( (sockfd4 = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
   {
   	perror("Error on fourth socket()");
	return -1;
   }

   if ( (sockfd5 = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
   {
   	perror("Error on fifth socket()");
	return -1;
   }

   // set socket options for TCP sockets 
   int sendbuff = 16384;

   if ( setsockopt(sockfd2, SOL_SOCKET, SO_REUSEADDR,
   	(char *) &sendbuff, sizeof(sendbuff)) < 0 )
   {
   	perror("Error on second TCP setsock option");
	return -1;
   }

   if ( setsockopt(sockfd3, SOL_SOCKET, SO_REUSEADDR,
   	(char *) &sendbuff, sizeof(sendbuff)) < 0 )
   {
   	perror("Error on third TCP setsock option");
	return -1;
   }

   if ( setsockopt(sockfd4, SOL_SOCKET, SO_REUSEADDR,
   	(char *) &sendbuff, sizeof(sendbuff)) < 0 )
   {
   	perror("Error on fourth TCP setsock option");
	return -1;
   }

   if ( setsockopt(sockfd5, SOL_SOCKET, SO_REUSEADDR,
   	(char *) &sendbuff, sizeof(sendbuff)) < 0 )
   {
   	perror("Error on fifth TCP setsock option");
	return -1;
   }

   // do bind()'s on all five sockets  
   if ( bind(sockfd2, (struct sockaddr *) &serv_addr2, sizeof(serv_addr2)) < 0 )
   {
   	perror("Error on second bind()");
	return -1;
   }

   if ( bind(sockfd3, (struct sockaddr *) &serv_addr3, sizeof(serv_addr3)) < 0 )
   {
   	perror("Error on third bind()");
	return -1;
   }

   if ( bind(sockfd4, (struct sockaddr *) &serv_addr4, sizeof(serv_addr4)) < 0 )
   {
   	perror("Error on fourth bind()");
	return -1;
   }

   if ( bind(sockfd5, (struct sockaddr *) &serv_addr5, sizeof(serv_addr5)) < 0 )
   {
   	perror("Error on fifth bind()");
	return -1;
   }

   // do listen()'s to indicate that server is ready to receive connections 
   if ( listen(sockfd2, QUEUELEN) < 0 )
   {
   	perror("Error on second listen()");
	return -1;
   }

   if ( listen(sockfd3, QUEUELEN) < 0 )
   {
   	perror("Error on third listen()");
	return -1;
   }

   if ( listen(sockfd4, QUEUELEN) < 0 )
   {
   	perror("Error on fourth listen()");
	return -1;
   }

   if ( listen(sockfd5, QUEUELEN) < 0 )
   {
   	perror("Error on fith listen()");
	return -1;
   }

   /* (3) Now just wait for any connections */

   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   for(;;)
   {
	fd_set rfds;
	FD_ZERO(&rfds);
	FD_SET(sockfd2, &rfds);
	FD_SET(sockfd3, &rfds);
	FD_SET(sockfd4, &rfds);
	FD_SET(sockfd5, &rfds);

	struct timeval timer;
	timer.tv_sec = SLEEPTIME;
	timer.tv_usec = 0;

	// set the timer 
	if ( select(32, &rfds, NULL, NULL, &timer) < 0 )
	{
	   perror("Error on select()");
	   return -1;
	}

	// (3.1) Are there any connections from sockfd2?
	if ( FD_ISSET(sockfd2, &rfds) )
	{
	   struct job_info temp_job;  // job_info element to insert into some queue
	   struct task_packet task_job;  // element to insert into job_find
	   string user_jobid;  // the job id (must be unique) 
	   int new_sockfd;
	   int flag1 = 0;  // bit is on if user entered invalid hosts or licenses
	   int flag2 = 0;  // bit is on if licenses are not available
	   int flag3 = 0;  // bit is on if user's onlyhost is not available
	   int discard_job = 0;  // initialize variable to 0 

	   // Accept a connection; fills in client address information 
   	   if ( (new_sockfd = accept(sockfd2, (struct sockaddr *) &cli_addr,
  			&clilen)) < 0 )
   	   {
		perror("Error on accept() for sockfd2");
		return -1;
	   }

	   #ifdef DEBUG
	   cout << "Connection from: " << inet_ntoa(cli_addr.sin_addr) << endl;
	   #endif

	   // (a) get the packet structure first
   	   struct info_packet packet;
   	   if ( recv(new_sockfd, &packet, sizeof(packet), 0) == -1 )
   	   {
		perror("Error on receiving packet structure");
		close(new_sockfd);
		continue;
   	   }

	   int for_counter = 0;  // prevents infinite looping within the for loops
   	   // (b) next, get the list of licenses
   	   for(;;)
   	   {
		char buffer[MAXLICENSELEN];
		if ( recv(new_sockfd, buffer, sizeof(buffer), 0) == -1 )
		{
	   	   perror("Error on receiving list of licenses");
		   discard_job = 1;
		   break;
		}

		if ( !strstr(buffer, "EOF") )
	  	   temp_job.license_vector.push_back(buffer);
		else 
	   	   break;

	    	for_counter++;
		if (for_counter == MAXLICENSES) 
		   { discard_job = 1; cerr << "License for_counter" << endl; break; }
   	   }

	   #ifdef DEBUG
	   cout << "After getting licenses" << endl;
	   #endif

	   // (b.1) finally, if user specifies batch mode, need to get user's
	   // environment
	   if ( !strcasecmp(packet.mode, "batch") )
	   {
	      // (do later)  need to set a timer so that if we don't receive
	      // the user's environment within so many seconds, will discard
	      // job; this prevents us from looping forever

	      // store each environment string in temp_job's vector
	      for(;;)
	      {
	         char data[MAXSTRINGLEN];
		 if ( recv(new_sockfd, data, MAXSTRINGLEN, 0) < 0 )
		 {
		    perror("Error on receiving user's environment");
		    discard_job = 1;
		    break;
		 }

		 if ( !strstr(data, "EOF") )
		    temp_job.vec_arge.push_back(data);
		 else
		    break;

	      	 for_counter++;
		 if (for_counter == MAXENVIRON) 
		    { discard_job = 1; cerr << "Environment for_counter" << endl; break; }
	      }
	   }

	   // job needs to be discarded?
	   if ( discard_job ) 
	   {
		close(new_sockfd);  // closes off the socket connection
		continue;
	   }

	   #ifdef DEBUG
	   cout << "After getting environment" << endl;
	   #endif

	   // store the info packet in temp_job element
	   temp_job.packet = packet;
	   temp_job.confiscated = 0;  // initialize bit to 0
	   list<string>::iterator host_iter;  // a hack (fix later)

	   // (c) check if the user-entered hosts and licenses are valid
	   {
		map<string, int>::iterator license_iter;

		// (c1) check for vaild hosts first
		if ( strcasecmp(temp_job.packet.onlyhost, "") )
	 	{
		   host_iter = find(valid_hosts.begin(), valid_hosts.end(),
					temp_job.packet.onlyhost);

		   if ( host_iter == valid_hosts.end() )
			flag1 = 1;	
		   else
		   {    // now check if this "onlyhost" is available	
			host_iter = find(avail_hosts.begin(), avail_hosts.end(), 
						temp_job.packet.onlyhost);

			if ( host_iter == avail_hosts.end() )
			   flag3 = 1;		
			else
			   strcpy(assigned_host, host_iter->c_str());
		   }
		}	
		else if ( strcasecmp(temp_job.packet.prefhost, "") )
		{
		   host_iter = find(valid_hosts.begin(), valid_hosts.end(),
					temp_job.packet.prefhost);

		   if ( host_iter == valid_hosts.end() )
			flag1 = 1;		 
		}

		// (c2) now check for valid licenses
   		for (int i = 0; i < temp_job.license_vector.size(); i++)
		{
		   license_iter = avail_licenses.find(temp_job.license_vector[i]);

		   if ( license_iter == avail_licenses.end() )
		  	flag1 = 1;
		   else if ( license_iter->second <= 0 )
		   {	// this license is currently unavailable
			flag2 = 1;
		   }
		}

		// valid hosts and licenses?
	 	if ( flag1 == 1 )
		{
		   // invalid; send "-1" error message back to queue client
		   char buffer[MAXHOSTNAMELEN] = "-1";
   		   if ( send(new_sockfd, buffer, sizeof(buffer), 0) < 0 )
   		   {
			perror("Error on sending to queue client");
   		   }
	  	   
		   close(new_sockfd);
		   continue;	
		}		
   	   } 

	   // (d) create the job id (must be unique)
	   for(;;)
	   {
		// generate a random number
		long int rand_num = random() % MAXJOBIDMOD;

		// job_id = uid + random number
		char uid[10]; char rnum[30];
		sprintf(uid, "%d%s", temp_job.packet.user_id, "_");
		sprintf(rnum, "%ld", rand_num);

		// set user_jobid 
		user_jobid = uid;
		user_jobid = user_jobid + rnum;

	 	// set temp_job's job_id to user_jobid
		temp_job.job_id = user_jobid;

		// check to make sure that job id does not exist already
		map<string, task_packet>::iterator it_find = job_find.find(temp_job.job_id);
		if ( it_find == job_find.end() )
		   break;
	   }

	   // (e) if in batch mode, then send the job_id back to queue client and 
	   // close off socket connection
	   if ( !strcasecmp(temp_job.packet.mode, "batch") )
	   { 
	   	char buffer[MAXHOSTNAMELEN];
		strcpy(buffer, temp_job.job_id.c_str());
   		if ( send(new_sockfd, buffer, sizeof(buffer), 0) < 0 )
   		{
		   perror("Error on sending ack to queue client");
   		}
		close(new_sockfd);
	   }

	   // (f) put the job in the appropriate waiting queue, then call the
	   // check_wait() function to see if we can run any jobs

	   // if in interactive mode, save the socket descriptor so that
	   // we can connect back to this process later
	   if ( !strcasecmp(temp_job.packet.mode, "interactive") )
	   	temp_job.sockfd = new_sockfd;

	   // save other information about the job in temp_job
	   temp_job.host_running = "";
	   temp_job.status = "waiting";

	   // store the job in the appropriate queue
	   if ( !strcasecmp(temp_job.packet.priority, "high") )
	   {
	   	high_waiting.push_back(temp_job);
		task_job.queue_type = "high_waiting";  // get the queue_type of task_job
	   }
	   else
	   {
	   	low_waiting.push_back(temp_job);		
	   	task_job.queue_type = "low_waiting";  // get the queue_type of task_job
	   }

	   // insert task_job into job_find
	   task_job.uid = temp_job.packet.user_id;
	   job_find.insert( map<string, task_packet>::value_type(user_jobid, task_job) );

	   // call check_wait()
	   check_wait();

	   // check if we need to execute the procedures after the "select" timeout 
	   ++starve_counter;
	   if ( starve_counter == MAXSTARVECOUNTER )
	   {
	      starve_counter = 0;  // reset the variable
	      check_jobmsg();
	      display_status();
	      waitpid(-1, NULL, WNOHANG);  // see if there are any zombie processes we need to bury

	      #ifdef DEBUG
	      display_debug();
	      #endif
	   }

	   continue;  // continue checking for any connections

	} // closes FD_ISSET

	// (3.2) Are there any connections from sockfd3?
	if ( FD_ISSET(sockfd3, &rfds) )
	{
	   int new_sockfd;

	   // Accept a connection; fills in client address information.
	   if ( (new_sockfd = accept(sockfd3, (struct sockaddr *) &cli_addr,
			&clilen)) < 0 )
	   {
		perror("Error on accept() for sockfd3");
		return -1;
	   }

	   #ifdef DEBUG
	   cout << "Connection from: " << inet_ntoa(cli_addr.sin_addr) << endl;
	   #endif

	   // (a) get the message bit first to determine what kind of message this is
	   char msg_bit[2];
	   if ( recv(new_sockfd, msg_bit, sizeof(msg_bit), 0) == -1 )
	   {
		perror("Error on receiving message bit");
		continue;
	   }
	   
	   // next, get the packet 
	   struct sockfd3_packet packet; 
	   if ( recv(new_sockfd, &packet, sizeof(packet), 0) == -1 )
	   {
		perror("Error on receving packet within (3.2)");
		continue;
	   }

	   // close off the socket connection
	   close(new_sockfd); 

	   #ifdef DEBUG
	   cout << "message bit: " << msg_bit << endl;
	   cout << "packet: " << packet.hostname << " " << packet.job_pid << " " 
		<< packet.user_id << endl;
	   #endif

	   // (b) process the information according to its message type

	   if ( !strcasecmp(msg_bit, "1") )  
	   {
	   	// (b1) job is running, so move the job element from the intermediate queue
	   	// to the running queue

	   	map<string, job_info>::iterator it_find;
		it_find = intermediate.find(packet.hostname);

		// make sure that the job is in the intermediate queue before deleting anything 
		// (otherwise we'll get a bunch of segmentation faults)
		if ( it_find != intermediate.end() )
		   move_job(it_find, packet);
	   }
	   else if ( !strcasecmp(msg_bit, "2") )  
	   {
		// (b2) job has terminated: so remove this job element from the running queue,
		// update the avail_hosts and avail_licenses; if the job was in batch mode,
		// have to do a waitpid on this child to bury this zombie process

		int batchpid = -1;
	   	map<string, job_info>::iterator it_find;

		// check which queue this job element belongs to and delete it
		if ((it_find = intermediate.find(packet.hostname)) != intermediate.end())
		{
		   // need to bury zombie process?
		   if ( !strcasecmp(it_find->second.packet.mode, "batch") )
		      batchpid = it_find->second.batch_pid;

		   // update avail_hosts and avail_licenses
		   avail_hosts.push_back(packet.hostname);

		   for ( int i=0; i < it_find->second.license_vector.size(); i++ )
		   {
			map<string, int>::iterator license_iter;
			license_iter = avail_licenses.find(
						it_find->second.license_vector[i]);
			license_iter->second = license_iter->second + 1;
		   }

		   // delete element off of job_find as well
		   map<string, task_packet>::iterator it_jobfind;
		   it_jobfind = job_find.find(it_find->second.job_id);
		   job_find.erase(it_jobfind); 

		   intermediate.erase(it_find);
		}
		else if ((it_find = high_running.find(packet.hostname)) != high_running.end())
		{
		   // need to bury zombie process?
		   if ( !strcasecmp(it_find->second.packet.mode, "batch") )
		      batchpid = it_find->second.batch_pid;

		   // update avail_hosts 
		   avail_hosts.push_back(packet.hostname);

		   // check if we have confiscated any licenses
		   if ( !it_find->second.conf_license.empty() )
		   {
			// update avail_licenses if avail_license_erase is not empty
			list<string>::iterator 
				it_begin = it_find->second.avail_license_erase.begin(),
				it_end = it_find->second.avail_license_erase.end();

			while ( it_begin != it_end )
			{
			   map<string, int>::iterator license_iter;
			   license_iter = avail_licenses.find(*it_begin);
			   license_iter->second = license_iter->second + 1;
			   ++it_begin;
			}

			// now open up a connection to all the hosts in 
			// conf_license to "unsuspend" the suspended jobs
		        map<string, conflic_packet>::iterator 
					itb = it_find->second.conf_license.begin(),
					ite = it_find->second.conf_license.end();

			while ( itb != ite )
			{
			   struct tm_packet tmpacket;  // packet to send to task_manager
			   tmpacket.job_pid = itb->second.job_pid; 
			   strcpy(tmpacket.message, "unsuspend");

			   // call tm_connect function
			   if ( tm_connect(itb->first, tmpacket) == 0 )
			   {
			      // update the status of the confiscated license job
			      map<string, job_info>::iterator it_jfind =
							low_running.find(itb->first);
			      it_jfind->second.status = "running";
			      it_jfind->second.confiscated = 0;  // set bit back to 0
			   }

			   ++itb;
			} 
		   } 
		   else
		   {
		      #ifdef DEBUG 
		      cout << "No confiscated licenses" << endl;
		      #endif

		      // update avail_licenses
		      for ( int i=0; i < it_find->second.license_vector.size(); i++ )
		      {
			map<string, int>::iterator license_iter;
			license_iter = avail_licenses.find(
					 	it_find->second.license_vector[i]);
			license_iter->second = license_iter->second + 1;
		      }
		   }

		   // delete element off of job_find as well
		   map<string, task_packet>::iterator it_jobfind;
		   it_jobfind = job_find.find(it_find->second.job_id);
		   job_find.erase(it_jobfind); 

		   high_running.erase(it_find);
		}
		else if ((it_find = low_running.find(packet.hostname)) != low_running.end())
		{
		   // need to bury zombie process?
		   if ( !strcasecmp(it_find->second.packet.mode, "batch") )
		      batchpid = it_find->second.batch_pid;

		   // update avail_hosts and avail_licenses
		   avail_hosts.push_back(packet.hostname);

		   for ( int i=0; i < it_find->second.license_vector.size(); i++ )
		   {
			map<string, int>::iterator license_iter;
			license_iter = avail_licenses.find(
						it_find->second.license_vector[i]);
			license_iter->second = license_iter->second + 1;
		   }

		   // delete element off of job_find as well
		   map<string, task_packet>::iterator it_jobfind;
		   it_jobfind = job_find.find(it_find->second.job_id);
		   job_find.erase(it_jobfind); 

		   low_running.erase(it_find);
		}

		// need to bury zombie process?
		if ( batchpid != -1 )
		{
		   	// sometimes we have to manually kill off the forked off
		   	// queue_manager (better to do this way; otherwise,
		   	// waitpid will block forever waiting for the child to die)

		 	// the command to get the "sh..." pid first
			char pidcmd[100];
			strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
			sprintf(pidcmd, "%s %d %s", pidcmd, batchpid,
						"| awk '{print $3}' | grep -v");
			sprintf(pidcmd, "%s %d %s %s", pidcmd, batchpid, ">", TEMPFILE); 

			#ifdef DEBUG
			cout << pidcmd << endl;
			#endif

			if ( system(pidcmd) < 0 )
			   perror("Error on pidcmd system()");
			else
			{
   			   // now read in the value of the "sh" pid
   			   int sh_pid = -1;
   			   fin.open(TEMPFILE);

			   if ( !fin.bad() )
			   {
   			      fin >> sh_pid;
   			      fin.close();

   			      if ( sh_pid != -1 )
   			      {
			         char pidcmd[100];
			         strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
			         sprintf(pidcmd, "%s %d %s", pidcmd, sh_pid,
					"| awk '{print $3}' | grep -v");
			         sprintf(pidcmd, "%s %d %s %s", pidcmd, sh_pid, ">", TEMPFILE);

        		         if ( system(pidcmd) < 0 )
	   			   perror("Error on pidcmd system()");
			         else
			         {
			            // now get the actual pid that we need to kill the job
			            int kill_pid = -1;
			            fin.open(TEMPFILE);

				    if ( !fin.bad() )
				    {
			               fin >> kill_pid;
			               fin.close();

			               #ifdef DEBUG
			               cout << "kill_pid: " << kill_pid << endl;
			               #endif
	
			               // send the process the kill signal
				       if (kill_pid > 0)
				       { 
		  	                  kill( kill_pid, SIGTERM );  // try SIGTERM first
		  	                  kill( kill_pid, SIGKILL );
				       }
				    }
			         }
   			      } // closes off "if (sh_pid..."
			   }
			}

			// now bury this child	
			waitpid(batchpid, NULL, WNOHANG);

			#ifdef DEBUG
			cout << "after waiting on child process" << endl;
			#endif
		}

		// (c) Need to remove licenses?  (Ask Scott about this.) 
	   }

	   // check if we need to execute the procedures after the "select" timeout 
	   ++starve_counter;
	   if ( starve_counter == MAXSTARVECOUNTER )
	   {
	      starve_counter = 0;  // reset the variable
	      check_wait();
	      check_jobmsg();
	      display_status();
	      waitpid(-1, NULL, WNOHANG);  // see if there are any zombie processes we need to bury

	      #ifdef DEBUG
	      display_debug();
	      #endif
	   }

	   continue;  // continue checking for any connections

	} // closes FD_ISSET

	// (3.3) Are there any connections from sockfd4?
	if ( FD_ISSET(sockfd4, &rfds) )
	{
	   int new_sockfd;
	   char ack_mesg[3];  // ack message to send back to client

	   // accept a connection; fills in client address information
	   if ( (new_sockfd = accept(sockfd4, (struct sockaddr *) &cli_addr,
			&clilen)) < 0 )
	   {
		perror("Error on accept() for sockfd4");
		return -1;
	   }

	   #ifdef DEBUG
	   cout << "Connection from: " << inet_ntoa(cli_addr.sin_addr) << endl;
	   #endif

	   // (a) get the packet of information from client 
	   struct sockfd4_packet packet; 
	   if ( recv(new_sockfd, &packet, sizeof(packet), 0) == -1 )
	   {
		perror("Error on receving packet from sockfd4");
		close(new_sockfd);
		continue;
	   }

	   #ifdef DEBUG
	   cout << "In sockfd4: " << endl;
	   cout << packet.uid << ", " << packet.job_id << ", " << packet.host_license << ", "
	   	<< packet.maxlicense << ", " << packet.licensefile << ", " << packet.message << endl;
	   #endif

	   // (b) check what kind of message we have
	   if ( !strcmp(packet.message, "add_host") || !strcmp(packet.message, "delete_host") ||
	   	!strcmp(packet.message, "add_license") || !strcmp(packet.message, "delete_license") )
	   {
	      // this message is related to dynamically adding/deleting servers/licenses

	      // initialize the ack message
	      strcpy(ack_mesg, "1");  // everything is ok

	      // check if the user is root 
	      if ( packet.uid == 0 )
	      {
	         // if the message is to add a new host
		 if ( !strcmp(packet.message, "add_host") )
		 {
		    // if the host already exist, this is an error
		    list<string>::iterator it_addhost = find(valid_hosts.begin(), valid_hosts.end(),
		    						packet.host_license);
		    if (it_addhost == valid_hosts.end())
		    {
		       // add this new server to valid_hosts list but not to avail_hosts list yet
		       valid_hosts.push_back(packet.host_license);

		       // add this server to the communicate data structure
   		       // get the current time
		       struct timeval time;
		       gettimeofday(&time, NULL);

		       // temporary sockfd5_commun packet
		       struct sockfd5_commun sockfd5_packet;
		       sockfd5_packet.counter = 0;
		       sockfd5_packet.startup = 1;
		       sockfd5_packet.time = time;
	               communicate.insert( map<string, sockfd5_commun>::value_type(packet.host_license, 
		       							sockfd5_packet) );

		       // finally, check if this server is in the defective server list; if so, 
		       // delete this server from this list
		       list<string>::iterator host_iter =
		       	 find(defective_hosts.begin(), defective_hosts.end(), packet.host_license);
		       if (host_iter != defective_hosts.end())
		          defective_hosts.erase(host_iter);
		    }
		    else
		       strcpy(ack_mesg, "-3");  // host already exists
		 }
		 else if ( !strcmp(packet.message, "delete_host") )
		 {
		    // call the "defective_server" function
		    if ( defective_server(packet.host_license) < 0 )
		       strcpy(ack_mesg, "-4");  // host does not exists
		 }
		 else if ( !strcmp(packet.message, "add_license") )
		 {
		    map<string, int>::iterator it_addlicense = avail_licenses.find(packet.host_license);

		    // if license already exists, increment its counter by packet.maxlicense
		    if ( it_addlicense != avail_licenses.end() )
		    {
		       it_addlicense->second = it_addlicense->second + packet.maxlicense;

		       // if the license file is not equal to "", then update license file if file is valid
		       if ( strcmp(packet.licensefile, "") )
		       {
		          // check if packet's license file is valid
	   		  if ( lmleft(packet.licensefile, packet.host_license) >= 0 )
			  {
		             map<string, string>::iterator it_licensefile = 
			  				license_files.find(packet.host_license);
			     if (it_licensefile != license_files.end())
			        it_licensefile->second = packet.licensefile;
			  }
		       }
		    }
		    else  // license does not exist, so create a new license with total of packet.maxlicense 
		    {
		       // if the packet's license file is equal to "", this is an error 
		       if ( strcmp(packet.licensefile, "") )
		       {
		          // check if packet's license file is valid 
	   		  if ( lmleft(packet.licensefile, packet.host_license) < 0 )
			     strcpy(ack_mesg, "-6");  // invalid license file
			  else
			  {
		             avail_licenses.insert( map<string, int>::value_type(packet.host_license, 
		       									packet.maxlicense) );
			     license_files.insert( map<string, string>::value_type(packet.host_license,
			  						packet.licensefile) );
			  }
		       }
		       else
		          strcpy(ack_mesg, "-6");  // no license file
		    }
		 }
		 else if ( !strcmp(packet.message, "delete_license") )
		 {
		    // if license does not exist, this is an error
		    map<string, int>::iterator it_dlicense = avail_licenses.find(packet.host_license);

		    if (it_dlicense != avail_licenses.end())
		    {
		       it_dlicense->second = it_dlicense->second - packet.maxlicense;

		       // if the license file is not equal to "", then update license file if file is valid
		       if ( strcmp(packet.licensefile, "") )
		       {
		          // check if packet's license file is valid
	   		  if ( lmleft(packet.licensefile, packet.host_license) >= 0 )
			  {
		             map<string, string>::iterator it_licensefile = 
			  				license_files.find(packet.host_license);
			     if (it_licensefile != license_files.end())
			        it_licensefile->second = packet.licensefile;
			  }
		       }
		    }
		    else
		       strcpy(ack_mesg, "-5");  // license does not exists
		 }
	      }
	      else
	         strcpy(ack_mesg, "-2");  // permission denied

	      // send ack back to client 
	      if ( send(new_sockfd, ack_mesg, sizeof(ack_mesg), 0) < 1 )
	      {
		 perror("Error on sending acknowledgement to sockfd4");
	      }

	      // close off the socket connection
	      close(new_sockfd);
	   }
	   else
	   {
	      // this message is job related

	      map<string, task_packet>::iterator it_jobfind;
	      it_jobfind = job_find.find(packet.job_id);

	      if ( it_jobfind == job_find.end() )
		 strcpy(ack_mesg, "-1");  // job does not exist
	      else if ( (packet.uid == 0) || (packet.uid == it_jobfind->second.uid) )
		 strcpy(ack_mesg, "1");  // everything is ok
	      else
		 strcpy(ack_mesg, "-2");  // permission denied

	      // send ack back to client
	      if ( send(new_sockfd, ack_mesg, sizeof(ack_mesg), 0) < 1 )
	      {
		 perror("Error on sending acknowledgement to sockfd4");
	      } 

	      // close off the socket connection
	      close(new_sockfd);

	      // should we go on or stop now?
	      if ( (!strcasecmp(ack_mesg, "-1")) || (!strcasecmp(ack_mesg, "-2")) )
		continue;

	      // if job has license(s) confiscated or if job is in the intermediate queue,
	      // then we can't process this message yet
	      if ( it_jobfind->second.queue_type == "intermediate" )
	      {
	         // if the message is not to change the priority of the job
		 if ( strcmp(packet.message, "high_priority") && strcmp(packet.message, "low_priority") )
		 {
	            job_messages.push_back(packet);
		    continue;
		 }
	      }
	      else
	      {
	         // check if job has licenses confiscated
		 map<string, job_info>::iterator iter_find;
	         if ( it_jobfind->second.queue_type == "low_running" )
		 {
		    iter_find = low_running.find(it_jobfind->second.hostname);
		    if ( iter_find != low_running.end() )
		       if ( iter_find->second.confiscated )
		       {
		          job_messages.push_back(packet);
			  continue;
		       }
		 }
	      }

	      // call the task_control function to process the message
	      task_control(packet, it_jobfind);
	   }

	   // check if we need to execute the procedures after the "select" timeout 
	   ++starve_counter;
	   if ( starve_counter == MAXSTARVECOUNTER )
	   {
	      starve_counter = 0;  // reset the variable
	      check_wait();
	      check_jobmsg();
	      display_status();
	      waitpid(-1, NULL, WNOHANG);  // see if there are any zombie processes we need to bury

	      #ifdef DEBUG
	      display_debug();
	      #endif
	   }

	   continue;  // continue checking for any connections

	} // closes FD_ISSET

	// (3.4) Are there any connections from sockfd5?
	if ( FD_ISSET(sockfd5, &rfds) )
	{
	   int new_sockfd;

	   // accept a connection; fills in client address information
	   if ( (new_sockfd = accept(sockfd5, (struct sockaddr *) &cli_addr,
			&clilen)) < 0 )
	   {
		perror("Error on accept() for sockfd5");
		return -1;
	   }

	   #ifdef DEBUG
	   cout << "Connection from: " << inet_ntoa(cli_addr.sin_addr) << endl;
	   #endif

	   // (a) get the packet of information from client 
	   struct sockfd3_packet packet; 
	   if ( recv(new_sockfd, &packet, sizeof(packet), 0) == -1 )
	   {
		perror("Error on receving packet from sockfd3");
		close(new_sockfd);
		continue;
	   }

	   // close off the socket connection
	   close(new_sockfd); 

	   #ifdef DEBUG
	   cout << "In sockfd5: " << endl;
	   cout << "packet: " << packet.hostname << " " << packet.job_pid << " " 
		<< packet.user_id << endl;
	   #endif

	   // find this server in the communicate data structure
	   map<string, sockfd5_commun>::iterator itc_find = communicate.find(packet.hostname);
	   if (itc_find != communicate.end())
	   {
	      // reset the timer for this server
	      struct timeval time;
	      gettimeofday(&time, NULL);
	      itc_find->second.time = time;

	      // We have serveral cases to consider now: 
	      // (a) server is in the avail_hosts list and queued says no job is running
	      // (b) server is in the avail_hosts list and queued says a job is running
	      // (c) server is not in the avail_hosts list and queued says no job is running
	      // (d) server is not in the avail_hosts list and queued says a job is running.
	      // Case (a) is ok.  We have to worry about cases (b), (c), and (d).
	      
	      list<string>::iterator it_hosts = 
		   find(avail_hosts.begin(), avail_hosts.end(), itc_find->first);
	      if (it_hosts != avail_hosts.end())
	      {
	         // server is in the avail_hosts list, so just reset its counter
		 itc_find->second.counter = 0;

		 // (b) if queue daemon says that a job is running, this is a problem -- handle this!
		 if (packet.job_pid != 0)
		 {
		    // create a new job and put this job in the high_running queue -- problem
		    // is that I would not know how many licenses are available (root would have
		    // to update the licenses data structure manually)

   		    // delete this host name off of avail_hosts
		    avail_hosts.erase(it_hosts);

		    // call the create_newjob() function 
		    create_newjob(packet);
		 }
	      }
	      else
	      {
	         // server is not in the avail_hosts list, so check if queue daemon says if a job 
		 // is running or not

		 if (packet.job_pid != 0)
		 {
		    // (d) job is running, so just reset the counter
		    itc_find->second.counter = 0;

		    // set its startup bit to 0
		    itc_find->second.startup = 0;
		    
		    // check if job is in any of the running or intermediate queues; if 
		    // job is not in any of these queues, then we simply create a new
		    // job and put it in the high_running queue  (Note: this
		    // check is essentially used when the queue_manager first fires up.)
		    int createjob = 1;
   		    map<string, job_info>::iterator it_jobfind;
   		    if ((it_jobfind = high_running.find(itc_find->first)) != high_running.end())
		       createjob = 0;
   		    else if ((it_jobfind = low_running.find(itc_find->first)) != low_running.end())
		       createjob = 0;
   		    else if ((it_jobfind = intermediate.find(itc_find->first)) != intermediate.end())
		    {
		       createjob = 0;

		       // move the job to the high running queue
		       move_job(it_jobfind, packet);
		    }

		    if (createjob)  // need to create a new job
		       create_newjob(packet);
		 }
		 else  
		 {
		    // (c) job is not running 

		    // if this is the first time that we've heard from this queue daemon, then
		    // just put this server in the avail_hosts list and set its startup bit to 0
		    if (itc_find->second.startup)
		    {
		       avail_hosts.push_back(itc_find->first);
		       itc_find->second.startup = 0;
		       continue;
		    }

		    // The bad case:
		    // first, increment its counter; if the counter is equal to MAXQUEUEDCOUNTER,
		    // then update the data structures and reset counter
		    itc_find->second.counter = itc_find->second.counter + 1;
		    if (itc_find->second.counter == MAXQUEUEDCOUNTER)  
		    {
		       // reset the counter
		       itc_find->second.counter = 0;

		       // update avail_hosts 
		       avail_hosts.push_back(itc_find->first);
	
   		       // check the running queues and the intermediate queue to see if there is 
   		       // a job running on this server; if there is, delete this job from the queue

		       // Note: If batch job, need to wait on child process.  If this job
		       // has confiscated any licenses, needs to unsuspend all the suspended processes.
		       // (Haven't put in the code for this yet.)
		       int batchpid = -1;
   		       map<string, job_info>::iterator it_jobfind;

   		       if ((it_jobfind = high_running.find(itc_find->first)) != high_running.end())
   		       {
			  // delete the element off of job_find as well
			  map<string, task_packet>::iterator it_find;
			  it_find = job_find.find(it_jobfind->second.job_id);
			  job_find.erase(it_find);
	
		 	  // update the avail_licenses
		   	  for ( int i=0; i < it_jobfind->second.license_vector.size(); i++ )
		   	  {
				map<string, int>::iterator license_iter;
				license_iter = avail_licenses.find(
						it_jobfind->second.license_vector[i]);
				license_iter->second = license_iter->second + 1;
		   	  }

		  	  // need to bury zombie process?
			  if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   		     batchpid = it_jobfind->second.batch_pid;

			  high_running.erase(it_jobfind);
   		       }
   		       else if ((it_jobfind = low_running.find(itc_find->first)) != low_running.end())
   		       {
  			  // delete the element off of job_find as well
			  map<string, task_packet>::iterator it_find;
			  it_find = job_find.find(it_jobfind->second.job_id);
			  job_find.erase(it_find);

		 	  // update the avail_licenses
		   	  for ( int i=0; i < it_jobfind->second.license_vector.size(); i++ )
		   	  {
				map<string, int>::iterator license_iter;
				license_iter = avail_licenses.find(
						it_jobfind->second.license_vector[i]);
				license_iter->second = license_iter->second + 1;
		   	  }

		  	  // need to bury zombie process?
			  if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   		     batchpid = it_jobfind->second.batch_pid;

			  low_running.erase(it_jobfind);
   		       }
   		       else if ((it_jobfind = intermediate.find(itc_find->first)) != intermediate.end())
   		       {
  			  // delete the element off of job_find as well
			  map<string, task_packet>::iterator it_find;
			  it_find = job_find.find(it_jobfind->second.job_id);
			  job_find.erase(it_find);

		 	  // update the avail_licenses
		   	  for ( int i=0; i < it_jobfind->second.license_vector.size(); i++ )
		   	  {
				map<string, int>::iterator license_iter;
				license_iter = avail_licenses.find(
						it_jobfind->second.license_vector[i]);
				license_iter->second = license_iter->second + 1;
		   	  }

		  	  // need to bury zombie process?
			  if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   		     batchpid = it_jobfind->second.batch_pid;

			  intermediate.erase(it_jobfind);
   		       }

	// need to bury zombie process?
	if ( batchpid != -1 )
   	{
	// sometimes we have to manually kill off the forked off
	// queue_manager (better to do this way; otherwise,
	// waitpid will block forever waiting for the child to die)

 	// the command to get the "sh..." pid first
	char pidcmd[100];
	strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
	sprintf(pidcmd, "%s %d %s", pidcmd, batchpid,
					"| awk '{print $3}' | grep -v");
	sprintf(pidcmd, "%s %d %s %s", pidcmd, batchpid, ">", TEMPFILE);

	#ifdef DEBUG
	cout << pidcmd << endl;
	#endif

	if ( system(pidcmd) < 0 )
	   perror("Error on pidcmd system()");
	else
	{
   	   // now read in the value of the "sh" pid
   	   int sh_pid = -1;
   	   fin.open(TEMPFILE);

	   if ( !fin.bad() )
	   {
   	      fin >> sh_pid;
   	      fin.close();

   	      if ( sh_pid != -1 )
   	      {
	         char pidcmd[100];
	         strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
	         sprintf(pidcmd, "%s %d %s", pidcmd, sh_pid,
			"| awk '{print $3}' | grep -v");
	         sprintf(pidcmd, "%s %d %s %s", pidcmd, sh_pid, ">", TEMPFILE);

  	         if ( system(pidcmd) < 0 )
  		   perror("Error on pidcmd system()");
	         else
	         {
	            // now get the actual pid that we need to kill the job
	            int kill_pid = -1;
	            fin.open(TEMPFILE);

		    if ( !fin.bad() )
		    {
	               fin >> kill_pid;
	               fin.close();

		       #ifdef DEBUG
		       cout << "kill_pid: " << kill_pid << endl;
		       #endif
	
		       // send the process the kill signal
		       if (kill_pid > 0)
		       { 
		          kill( kill_pid, SIGTERM );  // try SIGTERM first
	 	          kill( kill_pid, SIGKILL );
		       }
		    }
	         }
   	      } // closes off "if (sh_pid..."
	   }
	}

	// now bury this child	
	waitpid(batchpid, NULL, WNOHANG);
	
	#ifdef DEBUG
	cout << "after waiting on child process" << endl;
	#endif
   }

		    }
		 }
	      }
	   }

	   // check if we need to execute the procedures after the "select" timeout 
	   ++starve_counter;
	   if ( starve_counter == MAXSTARVECOUNTER )
	   {
	      starve_counter = 0;  // reset the variable
	      check_wait();
	      check_jobmsg();
	      display_status();
	      waitpid(-1, NULL, WNOHANG);  // see if there are any zombie processes we need to bury

	      #ifdef DEBUG
	      display_debug();
	      #endif
	   }

	   continue;  // continue checking for any connections

	} // closes FD_ISSET

	#ifdef DEBUG
	cout << "Timed Out" << endl; 
	#endif

	// reset the starve_counter variable first
	starve_counter = 0;

	/* (4) Check if we can run any jobs in the waiting queues */
	check_wait();

	/* (5) Check if we can process any messages in the job_messages data structure. */
	check_jobmsg();

	/* (6) Update the status file. */
	display_status();

	/* (7) See if there are any zombie processes we need to bury. */
	waitpid(-1, NULL, WNOHANG);  

	#ifdef DEBUG
	display_debug();
	#endif

	/* (8) Check if any of the queue daemons are down. */
	check_queued();	

   }  // closes for loop

   return 0;
}

// updates the status file
int display_status()
{
   // open the status file
   if ( (fout_status = fopen(STATUSFILE, "w+")) == NULL )
   {
      perror("Can't open status file");
      return -1;
   }

   // print out the available servers
   list<string>::iterator list_begin, list_end;
   map<string, int>::iterator map_begin, map_end;

   fprintf(fout_status, "%s ", "AVAILABLE SERVERS:");
   list_begin = avail_hosts.begin(); list_end = avail_hosts.end();
   while ( list_begin != list_end )
   {
	fprintf(fout_status, "%s ", list_begin->c_str()); 
	++list_begin;
   }
   fprintf(fout_status, "\n");

   // print out the available licenses
   fprintf(fout_status, "%s", "AVAILABLE LICENSES: ");
   map_begin = avail_licenses.begin(); map_end = avail_licenses.end();
   while ( map_begin != map_end )
   {
	fprintf(fout_status, "%s %d ", map_begin->first.c_str(), map_begin->second); 
	++map_begin;
   }
   fprintf(fout_status, "\n");

   // print out the valid servers
   fprintf(fout_status, "%s ", "VALID SERVERS: ");
   list_begin = valid_hosts.begin(); list_end = valid_hosts.end();
   while ( list_begin != list_end )
   {
	fprintf(fout_status, "%s ", list_begin->c_str()); 
	++list_begin;
   }
   fprintf(fout_status, "\n");

   // print out the defective servers
   fprintf(fout_status, "%s ", "DEFECTIVE SERVERS: ");
   list_begin = defective_hosts.begin(); list_end = defective_hosts.end();
   while ( list_begin != list_end )
   {
	fprintf(fout_status, "%s ", list_begin->c_str()); 
	++list_begin;
   }
   fprintf(fout_status, "\n\n");

   // print out the number of jobs 
   fprintf(fout_status, "%s\n", "NUMBER OF JOBS SUBMITTED");
   fprintf(fout_status, "%s\n", "------------------------");
   fprintf(fout_status, "%s %d\n", "HIGH PRIORITY RUNNING JOBS:", high_running.size());
   fprintf(fout_status, "%s %d\n", "LOW PRIORITY RUNNING JOBS:", low_running.size());
   fprintf(fout_status, "%s %d\n", "INTERMEDIATE JOBS:", intermediate.size());
   fprintf(fout_status, "%s %d\n", "HIGH PRIORITY WAITING JOBS:", high_waiting.size());
   fprintf(fout_status, "%s %d\n\n", "LOW PRIORITY WAITING JOBS:", low_waiting.size());

   fprintf(fout_status, "%-11s %-10s %-6s %s %-9s %s %s %-29s %-35s %s\n", "JOB_ID", "USER", "USERID", 
   			"MODE", "SERVER", "STATUS", "PRIORITY", "DATE", "JOB", "LICENSE(S)");
   fprintf(fout_status, "-----------------------------------------------------------------------------------------------------------------------------------------\n");

   // print out information from the high-low_running, and intermediate queues
   for ( int i = 0; i < 3; i++ )
   {
	map<string, job_info>::iterator q_begin, q_end;
  	if ( i == 0 )
	{ q_begin = high_running.begin(); q_end = high_running.end(); }
	else if ( i == 1 )
	{ q_begin = low_running.begin(); q_end = low_running.end(); }
	else
	{ q_begin = intermediate.begin(); q_end = intermediate.end(); }

	while ( q_begin != q_end )
	{
	   hdisplay_status(q_begin->second);
	   ++q_begin;
	} 
   }

   // now print out information from the high-low waiting queues
   for ( int i = 0; i < 2; i++ )
   {
      list<job_info>::iterator q_begin, q_end;

      if ( i == 0 )
      { q_begin = high_waiting.begin(); q_end = high_waiting.end(); }
      else
      { q_begin = low_waiting.begin(); q_end = low_waiting.end(); }

      while ( q_begin != q_end )
      {
	 hdisplay_status(*q_begin);
	 ++ q_begin;
      }
   }

   fclose(fout_status);
   return 0;
}

// a helper display function to the display_status function
void hdisplay_status(job_info packet)
{
   fprintf(fout_status, "%-11s %-10s %-7d ", packet.job_id.c_str(), packet.packet.user,
   	packet.packet.user_id);

   // print out the mode
   if ( !strcasecmp(packet.packet.mode, "interactive") )
	fprintf(fout_status, "%-4s", "I ");
   else 
	fprintf(fout_status, "%-4s", "B ");

   // print out the server
   if ( packet.host_running == "" )
   	fprintf(fout_status, "%-11s", "N/A");
   else
   	fprintf(fout_status, "%-11s", packet.host_running.c_str());

   // print out the status
   if ( (packet.status == "running") || (packet.status == "suspend") )
	fprintf(fout_status, "%-7s ", "run");
   else
	fprintf(fout_status, "%-7s ", "wait");

   // print out the priority
   if ( !strcasecmp(packet.packet.priority, "high") )
	fprintf(fout_status, "%-7s", "high  ");
   else
	fprintf(fout_status, "%-7s", "low  ");
	  
   // print out the date
   fprintf(fout_status, "%-30s", packet.packet.datesubmit);

   // print out the job command 
   fprintf(fout_status, "%-35s  ", packet.packet.job);

   // print out the licenses 
   fprintf(fout_status, "%s", "[ ");
   for (int i = 0; i < packet.license_vector.size(); i++)
   	fprintf(fout_status, "%s ", packet.license_vector[i].c_str());
   fprintf(fout_status, "%s\n", "] ");
}

#ifdef DEBUG
int display_debug()
{
	fout_debug.open(QDEBUGFILE);
	if ( fout_debug.bad() )
	{
	   perror("Can't open debug file");
	   return -1;
	}

	// (1) Display valid_hosts, avail_hosts, avail_licenses first. 
 	list<string>::iterator list_begin, list_end;
	map<string, int>::iterator map_begin, map_end;

	fout_debug << "VALID_HOSTS" << endl;
	list_begin = valid_hosts.begin(); list_end = valid_hosts.end();
	while ( list_begin != list_end )
	{
 	   fout_debug << *list_begin << " ";	
	   ++list_begin;
	}
	fout_debug << endl;

	fout_debug << "AVAIL_HOSTS" << endl;
	list_begin = avail_hosts.begin(); list_end = avail_hosts.end();
	while ( list_begin != list_end )
	{
 	   fout_debug << *list_begin << " ";	
	   ++list_begin;
	}
	fout_debug << endl;

	fout_debug << "AVAIL_LICENSES" << endl;
	map_begin = avail_licenses.begin(); map_end = avail_licenses.end();
	while ( map_begin != map_end )
	{
		fout_debug << map_begin->first << " " << map_begin->second << " ";
		++map_begin;
	}
	fout_debug << endl;

	// Display the defective_hosts.
	fout_debug << "DEFECTIVE_HOSTS" << endl;
	list_begin = defective_hosts.begin(); list_end = defective_hosts.end();
	while ( list_begin != list_end )
	{
 	   fout_debug << *list_begin << " ";	
	   ++list_begin;
	}
	fout_debug << endl;

	// Display the license files.
	fout_debug << "LICENSE_FILES: " << endl;
	map<string, string>::iterator itl_begin = license_files.begin(), itl_end = license_files.end();
	while ( itl_begin != itl_end )
	{
	   fout_debug << itl_begin->first << " " << itl_begin->second << endl; 
	   ++itl_begin;
	}
	fout_debug << endl;

	// (2) Display all the queues.
	map<string, job_info>::iterator queue_begin, queue_end;
	list<job_info>::iterator qlist_begin, qlist_end;

	fout_debug << "HIGH_RUNNING QUEUE" << endl;
	queue_begin = high_running.begin(); queue_end = high_running.end();
	while ( queue_begin != queue_end )
	{
		hdisplay_debug(queue_begin->second);
		++ queue_begin;
	}

	fout_debug << "LOW_RUNNING QUEUE" << endl;
	queue_begin = low_running.begin(); queue_end = low_running.end();
	while ( queue_begin != queue_end )
	{
		hdisplay_debug(queue_begin->second);
		++ queue_begin;
	}
 		
	fout_debug << "INTERMEDIATE QUEUE" << endl;
	queue_begin = intermediate.begin(); queue_end = intermediate.end();
	while ( queue_begin != queue_end )
	{
		hdisplay_debug(queue_begin->second);
		++ queue_begin;
	}
 		
	fout_debug << "HIGH_WAITING QUEUE" << endl;
	qlist_begin = high_waiting.begin(); qlist_end = high_waiting.end();
	while ( qlist_begin != qlist_end )
	{
		hdisplay_debug(*qlist_begin);
		++ qlist_begin;
	}
 		
	fout_debug << "LOW_WAITING QUEUE" << endl;
	qlist_begin = low_waiting.begin(); qlist_end = low_waiting.end();
	while ( qlist_begin != qlist_end )
	{
		hdisplay_debug(*qlist_begin);
		++ qlist_begin;
	}

	// (3) Display the job_find map.
	fout_debug << "JOB_FIND MAP" << endl;
 	map<string, task_packet>::iterator itb_jobfind = job_find.begin(),
				ite_jobfind = job_find.end();
	while ( itb_jobfind != ite_jobfind )
	{
		fout_debug << itb_jobfind->first << " " << itb_jobfind->second.uid 
		     << " " << itb_jobfind->second.queue_type 
		     << endl; 
		++itb_jobfind;	   
	}
	fout_debug << endl;

	// (4) Display the job_messages. 
	fout_debug << "JOB_MESSAGES" << endl;
	list<sockfd4_packet>::iterator itb_jobmsg = job_messages.begin(), 
					ite_jobmsg = job_messages.end();
	while ( itb_jobmsg != ite_jobmsg )
	{
 	   fout_debug << itb_jobmsg->job_id << " " << itb_jobmsg->message << endl;	
	   ++itb_jobmsg;
	}

	fout_debug.close();
}
#endif

#ifdef DEBUG
void hdisplay_debug(job_info packet)
{
   fout_debug << "Job Element: " << endl;

   // display the structure first
   fout_debug << "user: " << packet.packet.user << ", ";
   fout_debug << "user_id: " << packet.packet.user_id << ", ";
   fout_debug << "group_id: " << packet.packet.gid << ", ";
   fout_debug << "date submitted: " << packet.packet.datesubmit << ", "; 
   fout_debug << "job: " << packet.packet.job << ", ";
   fout_debug << "mode: " << packet.packet.mode << ", ";
   fout_debug << "confiscated: " << packet.confiscated << ", ";
   fout_debug << "priority: " << packet.packet.priority << ", ";
   if (!strcasecmp(packet.packet.mode, "batch"))
	fout_debug << "logfile: " << packet.packet.logfile << ", ";
   fout_debug << "prefhost: " << packet.packet.prefhost << ", ";
   fout_debug << "onlyhost: " << packet.packet.onlyhost << ", ";
   fout_debug << "status: " << packet.status << ", ";
   if ( !strcasecmp(packet.status.c_str(), "running"))
	fout_debug << "job_pid: " << packet.job_pid << ", ";

   // print out the job_id
   fout_debug << "JOB_ID: " << packet.job_id << ", "; 

   // now display the vector buffer
   fout_debug << endl << "Licenses: ";
   for (int i = 0; i < packet.license_vector.size(); i++)
	fout_debug << packet.license_vector[i] << " "; 

   fout_debug << endl << endl;
}
#endif

// jumps to this function when host and license(s) are available, interactive job
int hlavail_i(job_info temp_job, int new_sockfd, list<string>::iterator it_find )
{
   // Just in case the interactive user decides to quit the queue client program.
   signal(SIGPIPE, sigpipe_handler); 

   // send the server name to the queue client
   if (send(new_sockfd, assigned_host, sizeof(assigned_host), 0) < 0)
   {
	   perror("Error on sending assigned host");
	   return -1;
   }

   // send the job id to the queue client
   char buffer[MAXHOSTNAMELEN];
   strcpy(buffer, temp_job.job_id.c_str());
   if (send(new_sockfd, buffer, sizeof(buffer), 0) < 0)
   {
	   perror("Error on sending job_id");
	   return -1;
   }

   // close off the socket connection
   close(new_sockfd);

   // delete this host name off of avail_hosts
   if ( it_find != avail_hosts.end() )
	avail_hosts.erase(it_find);

   // update available licenses list 			
   map<string, int>::iterator license_iter;
   for (int i = 0; i < temp_job.license_vector.size(); i++)
   {
  	license_iter = avail_licenses.find(temp_job.license_vector[i]);
	license_iter->second = license_iter->second - 1; 
   }

   // save other information about the job in temp_job
   temp_job.host_running = assigned_host;
   temp_job.status = "waiting";

   // put job in intermediate queue
   intermediate.insert( map<string, job_info>::value_type(assigned_host, temp_job) );

   return 0;
}

// jumps to this function when host and license(s) are available, batch job
int hlavail_b(job_info temp_job, int waitq, list<string>::iterator it_find)
{
   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   // (1) piece together the command line argument

   // command to "cd" to the user's directory where "queue" was submitted
   char cd_cmd[MAXQUEUECOMMAND];
   strcpy(cd_cmd, "cd");
   sprintf(cd_cmd, "%s %s%s", cd_cmd, temp_job.packet.cur_dir, "; pwd;");

   // the queue command
   char q_command[MAXQUEUECOMMAND];
   strcpy(q_command, QDIR);
   sprintf(q_command, "%s %s %s", q_command, "-h", assigned_host);

   // a dummy license so that queue.c won't complain that we didn't
   // specify any licenses
   sprintf(q_command, "%s %s %s", q_command, "-a", "license");

   // a hack so that queue.c will not make a connection back to us 
   sprintf(q_command, "%s %s", q_command, "-1");

   sprintf(q_command, "%s %s %s", q_command, "--", temp_job.packet.job); 
   
   // redirect the stdout of the batch job to the log file
   sprintf(q_command, "%s %s %s", q_command, ">", 
					temp_job.packet.logfile);

   // the whole command
   char cmd[MAXQUEUECOMMAND];
   strcpy(cmd, cd_cmd);
   sprintf(cmd, "%s %s", cmd, q_command); 

   #ifdef DEBUG
   cout << "cmd: " << cmd << endl;
   #endif

   // (2) now fork off a child process	
   int pid;
   if ( (pid = fork()) == 0 )
   {
	/* child process */

	// set the current environment to the user's environment
	extern char ** environ;
	for ( int i=0; i < temp_job.vec_arge.size(); i++ )
	   putenv(temp_job.vec_arge[i].c_str());

	// set the uid and gid to the user of the current job
	if ( setgid(temp_job.packet.gid) < 0 )
	{
	   perror("Error: on setting gid");
	   exit(-1);
	}  
	
	// initialize the group access list
	if ( initgroups(temp_job.packet.user, temp_job.packet.gid) < 0 )
	{
	   perror("Error: on setting initgroups");
	   exit(-1);
	}

	if ( setuid(temp_job.packet.user_id) < 0 )
	{
	   perror("Error: on setting user id");
	   exit(-1);
	}
    
	// create the user's logfile 
	ofstream fout(temp_job.packet.logfile);
	if ( fout.bad() )
	{
	   perror("Can't create user's logfile"); 
	   exit(-1);
	}
	fout.close();

	// now execute the job
	if ( system(cmd) < 0 )
	{
	   perror("Error: in system()");
	   exit(-1);
	}

	#ifdef DEBUG
	cout << "Child process finishes..." << endl;
	#endif

	// exit when done
	exit(1);
   }
   else if ( pid == -1 )
   {
	// fork error: too many processes right now, so just try forking this
	// job again later; 
	return 1;
   }
   else
   {
	/* parent process */

	// store the child's pid in temp_job
	temp_job.batch_pid = pid;

	#ifdef DEBUG
	cout << "batch_pid: " << temp_job.batch_pid << endl;
	#endif

	// delete this host name off of avail_hosts
	if ( it_find != avail_hosts.end() )
	   avail_hosts.erase(it_find);

	// update available licenses list 			
 	map<string, int>::iterator license_iter;
	for (int i = 0; i < temp_job.license_vector.size(); i++)
	{
	   license_iter = avail_licenses.find(temp_job.license_vector[i]);
	   license_iter->second = license_iter->second - 1; 
	}

	// save other information about the job in temp_job
	temp_job.host_running = assigned_host;
	temp_job.status = "waiting";

	// put job in intermediate queue
	intermediate.insert( map<string, job_info>::value_type(assigned_host, temp_job) );

	return 0;
   }
}

// jumps to this function when job is high priority and host is available but license(s) are 
// not available (for both interactive and batch jobs)
int hl_unavail(job_info temp_job, int new_sockfd, int waitq, list<string>::iterator it_find)
{
   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   map<string, conflic_packet> temp_map;
   list<string> avail_erase;  // licenses to erase from avail_licenses
   map<string, int> unsuspend_servers;  // list of jobs to unsuspend 

   // insert all the licenses that we need into a list
   list<string> license_vector;
   for ( int i = 0; i < temp_job.license_vector.size(); i++ )
	license_vector.push_back(temp_job.license_vector[i]);

   // 1st, iterate through the avail_licenses list to check if
   // there are any licenses available before going to the queue
   list<string>::iterator itb_need = license_vector.begin(),	
				itb_end = license_vector.end();

   while ( itb_need != itb_end )
   {
      map<string, int>::iterator it_find = avail_licenses.find(*itb_need);

      if ( it_find->second > 0 )
      {
	 /* this is an error -- can't update yet!
	 // update available license list
	 it_find->second = it_find->second - 1; */

	 avail_erase.push_back(*itb_need);

	 // save the state of the current iterators 
	 list<string>::iterator temp1_iter = itb_need;
	 list<string>::iterator temp2_iter = ++temp1_iter;

	 // delete the license off of license_vector
	 license_vector.erase(itb_need);
	
	 // update the iterators
	 itb_need = temp2_iter;
	 itb_end = license_vector.end();

	 continue;  // go back to the top of the loop
     }

     ++itb_need;
   }
		 
   // 2nd, iterate through each job in the low_running queue
   // (forget about the intermediate queue -- too complicated)
   map<string, job_info>::iterator it_begin = low_running.begin(),
			   	   it_end = low_running.end();
   while ( it_begin != it_end )
   {
      // if the job has any licenses already confiscated by
      // another job, skip this job (makes life simpler)
      if ( it_begin->second.confiscated == 1 )
      {
	 ++it_begin;
	 continue;
      }

      // packet that holds the confiscated license(s) 
      // that we've gotten from this job
      struct conflic_packet tempconf_packet;

      // set iterators for license_vector list (license(s) needed)
      list<string>::iterator itb_need = license_vector.begin(),	
					itb_end = license_vector.end();

      // for each license in the license_vector list
      while ( itb_need != itb_end )
      {
	   // Note: this will not work if we need multiple license
	   // of the same type (like, we need two "apple" licenses).
	   // This is assuming that we need only one license of each
	   // type.  Can fix later if need to.

	   // for each license in the low_running job's license_vector
	   for (int j = 0; j < it_begin->second.license_vector.size(); j++)
	   {
	      // if the licenses match, then insert into tempconf_packet 
	      if ( !strcasecmp((*itb_need).c_str(),
			(it_begin->second.license_vector[j]).c_str()) )
		tempconf_packet.license_vector.push_back(*itb_need);	
	   }
	   ++itb_need;	
      }

      if ( !tempconf_packet.license_vector.empty() )
      {
	 // insert the forked off queued pid into the temp_map
	 tempconf_packet.job_pid = it_begin->second.job_pid;
 
	 // insert hostname and tempconf_packet into the temp_map 
	 temp_map.insert( map<string, conflic_packet>::
				value_type(it_begin->first, tempconf_packet) );

	 // now delete licenses off of the license_vector list
	 for ( int k = 0; k < tempconf_packet.license_vector.size(); k++ )
	 {
	       list<string>::iterator itlist_find = 
		find(license_vector.begin(), license_vector.end(), 		
	       tempconf_packet.license_vector[k]);

	       license_vector.erase(itlist_find);
	 } 
       }

       ++it_begin;
   }	

   // if license_vector is empty, means that we have all the
   // confiscated licenses available 
   if ( license_vector.empty() )
   {
	#ifdef DEBUG
	cout << "licenses available!" << endl;
	#endif

	// (1) open up a connection to the "task_manager" of every host in 
	// temp_map and send the job a "suspend" signal
        map<string, conflic_packet>::iterator itb = temp_map.begin(),
					ite = temp_map.end();

	while ( itb != ite )
	{
	   // send the packet over to the task_manager
	   struct tm_packet tmpacket;  // packet to send to task_manager
	   tmpacket.job_pid = itb->second.job_pid; 
	   strcpy(tmpacket.message, "suspend");

	   // call tm_connect function
	   if ( tm_connect(itb->first, tmpacket) == 0 )
	   {
	      // put server name in temporary list "unsuspend_servers"
	      unsuspend_servers.insert( map<string, int>::value_type(itb->first, 
	      						itb->second.job_pid) );

	      // update the status of the confiscated license job
	      map<string, job_info>::iterator it_jfind =
					low_running.find(itb->first);
	      it_jfind->second.status = "suspend";
	      it_jfind->second.confiscated = 1;  // set confiscated bit
	   }
	   else
	   {
	      // got an error, so we have to unsuspend all the jobs that we've suspended;
	      // call "unsuspend_jobs" function to handle this error condition
	      unsuspend_jobs(unsuspend_servers);
	      return -1;
	   }

	   ++itb;
	} 

	// (2) assign temp_job's conf_license to temp_map
	// (note: we are assuming that all the connections are 
	// successful -- have to handle error cases later);
	// also assign temp_job's avail_license_erase to avail_erase
	temp_job.conf_license = temp_map;  
	temp_job.avail_license_erase = avail_erase;

	// (3) remove the licenses manually

	// (4) now follow the same exact format as above where hosts
	// and licenses are available 

	// start a new block
	{  
	   // interactive mode: send hostname back to queue client
	   if ( !strcasecmp(temp_job.packet.mode, "interactive") )
	   {
		if (send(new_sockfd, assigned_host, sizeof(assigned_host), 0) < 0)
		{
		   perror("Error on sending assigned host to queue client");
		   unsuspend_jobs(unsuspend_servers);
		   return -1;
		}

		// close off the socket connection
		close(new_sockfd);

		// delete this host name off of avail_hosts
		if ( it_find != avail_hosts.end() )
		   avail_hosts.erase(it_find);

		// save other information about the job in temp_job
		temp_job.host_running = assigned_host;
		temp_job.status = "waiting";

		// need to update avail_licenses list (if we took any licenses
		// from this list)
		list<string>::iterator it_begin = avail_erase.begin(),
					it_end = avail_erase.end();

		while ( it_begin != it_end )
		{
           	   map<string, int>::iterator it_find = 
			avail_licenses.find(*it_begin);
	   	   it_find->second = it_find->second - 1; 
	   	   ++it_begin;
		}

		// put job in intermediate queue
	 	intermediate.insert( map<string, job_info>::value_type(assigned_host,
									temp_job) ); 

		return 0;
	   }
	   // else, in batch mode
	   else
	   {
   		// (1) piece together the command line argument

   		// command to "cd" to the user's directory where "queue" was submitted
   		char cd_cmd[MAXQUEUECOMMAND];
   		strcpy(cd_cmd, "cd");
   		sprintf(cd_cmd, "%s %s%s", cd_cmd, temp_job.packet.cur_dir, "; pwd;");

   		// the queue command
   		char q_command[MAXQUEUECOMMAND];
   		strcpy(q_command, QDIR);
   		sprintf(q_command, "%s %s %s", q_command, "-h", assigned_host);

   		// a dummy license so that queue.c won't complain that we didn't
   		// specify any licenses
   		sprintf(q_command, "%s %s %s", q_command, "-a", "license");

   		// a hack so that queue.c will not make a connection back to us 
   		sprintf(q_command, "%s %s", q_command, "-1");

   		sprintf(q_command, "%s %s %s", q_command, "--", temp_job.packet.job); 
   
   		// redirect the stdout of the batch job to the log file
   		sprintf(q_command, "%s %s %s", q_command, ">", 
					temp_job.packet.logfile);

   		// the whole command
   		char cmd[MAXQUEUECOMMAND];
   		strcpy(cmd, cd_cmd);
   		sprintf(cmd, "%s %s", cmd, q_command); 

   		#ifdef DEBUG
   		cout << "cmd: " << cmd << endl;
   		#endif

		// (2) now fork off a child process	
		int pid;
		if ( (pid = fork()) == 0 )
		{
		   /* child process */

		   // set the current environment to the user's environment
		   extern char ** environ;
		   for ( int i=0; i < temp_job.vec_arge.size(); i++ )
	   		putenv(temp_job.vec_arge[i].c_str());

		   // set the uid and gid to the user of the current job
		   if ( setgid(temp_job.packet.gid) < 0 )
		   {
			perror("Error: on setting gid");
		  	exit(-1);
		   }  

		   // initialize the group access list
	  	   if ( initgroups(temp_job.packet.user, temp_job.packet.gid) < 0 )
		   {
	   		perror("Error: on setting initgroups");
	   		exit(-1);
		   }
			
		   if ( setuid(temp_job.packet.user_id) < 0 )
		   {
			perror("Error: on setting user id");
			exit(-1);
		   }

		   // create the user's logfile 
		   ofstream fout(temp_job.packet.logfile);
		   if ( fout.bad() )
		   {
	   		perror("Can't create user's logfile"); 
	   		exit(-1);
		   }
		   fout.close();

		   // now execute the job
		   if ( system(cmd) < 0 )
		   {
	   		perror("Error: in system()");
	   		exit(-1);
		   }

		   #ifdef DEBUG
		   cout << "Child process finishes..." << endl;
		   #endif

		   // exit when done
		   exit(1);
		}
		else if ( pid == -1 )
		{
		   // fork error: too many processes right now, so just try forking this
		   // job again later; job will be put in the waiting queue 

		   // call the error handling routine to unsuspend jobs
		   unsuspend_jobs(unsuspend_servers);

		   return -1;
		}	
		else
		{
		   /* parent process */

		   // store the child's pid in temp_job
		   temp_job.batch_pid = pid;

		  #ifdef DEBUG
		  cout << "batch_pid: " << temp_job.batch_pid << endl;
		  #endif

		   // delete this host name off of avail_hosts
		   if ( it_find != avail_hosts.end() )
			avail_hosts.erase(it_find);

		   // save other information about the job in temp_job
		   temp_job.host_running = assigned_host;
		   temp_job.status = "waiting";

		   // need to update avail_licenses list (if we took any licenses
		   // from this list)
		   list<string>::iterator it_begin = avail_erase.begin(),
					it_end = avail_erase.end();

		   while ( it_begin != it_end )
		   {
           	      map<string, int>::iterator it_find = 
			avail_licenses.find(*it_begin);
	   	      it_find->second = it_find->second - 1; 
	   	      ++it_begin;
		   }

		   // put job in intermediate queue
		   intermediate.insert( map<string, job_info>::value_type(assigned_host,
									temp_job) ); 

		   return 0;
		}

	   }  // closes off batch mode else 

	}  // closes off block
   }  // closes "if" license_vector is empty
   else
   {
	#ifdef DEBUG
	cout << "licenses not available" << endl;
	#endif

	return 1;
   } 

   #ifdef DEBUG
   list<string>::iterator itb = license_vector.begin(),
			ite = license_vector.end();
   cout << "License Vector: " << endl;
   while ( itb != ite )
   {
	cout << *itb << endl;
	++itb;
   }

   map<string, conflic_packet>::iterator itbegin =
	temp_job.conf_license.begin(), itend = temp_job.conf_license.end();
   while ( itbegin != itend )
   {
	cout << itbegin->first << ": " << itbegin->second.job_pid << ": ";
	for ( int g = 0; g < itbegin->second.license_vector.size(); g++ )
	   cout << itbegin->second.license_vector[g] << ", ";
	cout << endl; 
	++itbegin;
   }
   #endif

}

// jumps to this function whenever we need to make a connection to the task manager
int tm_connect(string hostname, struct tm_packet tmpacket)
{
   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   int sockfd;
   int counter = 1;
   struct sockaddr_in serv_addr;
   struct hostent *host;

   // get the IP address of the host to connect to
   if ( (host = gethostbyname(hostname.c_str())) == NULL )
   {
	perror("Invalid host name!");
	return 1;
   }

   // fill in the server information so that we can connect to it
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_port = htons(C_PORTNUM);
   serv_addr.sin_addr = *((struct in_addr *)host->h_addr);

   // We try to connect ten times to prevent an overloaded 
   // system from keeping us down. 
   while ( counter <= 10 )
   {
      // open up a TCP socket
      if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
      {
	 perror("Error on socket()");
	 return 1;
      }
		
      // set socket options for TCP socket
      int sendbuff = 16384;
      if ( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
		(char *) &sendbuff, sizeof(sendbuff)) < 0 )
      {
 	 perror("Error on TCP setsock option");
	 return 1;
      }
		
      if ( connect(sockfd, (struct sockaddr *) &serv_addr,
		sizeof(serv_addr)) < 0 )
      {
	 counter++;
	 cout << "Connecting to task_manager..." << endl;
	 sleep(3);  // sleep a few seconds before trying again	
      }
      else
	 break;
   }

   // if can't connect to task_manager, then assume that the server is down; put the server in 
   // the defective server list and call "defective_server"
   if ( counter == 11 )
   {
      defective_hosts.push_back(hostname);
      defective_server(hostname);
      return -1;
   }
   else
   {
      if ( send(sockfd, &tmpacket, sizeof(tmpacket), 0) < 0 )
      {
         defective_hosts.push_back(hostname);
         defective_server(hostname);
         perror("Error on sending packet");
	 return -1;
      }
   }

   // close off the socket connection
   close(sockfd);			   
 
   return 0;
}

// this function is called when we have to process user's message to kill, suspend, ... a job
int task_control(struct sockfd4_packet packet, map<string, task_packet>::iterator it_jobfind)
{
   	   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
  	   signal(SIGPIPE, sigpipe_handler); 

	   // (a) process the message 
	   int connect_bit = 0;  // need to connect to task_manager?
	   tm_packet tmpacket;  // packet to send to task_manager 
	   
	   // (a1) if the message is "kill" job
	   if ( !strcasecmp(packet.message, "kill") )
	   {
		// if the job is in the waiting queue
		if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") ||
		     !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_waiting") )
		{
		   // just delete the job off the queue 

		   int bit = 0;  // tells us which queue we're in
		   list<job_info>::iterator it_begin, it_end;
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") )
		   { bit = 1; it_begin = high_waiting.begin(); 
			it_end = high_waiting.end(); }
		   else
		   { it_begin = low_waiting.begin(); it_end = low_waiting.end(); }

		   while ( it_begin != it_end )
		   {
		      // found the job element
		      if ( it_begin->job_id == it_jobfind->first )
		      {
		 	 if ( bit )
			 {
		   	    // if job is interactive, need to close off the socket
			    // connection first to free up the socket descriptor
			    if ( !strcasecmp(it_begin->packet.mode, "interactive") )
				close(it_begin->sockfd);
			    high_waiting.erase(it_begin);
			 }
			 else
			 {
		   	    // if job is interactive, need to close off the socket
			    // connection first to free up the socket descriptor
			    if ( !strcasecmp(it_begin->packet.mode, "interactive") ) 
				close(it_begin->sockfd);
			    low_waiting.erase(it_begin);	 
			 }
		         break;
		      }
		      ++it_begin;
		   }

		   // update the job_find data structure
		   job_find.erase(it_jobfind);
		}
		// else, job is in running queue
		else
		{
		   // get all the information to send to the task_manager 
		   map<string, job_info>::iterator it_find;
		   
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_running") )
			it_find = high_running.find(it_jobfind->second.hostname);
		   else if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_running") )
			it_find = low_running.find(it_jobfind->second.hostname);
		 
	 	   tmpacket.job_pid = it_find->second.job_pid;
		   strcpy(tmpacket.message, "kill");

		   #ifdef DEBUG
		   cout << "tmpacket.job_pid: " << tmpacket.job_pid << " " 
			<< "tmpacket.message: " << tmpacket.message << endl; 
		   #endif

		   // need to connect to task_manager
		   connect_bit = 1;
		}
	   }  // closes off (a1)

	   // (a2) else if the message is "suspend" job
	   else if ( !strcasecmp(packet.message, "suspend") )
	   {
		// if the job is in the waiting queue
		if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") ||
		     !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_waiting") )
		{
		   list<job_info>::iterator it_begin, it_end;
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") )
		   { it_begin = high_waiting.begin(); it_end = high_waiting.end(); }
		   else
		   { it_begin = low_waiting.begin(); it_end = low_waiting.end(); }

		   while ( it_begin != it_end )
		   {
		      // found the job element
		      if ( it_begin->job_id == it_jobfind->first )
		      {
		   	 // change the status of the job to "suspend" 
			 it_begin->status = "suspend"; 
			 break;
		      }
		      ++it_begin;
		   }
		}
		// else, job is in running queue
		else
		{
		   // get all the information to send to the task_manager 
		   map<string, job_info>::iterator it_find;
		   
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_running") )
			it_find = high_running.find(it_jobfind->second.hostname);
		   else if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_running") )
			it_find = low_running.find(it_jobfind->second.hostname);
		 
	 	   tmpacket.job_pid = it_find->second.job_pid;
		   strcpy(tmpacket.message, "suspend");

		   // for now, just assume that job is suspended correctly 
		   // (change status of job to "suspend")
		   it_find->second.status = "suspend"; 

		   #ifdef DEBUG
		   cout << "tmpacket.job_pid: " << tmpacket.job_pid << " " 
			<< "tmpacket.message: " << tmpacket.message << endl; 
		   #endif

		   // need to connect to task_manager
		   connect_bit = 1;
		}
	   }

	   // (a3) else if the message is "unsuspend" job
	   else if ( !strcasecmp(packet.message, "unsuspend") )
	   {
		// if the job is in the waiting queue
		if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") ||
		     !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_waiting") )
		{
		   list<job_info>::iterator it_begin, it_end;
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") )
		   { it_begin = high_waiting.begin(); it_end = high_waiting.end(); }
		   else
		   { it_begin = low_waiting.begin(); it_end = low_waiting.end(); }

		   while ( it_begin != it_end )
		   {
		      // found the job element
		      if ( it_begin->job_id == it_jobfind->first )
		      {
		   	 // change the status of the job back to "waiting" 
			 it_begin->status = "waiting"; 
			 break;
		      }
		      ++it_begin;
		   }
		}
		// else, job is in running queue
		else
		{
		   // get all the information to send to the task_manager 
		   map<string, job_info>::iterator it_find;
		   
		   if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_running") )
			it_find = high_running.find(it_jobfind->second.hostname);
		   else if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "low_running") )
			it_find = low_running.find(it_jobfind->second.hostname);
		 
	 	   tmpacket.job_pid = it_find->second.job_pid;
		   strcpy(tmpacket.message, "unsuspend");

		   // for now, just assume that job is unsuspended correctly 
		   it_find->second.status = "running";

		   #ifdef DEBUG
		   cout << "tmpacket.job_pid: " << tmpacket.job_pid << " " 
			<< "tmpacket.message: " << tmpacket.message << endl; 
		   #endif

		   // need to connect to task_manager
		   connect_bit = 1;
		}
	   }

	   // (a4) else if the message is to change the job to high_priority
	   else if ( !strcasecmp(packet.message, "high_priority") )
	   {
		// if job is in low_waiting queue
		if ( !strcasecmp(it_jobfind->second.queue_type.c_str(),"low_waiting") ) 
		{
		   // move the job to high_waiting queue
		   list<job_info>::iterator it_begin = low_waiting.begin(),
						it_end = low_waiting.end();

		   while ( it_begin != it_end )
		   {
		      // found the job element
		      if ( it_begin->job_id == it_jobfind->first )
		      {
			 strcpy(it_begin->packet.priority, "high");
			 high_waiting.push_back(*it_begin);
			 low_waiting.erase(it_begin);
		         break;
		      }
		      ++it_begin;
		   }

		   // update the job_find data structure
		   it_jobfind->second.queue_type = "high_waiting"; 
		}
		// else if job is in low_running queue
		else if (!strcasecmp(it_jobfind->second.queue_type.c_str(), "low_running"))
		{
		   // move the job to high_running queue
		   map<string, job_info>::iterator it_find = 
			low_running.find(it_jobfind->second.hostname);

		   strcpy(it_find->second.packet.priority, "high");
		   high_running.insert( map<string, job_info>::value_type(
			it_jobfind->second.hostname, it_find->second) );

		   low_running.erase(it_find);

		   // update the job_find data structure
		   it_jobfind->second.queue_type = "high_running"; 
		} 
		// else if job is in intermediate queue
		else if (!strcasecmp(it_jobfind->second.queue_type.c_str(),"intermediate"))
		{
		   // change its priority to "high" 
		   map<string, job_info>::iterator it_find = 
			intermediate.find(it_jobfind->second.hostname);
		   strcpy(it_find->second.packet.priority, "high"); 
		}
	   }

	   // (a5) else if the message is to change the job to low_priority
	   else if ( !strcasecmp(packet.message, "low_priority") )
	   {
		// if job is in high_waiting queue
		if ( !strcasecmp(it_jobfind->second.queue_type.c_str(), "high_waiting") ) 
		{
		   // move the job to low_waiting queue
		   list<job_info>::iterator it_begin = high_waiting.begin(),
						it_end = high_waiting.end();

		   while ( it_begin != it_end )
		   {
		      // found the job element
		      if ( it_begin->job_id == it_jobfind->first )
		      {
			 // if the job is interactive, then just return (can't 
			 // change interactive jobs to low priority)
			 if ( !strcmp(it_begin->packet.mode, "interactive") )
			    return 0;
		       
			 strcpy(it_begin->packet.priority, "low");
			 low_waiting.push_back(*it_begin);
			 high_waiting.erase(it_begin);
		         break;
		      }
		      ++it_begin;
		   }

		   // update the job_find data structure
		   it_jobfind->second.queue_type = "low_waiting"; 
		}
		// else if job is in high_running queue
		else if (!strcasecmp(it_jobfind->second.queue_type.c_str(), "high_running"))
		{
		   // move the job to low_running queue
		   map<string, job_info>::iterator it_find = 
			high_running.find(it_jobfind->second.hostname);

		   // if the job is interactive, then just return (can't 
		   // change interactive jobs to low priority)
		   if ( !strcmp(it_find->second.packet.mode, "interactive") )
		      return 0;

		   strcpy(it_find->second.packet.priority, "low");
		   low_running.insert( map<string, job_info>::value_type(
			it_jobfind->second.hostname, it_find->second) );

		   high_running.erase(it_find);

		   // update the job_find data structure
		   it_jobfind->second.queue_type = "low_running"; 
		} 
		// else if job is in intermediate queue
		else if (!strcasecmp(it_jobfind->second.queue_type.c_str(), "intermediate"))
		{
		   // change its priority to "low" 
		   map<string, job_info>::iterator it_find = 
			intermediate.find(it_jobfind->second.hostname);

		   // if the job is interactive, then just return (can't 
		   // change interactive jobs to low priority)
		   if ( !strcmp(it_find->second.packet.mode, "interactive") )
		      return 0;

		   strcpy(it_find->second.packet.priority, "low"); 
		}
	   }

	   // (b) open up a connection to the task_manager and send it 
	   // the relevant information to do something to the job
	   if ( connect_bit )
	   {
	      // call tm_connect function
	      if ( tm_connect(it_jobfind->second.hostname, tmpacket) != 0 )
	      {
		 // something went wrong
		 return -1;
	      }
	   }  // closes off connection block

	   return 0;
}

int defective_server(string server)
{
   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   list<string>::iterator it_dhost = find(valid_hosts.begin(), 
 				valid_hosts.end(), server);

   // if host does not exist, this is an error 
   if (it_dhost == valid_hosts.end())
	return -1;

   // delete this server from valid_hosts
   valid_hosts.erase(it_dhost);

   // delete this server from avail_hosts (if it's in there currently)
   it_dhost = find(avail_hosts.begin(), avail_hosts.end(), server);
   if (it_dhost != avail_hosts.end())
	avail_hosts.erase(it_dhost);

   // delete this server from the communicate data structure
   map<string, sockfd5_commun>::iterator itc_find = communicate.find(server);
   if (itc_find != communicate.end())
   	communicate.erase(itc_find);

   // check the running queues and the intermediate queue to see if there is 
   // a job running on this server; if there is, delete this job from the queue
   map<string, job_info>::iterator it_jobfind;

   // Note: If batch job, need to wait on child process.  If this job
   // has confiscated any licenses, needs to unsuspend all the suspended processes.
   int batchpid = -1;

   if ((it_jobfind = high_running.find(server)) != high_running.end())
   {
	// delete the element off of job_find as well
	map<string, task_packet>::iterator it_find;
	it_find = job_find.find(it_jobfind->second.job_id);
	job_find.erase(it_find);

	// need to bury zombie process?
	if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   batchpid = it_jobfind->second.batch_pid;

	// check if we have confiscated any licenses
	if ( !it_jobfind->second.conf_license.empty() )
	{
	   // open up a connection to all the hosts in 
	   // conf_license to "unsuspend" the suspended jobs
	   map<string, conflic_packet>::iterator 
			itb = it_jobfind->second.conf_license.begin(),
			ite = it_jobfind->second.conf_license.end();

	   while ( itb != ite )
	   {
		struct tm_packet tmpacket;  // packet to send to task_manager
		tmpacket.job_pid = itb->second.job_pid; 
		strcpy(tmpacket.message, "unsuspend");

		// call tm_connect function
		if ( tm_connect(itb->first, tmpacket) == 0 )
		{
		      // update the status of the confiscated license job
		      map<string, job_info>::iterator it_jfind =
							low_running.find(itb->first);
		      it_jfind->second.status = "running";
		      it_jfind->second.confiscated = 0;  // set bit back to 0
		}

		++itb;
 	   } 
	} 
	else
	{
	   #ifdef DEBUG
	   cout << "No confiscated licenses" << endl;
	   #endif
	}

	high_running.erase(it_jobfind);
   }
   else if ((it_jobfind = low_running.find(server)) != low_running.end())
   {
  	// delete the element off of job_find as well
	map<string, task_packet>::iterator it_find;
	it_find = job_find.find(it_jobfind->second.job_id);
	job_find.erase(it_find);

	// need to bury zombie process?
	if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   batchpid = it_jobfind->second.batch_pid;

	low_running.erase(it_jobfind);
   }
   else if ((it_jobfind = intermediate.find(server)) != intermediate.end())
   {
  	// delete the element off of job_find as well
	map<string, task_packet>::iterator it_find;
	it_find = job_find.find(it_jobfind->second.job_id);
	job_find.erase(it_find);

	// need to bury zombie process?
	if ( !strcasecmp(it_jobfind->second.packet.mode, "batch") )
	   batchpid = it_jobfind->second.batch_pid;

	intermediate.erase(it_jobfind);
   }

   // need to bury zombie process?
   if ( batchpid != -1 )
   {
	// sometimes we have to manually kill off the forked off
	// queue_manager (better to do this way; otherwise,
	// waitpid will block forever waiting for the child to die)

 	// the command to get the "sh..." pid first
	char pidcmd[100];
	strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
	sprintf(pidcmd, "%s %d %s", pidcmd, batchpid,
					"| awk '{print $3}' | grep -v");
	sprintf(pidcmd, "%s %d %s %s", pidcmd, batchpid, ">", TEMPFILE);

	#ifdef DEBUG
	cout << pidcmd << endl;
	#endif

	if ( system(pidcmd) < 0 )
	   perror("Error on pidcmd system()");
	else
	{
   	   // now read in the value of the "sh" pid
   	   int sh_pid = -1;
   	   fin.open(TEMPFILE);

	   if ( !fin.bad() )
	   {
   	      fin >> sh_pid;
   	      fin.close();

   	      if ( sh_pid != -1 )
   	      {
	         char pidcmd[100];
	         strcpy(pidcmd, "ps alx | grep -v 'ps alx' | grep que | grep");
	         sprintf(pidcmd, "%s %d %s", pidcmd, sh_pid,
			"| awk '{print $3}' | grep -v");
	         sprintf(pidcmd, "%s %d %s %s", pidcmd, sh_pid, ">", TEMPFILE);

  	         if ( system(pidcmd) < 0 )
  		   perror("Error on pidcmd system()");
	         else
	         {
	            // now get the actual pid that we need to kill the job
	            int kill_pid = -1;
	            fin.open(TEMPFILE);

		    if ( !fin.bad() )
		    {
	               fin >> kill_pid;
	               fin.close();

		       #ifdef DEBUG
		       cout << "kill_pid: " << kill_pid << endl;
		       #endif
	
		       // send the process the kill signal
		       if (kill_pid > 0)
		       { 
		          kill( kill_pid, SIGTERM );  // try SIGTERM first
	 	          kill( kill_pid, SIGKILL );
		       }
		    }
	         }
   	      } // closes off "if (sh_pid..."
	   }
	}

	// now bury this child	
	waitpid(batchpid, NULL, WNOHANG);
	
	#ifdef DEBUG
	cout << "after waiting on child process" << endl;
	#endif
   }

   return 0;

}

int unsuspend_jobs(map<string, int> unsuspend_servers)
{
   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   signal(SIGPIPE, sigpipe_handler); 

   // open up a connection to the "task_manager" of every host in 
   // unsuspend_servers and send the job an "unsuspend" signal
   map<string, int>::iterator itb = unsuspend_servers.begin(),
					ite = unsuspend_servers.end();

   while ( itb != ite )
   {
	// send the packet over to the task_manager
	struct tm_packet tmpacket;  // packet to send to task_manager
	tmpacket.job_pid = itb->second; 
	strcpy(tmpacket.message, "unsuspend");

	// call tm_connect function
	if ( tm_connect(itb->first, tmpacket) == 0 )
	{
	   // update the status of the confiscated license job
	   map<string, job_info>::iterator it_jfind =
				low_running.find(itb->first);
	   it_jfind->second.status = "running";
	   it_jfind->second.confiscated = 0;  // unset confiscated bit
	}

	++itb;
   }

   return 0;
}

// checks if we can run any jobs in the waiting queues
int check_wait()
{
   	// set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   	signal(SIGPIPE, sigpipe_handler); 

	list<job_info>::iterator iter_begin, iter_end;

	for ( int i = 0; i < 2; i++ )
	{
	   int high_queue;  // denotes that we are working on the high priority queue 
 
	   // check high priority queue first
	   if ( i == 0 )
	   { iter_begin = high_waiting.begin(); iter_end = high_waiting.end(); 
	     high_queue = 1; }
	   else
	   { iter_begin = low_waiting.begin(); iter_end = low_waiting.end(); 
	     high_queue = 0; }

	   while ( iter_begin != iter_end )
	   {
	      int host_flag = 0;  // are there any hosts available?
	      list<string>::iterator it_find; // avail_hosts list iterator

	      // (a1) if job's status is "suspend," skip it
	      if ( !strcasecmp(iter_begin->status.c_str(), "suspend") )
	      {
		 ++iter_begin;
		 continue;
	      }

	      // (a) figure out what the host should be 
	      if ( !avail_hosts.empty() ) 
	      {
		 // check if user specified onlyhost 
		 if ( strcasecmp(iter_begin->packet.onlyhost, "") )
		 {
		    it_find = find(avail_hosts.begin(), avail_hosts.end(), 
							iter_begin->packet.onlyhost);    
		    if ( it_find != avail_hosts.end() )
		    {
			strcpy(assigned_host, it_find->c_str());
			host_flag = 1;
		    }
		 } 
		 // else if user specified prefhost, then see if this host is available
		 else if ( strcasecmp(iter_begin->packet.prefhost, "") )
		 {
		    host_flag = 1;
		    it_find = find(avail_hosts.begin(), avail_hosts.end(),
							iter_begin->packet.onlyhost);

		    if ( it_find != avail_hosts.end() )
			strcpy(assigned_host, it_find->c_str());
		    else
		    {
			// just get the first hostname off of the avail_hosts list
			it_find = avail_hosts.begin();
			strcpy(assigned_host, it_find->c_str());
		    }
		 }
		 // else, just get the first hostname off of the avail_hosts list
		 else
		 {
	    	    host_flag = 1;
		    it_find = avail_hosts.begin();
		    strcpy(assigned_host, it_find->c_str());			   
		 }
	      }

	      // (b) if a host is available, check if the licenses are available  
	      if ( host_flag )
	      {
	         int license_flag  = 1;  // are the licenses available?
		 map<string, int>::iterator license_iter;
  		 for ( int i = 0; i < iter_begin->license_vector.size(); i++ )
		 {
		    license_iter = avail_licenses.find(iter_begin->license_vector[i]);

		    if ( license_iter->second <= 0 )
			license_flag = 0;
		 } 

		 // (b1) if the licenses are available (we think licenses are available)
		 if ( license_flag )
		 {
		    // call the "lmleft" function to ensure that there really are licenses available
		    int license_notavail = 0;
		    map<string, string>::iterator it_licensefile;
  		    for ( int i = 0; i < iter_begin->license_vector.size(); i++ )
		    {
		       it_licensefile = license_files.find(iter_begin->license_vector[i]);
		       if (it_licensefile != license_files.end())
		       {
		          // license is really not available 
		          if ( lmleft(it_licensefile->second.c_str(), it_licensefile->first.c_str()) <= 0 )
			  {
			     license_notavail = 1;
			     break;
			  }
		       }
		    }	 

		    // if licenses are not available
		    if (license_notavail)
		    {
		       ++iter_begin;
		       continue;
		    }

		    // interactive mode: send hostname back to queue client
		    if ( !strcasecmp(iter_begin->packet.mode, "interactive") )
		    {
			// call hlavail_i function
			// (note: we stored the socket descriptor within the job element
			// itself, so we haven't closed off the connection yet)
		 	if ( hlavail_i(*iter_begin, iter_begin->sockfd, it_find) != 0 )
			{
			   close(iter_begin->sockfd);

			   // delete the job off of job_find
		   	   map<string, task_packet>::iterator it_jobfind;
		   	   it_jobfind = job_find.find(iter_begin->job_id);
			   job_find.erase(it_jobfind);
			}
			else
			{
		   	   // change the queue_type of the job element in job_find
		   	   map<string, task_packet>::iterator it_jobfind;
		   	   it_jobfind = job_find.find(iter_begin->job_id);
		   	   it_jobfind->second.queue_type = "intermediate"; 
		   	   it_jobfind->second.hostname = assigned_host; 
			}

			// delete the job off of the waiting queue

			// temp2_iter points to the next element in the queue
			list<job_info>::iterator temp1_iter = iter_begin;
			list<job_info>::iterator temp2_iter = ++temp1_iter;

			if ( high_queue == 1 )
			{
			   high_waiting.erase(iter_begin);
			
			   // update the iterators
			   iter_begin = temp2_iter;
			   iter_end = high_waiting.end();
			}
			else
			{
			   low_waiting.erase(iter_begin);

			   // update the iterators
			   iter_begin = temp2_iter;
			   iter_end = low_waiting.end();
			}

			continue; // go back to the while loop
		    }
		    // else, in batch mode
		    else
		    {
			// call hlavail_b function
			int return_val;
			if ( (return_val = hlavail_b(*iter_begin, 1, it_find)) == 1 )
			   continue; // fork failed, so job is still in waiting queue
			else if ( return_val == 0 )
			{
		   	   // change the queue_type of the job element in job_find
		   	   map<string, task_packet>::iterator it_jobfind;
		   	   it_jobfind = job_find.find(iter_begin->job_id);
		   	   it_jobfind->second.queue_type = "intermediate"; 
		   	   it_jobfind->second.hostname = assigned_host; 
			}
			else
			{
			   // delete the job off of job_find
		   	   map<string, task_packet>::iterator it_jobfind;
		   	   it_jobfind = job_find.find(iter_begin->job_id);
			   job_find.erase(it_jobfind);
			}

			// delete the job off of the waiting queue

			// temp2_iter points to the next element in the queue
			list<job_info>::iterator temp1_iter = iter_begin;
			list<job_info>::iterator temp2_iter = ++temp1_iter;

			if ( high_queue == 1 )
			{
			   high_waiting.erase(iter_begin);
			
			   // update the iterators
			   iter_begin = temp2_iter;
			   iter_end = high_waiting.end();
			} 
			else
			{
			   low_waiting.erase(iter_begin);

			   // update the iterators
			   iter_begin = temp2_iter;
			   iter_end = low_waiting.end();
			}

			 continue; // go back to the while loop
		    }
		 }
		 // (b2) if the licenses are not available
		 else
		 {
		   #ifdef CONFISCATE 
		   if ( high_queue == 1 )
		   {		   
			// call the function (if function returns 0, means that
			// everything went well; nonzero otherwise)
			if ( hl_unavail(*iter_begin, iter_begin->sockfd, 1, it_find) != 0 )
			{
			   // something went wrong
			}
		 	else
			{
			   // change the queue_type of the job in job_find
			   map<string, task_packet>::iterator mfind = job_find.find(
								iter_begin->job_id);
			   mfind->second.queue_type = "intermediate";
			   mfind->second.hostname = assigned_host;

			   // delete the job element off of the waiting queue
			   list<job_info>::iterator temp1_iter = iter_begin;
			   list<job_info>::iterator temp2_iter = ++temp1_iter;

			   high_waiting.erase(iter_begin);
	
			   // update the iterators
			   iter_begin = temp2_iter;
			   iter_end = high_waiting.end();

			   continue;  // go back to the while loop
			}
		   } 
		   #endif

		   // otherwise, the job is low_priority, so do nothing
		 }

		}
 
	      ++iter_begin;
	   }
	}

	return 0;
}

// checks if any of the queue daemons are down
int check_queued()
{
   // a temporary list to hold any servers that are down 
   list<string> downservers;

   // get the current time
   struct timeval time;
   gettimeofday(&time, NULL);

   // now iterate through each element of the communicate data structure, deleting any servers
   // where the time has expired
   map<string, sockfd5_commun>::iterator it_begin = communicate.begin(), it_end = communicate.end();
   while (it_begin != it_end)
   {
      if ( (time.tv_sec - it_begin->second.time.tv_sec) > MAXQUEUEDTIME )
         downservers.push_back(it_begin->first);

      ++it_begin;
   }

   // if the temporary list is not empty, call the defective server function
   list<string>::iterator itb = downservers.begin(), ite = downservers.end();
   while (itb != ite)
   {
      defective_hosts.push_back(*itb);
      defective_server(*itb);
      ++itb;
   }
 
   return 0;
}

// checks if there are any job messages that we can process
int check_jobmsg()
{  
   	   // set up the handler just in case we get a SIGPIPE signal (which will crash the queue_manager!)
   	   signal(SIGPIPE, sigpipe_handler); 

	   map<string, task_packet>::iterator it_jobfind;
	   list<sockfd4_packet>::iterator itb_jobmsg = job_messages.begin(),
	   					ite_jobmsg = job_messages.end();

	   while (itb_jobmsg != ite_jobmsg)
	   {
	      // find this element in job_find
	      it_jobfind = job_find.find(itb_jobmsg->job_id);

	      // if the element is not in job_find, then delete this element
	      if ( it_jobfind == job_find.end() )
	      {
	         list<sockfd4_packet>::iterator temp1_iter = itb_jobmsg;
		 list<sockfd4_packet>::iterator temp2_iter = ++temp1_iter;

		 job_messages.erase(itb_jobmsg);

		 // update the iterators
		 itb_jobmsg = temp2_iter;
		 ite_jobmsg = job_messages.end();

		 continue;
	      }
	      else
	      {
		 // if job is in the intermediate queue, then skip this job
		 if ( it_jobfind->second.queue_type == "intermediate" )
		 {
		    ++itb_jobmsg;
		    continue;
		 }
		 else 
		 {
		    // if its licenses are confiscated
		    if ( it_jobfind->second.queue_type == "low_running" )
		    {
		        map<string, job_info>::iterator iter_find =
		       				low_running.find(it_jobfind->second.hostname);
			if ( iter_find != low_running.end() )
			   if ( iter_find->second.confiscated )
			   {
			      ++itb_jobmsg;
			      continue;
			   }
		    }

		    // if got to here, means that job is not in intermediate queue and
		    // licenses are not confiscated, so call the task_control function
              	    task_control(*itb_jobmsg, it_jobfind);
		 }
	      }

	      ++itb_jobmsg;
	   }

	   return 0;
}

// creates a new job to put in the high_running queue
int create_newjob(struct sockfd3_packet packet)
{
   struct job_info temp_job;  // job_info element to insert into some queue
   struct info_packet temp_info;
   strcpy(temp_info.priority, "high");
   strcpy(temp_info.user, packet.user);
   strcpy(temp_info.datesubmit, "");
   strcpy(temp_info.job, "");
   temp_info.user_id = packet.user_id;
   strcpy(temp_info.mode, "interactive");
   temp_job.host_running = packet.hostname;
   temp_job.status = "running";
   temp_job.confiscated = 0;
   temp_job.job_pid = packet.job_pid;
   temp_job.packet = temp_info;

   // generate a random number for the job_id
   for(;;)
   {
      long int rand_num = random() % MAXJOBIDMOD;
      char uid[10]; char rnum[30];
      sprintf(uid, "%d%s", temp_job.packet.user_id, "_");
      sprintf(rnum, "%ld", rand_num);
      temp_job.job_id = uid;
      temp_job.job_id = temp_job.job_id + rnum;

      // check to make sure that job id does not exist already
      map<string, task_packet>::iterator it_find = job_find.find(temp_job.job_id);
      if ( it_find == job_find.end() )
	 break;
   }

   // insert task_job into job_find
   struct task_packet task_job; 
   task_job.uid = temp_job.packet.user_id;
   job_find.insert( map<string, task_packet>::value_type(temp_job.job_id, task_job) );

   // put job in high_running queue
   high_running.insert( map<string, job_info>::value_type(packet.hostname, temp_job) );

   return 0;
}

// moves the packet from the intermediate queue to the high_running queue
int move_job(map<string, job_info>::iterator it_find, struct sockfd3_packet packet)
{
   struct job_info temp_job;			
   temp_job = it_find->second;
   temp_job.status = "running";
   temp_job.job_pid = packet.job_pid;

   intermediate.erase(it_find);

   if  ( !strcasecmp(temp_job.packet.priority, "high") )
   {
	high_running.insert( map<string, job_info>::value_type(packet.hostname, temp_job) );

	// change the queue_type of the job element in job_find
	map<string, task_packet>::iterator it_jobfind;
	it_jobfind = job_find.find(temp_job.job_id);
	it_jobfind->second.queue_type = "high_running"; 
   }
   else
   {
   	low_running.insert( map<string, job_info>::value_type(packet.hostname, temp_job) );

	// change the queue_type of the job element in job_find
	map<string, task_packet>::iterator it_jobfind;
	it_jobfind = job_find.find(temp_job.job_id);
	it_jobfind->second.queue_type = "low_running"; 
   }

   return 0;
}

void sigpipe_handler(int)
{
   #ifdef DEBUG
   cout << "In SIGPIPE Handler" << endl;
   #endif
}

int lmleft (const char* given_licfile, const char* given_feature)
{
    char  cmd[1024];
    //------------------------------------------------------------------------------
    // Run the lmstat command and redirect the output to a temporary file.
    //------------------------------------------------------------------------------
    sprintf(cmd, "%s %s > %s", LMCMD, given_licfile, TEMPFILE);
    //printf("EXEC: %s\n", cmd);
    if (system(cmd))
    {
        fprintf(stderr, "ERROR: Command exited in error: \"%s\".\n", cmd);
        return ERR_SYS_FAILURE;
    }
    //------------------------------------------------------------------------------
    // Retreive the output from the temporary file for parsing.
    //------------------------------------------------------------------------------
    FILE* LMOUT;
    LMOUT=fopen(TEMPFILE, "r");
    if (NULL==LMOUT) {
        return ERR_NO_TMP_FILE;
    }

    int  feature_found    = 0;
    int  feature_totallic = 0;
    int  feature_inuse    = 0;
    char line[LMSTAT_MAX_LINE_SIZE];
    char feature[LMSTAT_MAX_LINE_SIZE];
    int  totallic;

    //------------------------------------------------------------------------------
    // Parse the output of the lmstat command line by line.
    //------------------------------------------------------------------------------
    while (!feof(LMOUT))
    {
        fgets(line, LMSTAT_MAX_LINE_SIZE, LMOUT);  // put next line into "line" var

        if (strstr(line, "Cannot find license file") || strstr(line, "Error getting status"))
        {
            fprintf(stderr, "ERROR: Given license file, \"%s\",  not found.\n", given_licfile);
            return ERR_NO_LM_FILE;
        }
        else if (sscanf(line, "Users of %[^:]:  (Total of %d licenses available)", feature, &totallic))
        {
            //printf("feature: %s, total licenses: %d\n", feature, totallic);
            if (feature_found) {
                break;  // This is the beginning of the listing for the next feature.
            } else if (! strcasecmp(feature, given_feature)) {
                feature_found = 1;
                feature_totallic = totallic;
            }
        }
        else if (feature_found && strstr(line, ", start "))
        {
            //printf("  in use: %s", line);
            feature_inuse++;
        }
    }
    if (fclose(LMOUT)) {
        return ERR_NO_TMP_FILE;
    }

    if (!feature_found)
    {
        fprintf(stderr, "ERROR: Given feature, \"%s\", not found.\n", given_feature);
        return ERR_NO_FEATURE;
    }
    if (feature_totallic <= 0)
    {
        fprintf(stderr, "ERROR: No available licenses for given feature, \"%s\".\n", given_feature);
        return ERR_NO_LIC_AVAIL;
    }

    //------------------------------------------------------------------------------
    // Make the return status of this script equal to the number of licenses left for use.
    //------------------------------------------------------------------------------
    int num_left = feature_totallic - feature_inuse;

    #ifdef DEBUG
    printf("NUM LICENSES LEFT: %d\n", num_left);
    #endif

    return num_left;
}

#else
main()
{
}

#endif /*NO_QUEUE_MANAGER*/