This file is indexed.

/usr/bin/taktuk is in taktuk 3.7.5-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
#!/usr/bin/perl -w

###############################################################################
#                                                                             #
#  TakTuk, a middleware for adaptive large scale parallel remote executions   #
#  deployment. Perl implementation, copyright(C) 2006 Guillaume Huard.        #
#                                                                             #
#  This program is free software; you can redistribute it and/or modify       #
#  it under the terms of the GNU General Public License as published by       #
#  the Free Software Foundation; either version 2 of the License, or          #
#  (at your option) any later version.                                        #
#                                                                             #
#  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA #
#                                                                             #
#  Contact: Guillaume.Huard@imag.fr                                           #
#           Laboratoire LIG - ENSIMAG - Antenne de Montbonnot                 #
#           51 avenue Jean Kuntzmann                                          #
#           38330 Montbonnot Saint Martin                                     #
#           FRANCE                                                            #
#                                                                             #
###############################################################################

############################################################################
###                          THIS IS TAKTUK                              ###
### In-code documentation is mostly made of comments that goes along     ###
### with the following prototypes                                        ###
### THE ORDER OF PRESENTATION IS ONLY LEXICOGRAPHIC, NO OTHER LOGIC      ###
### (except for the package settings which is placed first)              ###
### If you are looking for a good starting point, looking at the code of ###
### the package main seems a proper idea                                 ###
############################################################################

############################################################################
### CAUTION                                                              ###
### Even if the mechanics of taktuk looks able to work using a directed  ###
### acyclic graph as logical network, synchronization and messages       ###
### heavily rely on the fact that it is only a tree                      ###
############################################################################

# Some default settings for readline (otherwise painful to set)
$ENV{PERL_RL}=" o=0";

# I've got to ignore some signals that could kill TakTuk unexpectedly
$SIG{PIPE} = 'IGNORE';

###############################################
### SETTINGS                                ###
### simple constants definition, no         ###
### implementation.                         ###
###############################################

package settings;

use constant FD => 0;
use constant SOCKET => 1;
use constant USE_SOCKETPAIR => 0;

###############################################
### PROTOTYPES                              ###
###############################################

###############################################
### ARGUMENTS                               ###
### argument line options parsing           ###
###############################################

package arguments;

# Creates a terminal object for using readline
sub initialize_terminal();
# Adds arguments to the internal command line
# Only fetched arguments are parsed by this package
# the values fetched may be opened filehandles to files that contain
# arguments
sub fetch_arguments(@);
# Adds arguments line to the internal command line
sub fetch_line($);
# Undo the last issued call to get_next_stuff, use only this to undo
# arguments getting
sub restore_last_argument();
# Undo the last issued call to get_next_command, do not combine with
# restore_last_argument
sub restore_last_command();
# Sets the variable $current_command to the value of the next command
# $arguments_ended is set to 1 if there are no more command
sub get_next_command();
# Sets the variable $current_argument to the value of the next argument
# $arguments_ended is set to 1 if there are no more arguments
sub get_next_argument();
# Read new data from a given file descriptor into the associated buffer
sub read_buffer_data($);
# Remove a buffer that is no more used
sub delete_buffer($);
# Returns a pointer to the next relevant data (either an argument or a pointer
# to a buffer filled with file data)
sub get_data_buffer();
# Set the variable $current_stuff to the value of the next stuff in arguments
# The parameter is a word separator used when reading arguments for a
# file
sub get_next_stuff($);
# Returns the value of the next parameters
# $arguments_ended is set to 1 if there are no more arguments
sub get_parameters();
# Finds and skip the next command separator(s)
# It should be at the beginning of upcoming data possibly after option
# separators
sub skip_command_separator();
# Closes any opened filehandle in the internal arguments list and sets
# $arguments_ended to 1
sub terminate_arguments_parsing();
# These are routines that are registered with some of taktuk options
# Adds a file (which name is given) containing arguments to fetched arguments
sub args_file($);
# Adds machine names contained in a file (which name is given) as new remote
# peers to deploy
sub machines_file($);
# Adds a new remote peer which name is given. Also parses -[ and ]- imbrication
sub machine($);
# Adds a new remote peer which name is given. This peer will be treated as a
# gateway : that means an unnumbered node that cannot be the destination of any
# broadcast or multicast command. It match some kind of forward-only node.
# Also parses -[ and ]- imbrication
sub gateway($);
# Changes the localhost name (as viewed by taktuk)
sub localhost($);
# Sets $general::root to 0
sub not_root();
# Prints default taktuk settings
sub print_defaults();
# Prints the taktuk package exported by taktuk_perl and exits
sub print_package($);
# Prints TakTuk version
sub print_version();
# Prints TakTuk version and exits
sub print_version_quit();
# Performs registering of options accepted by taktuk and reading of environment
sub init();
# Parses and handle all arguments that are options
# I don't use GetOpt::Long because processing order is not ensured
sub parse_options();
# Checks if separators sets overlap of include characters that might break
# TakTuk command line parser
sub check_separators_integrity();
# Begins a deployment group (contextualized options and confined work-stealing)
sub begin_group();
# Ends a deployment group
sub end_group();
# Changes the dynamicity in current group
sub dynamic($);

###############################################
### COMMAND                                 ###
### command forking with pipe redirections  ###
###############################################

package command;

# Creates and bless a new command
# Arguments might include hash keys : line, read, write, error, type
# read, write and error are communication channels (fds) as viewed by the
# command : in other words, taktuk itself writes into read and reads from write
# and error
# type might either be settings::FD or settings::SOCKET depending on the nature
# of read and write
sub new (%);
# Forks a new process to execute the command line and redirects I/Os to the
# command communication channels. The parameters tells if the new command
# should change its process group or not.
sub run ($);
# Closes all opened communication channels for the command, waits for its
# completion and return its exit status
sub cleanup();
# Does a shutdown and checks the return value
sub my_shutdown($$);
# Closes one of the communication channels (read, write or error);
sub close($);
# Propagate command output upward to the deployment tree root
# Arguments are : output type and message
sub output($$);
# Returns a string message associated with an event code
sub event_msg($);

###############################################
### COMMUNICATOR                            ###
### communication server                    ###
###############################################

package communicator;

# Creates a pair of connected connectors
sub create_channel();
# Initializes data structures for the communicator before it can be used
sub init();
# Closes everything in the whole communicator
sub cleanup();
# Returns a asked set of connections ('sources', 'sinks', 'local_commands',...)
sub get_connections($);
# Returns the root connector (firt source)
sub get_root();
# Read pending data on a descriptor (second argument) of a connector (first
# argument) and process all complete messages in the connector
sub process_messages($$);
# Calls the hanler for the given coded message (second argument) coming from a
# given connector (first argument)
sub process_message($$);
# Prints output produced by a locally spawned command (root) or propagates it
# to the root (other nodes)
sub process_command_output($$);
# Propagates the input got from an opened pipe according to this pipe's message
sub process_pipe_output($$);
# Enters into the main communicator loop
sub run ();
# Signify the communicator our wish to terminate the main loop
sub terminate ();
# Adds descriptors from a given connector or command communication channels to
# descriptors that the communicator listen to
sub add_descriptors($);
# Removes a descriptor (second argument) belonging to a connector or command
# (first argument) from the descriptors listened by the communicator
sub remove_descriptor($$);
# Removes a connector or command (first argument) from the communicator
sub remove_cobidule($);
# Returns true if no connectors are uninitialized
sub no_pending_connectors();
# Adds a connector (initialized) to one of the connectors sets (sources, ...)
sub add_connector($$);
# This function should be called when a connector already added to the
# communicator completes its initialization
sub connector_initialized($);
# Used internally by remove_xxx
sub remove_from_set($);
# Removes a previously added source connector
sub remove_source($);
# Removes a previously added interpreter connector
sub remove_interpreter($);
# Removes a previously added sink connector
sub remove_sink($);
# Removes a previously added control connector
sub remove_control($);
# Removes a previously added local command
sub remove_local_command($);
# Removes a previously added pipe input
sub remove_pipe($);
# Post to the engine a write that will be processed when possible. Arguments
# are the same as in syswrite: filehandle, scalar, length and offset
sub post_write($$@);
# Post to the engine a close that will be processed after all pending writes if
# any. Argument is the command which 'read' part is to be closed (actually this
# function only applies to commands because they're the ones the user closes
# explicitely).
sub post_close($);
# post some routine (second arg) to be called with third arg as argument when
# the pending writes to the descriptor (first arg) will be completed
sub post_termination($$$);
# removes anything related to pending data for given descriptor
sub cleanup_pending_stuff($);
# performs a write attempts for pending data related to the given descriptor
sub write_pending_stuff($);
# flushes any pending writes, blocking if necessary
sub flush_pending_stuff();
# helper function for command->{'read'} closing
sub close_cobidule_read($);
# Assign the given target number (second argument) to the given command
sub assign_target($$);
# Assign the next target number to the given command
sub assign_next_target($);
# Small function that returns and array of connectors given a target and a name
# of connectors set
sub get_target_set($$);

###############################################
### CONNECTOR                               ###
### external connector code (no self        ###
### duplication)                            ###
###############################################

package connector;

# Creates an uninitialized connector
# Arguments : might include fields used by command (especially 'line' that
# will be used for most connector which are set up using an external command
# such as "ssh taktuk").
# Extra fields specific to connectors include : arguments
# This is a ref to an array of arguments that will be communicated to the
# forked taktuk engine
sub new (%);
# Reads data from a given file descriptor that should be one of the connector
# communication channels and store it to the connector buffer
# If the connector is not initialized, this function also negociate the
# initialization with the remote peer
# If the descriptor match the error channel, the text is propagated to the root
sub read_data ($);
# To be called by synchronizer to send parameters to the remote host when the
# connector has been initialized
sub send_parameters();
# Returns the next available message or the empty string if none available
sub get_message ();
# Send a message to a remote peer
# The argument is the unpacked coded message
sub send_message($);
# Either handle locally a message (second argument) or send it to the other
# side of the connector depending on the value of prefix (first argument)
sub route_file_part($$);
# Copies a file or directory (second argument) to the destination (third
# argument). The remote host will be determinated by the first argument
# (prefix). Keeps files permissions.
sub send_file($$$);
# Returns a scalar packed form of the connector
sub pack();
# Unpack a previously packed connector
sub unpack($);
# Cancels connection
sub cancel();

###############################################
### DIAGNOSTIC                              ###
### debug and error messages                ###
###############################################

package diagnostic;

# Prints misc information for error diagnostic and debugging (root)
# propagate the information upward (other nodes)
# arguments : level, error type and additionnal message
sub print_info($$$);
# Various functions built on top of print_info
# A system call just failed
sub system ();
# Debugging information
sub debug ($);
# Error
sub error ($);
# Warning
sub warning ($);
# Special
sub special ($);

###############################################
### GENERAL                                 ###
### Taktuk-wide settings                    ###
### This package contains both global       ###
### settings and some functions that do not ###
### really fit elsewhere                    ###
###############################################

package general;

# Initializes the value of some global settings
sub init();
# Tells if the current system supports the socketpair call
sub has_socketpair();
# Creates a socketpair
sub create_socketpair();
# Applies change to internal management if local node is a gateway
sub apply_gateway_restrictions();
# Expand perl variables (from this package...) contained in a given string
sub expand($%);
# Opens a file and return a type glob to its descriptor
sub open_file($);
# Loads stuff from a file and return it
sub load_file($);
# Tries to figure out what's the filename of the taktuk executable and loads it
# into $general::taktuk_code
sub load_taktuk_code();
# Extract the taktuk package from the taktuk code and stores it into
# $general::taktuk_package
sub load_taktuk_package($);
# Prints taktuk help
sub print_help();
# Prints taktuk help and exit from the program
sub print_help_quit();
# Decodes a host set into a list of host specifications
sub decode_host_set($);
# Returns the first iteration vector of the given host specification
sub first_in_host($);
# Increments a vector (first argument) related to the given host specification
# and returns the carry if any (vector was the last element if carry is 1)
sub increment_host_vector($$);
# Returns the hostname associated with the iteration vector (first argument)
# and given host specification
sub host_vector_to_value($$);
# Decodes a host set into an internal exclusion set structure
sub decode_exclusion_set($);
# Returns true if the given name (first argument) is in the exclusion set
sub in_exclusion_set($$);
# Adds a new remote host to deploy
# Arguments are : the name of the host and the arguments to the taktuk command
sub add_peer($$@);
# Unbuffered print
sub print($);
# Prints in a pretty form a tree-like structure, arguments : prefix, tree
sub print_tree($$);
# Decode a string specifying a set of intervals and transforms it to an array
# The second argument is an upper bound to use as +
sub decode_set($$);
# Encode an array of intervals into a compact string specification
sub encode_set(@);

###############################################
### HANDLERS                                ###
### messages handlers definition            ###
###############################################

package handlers;

# Associate a callback function (second argument) to a message code (first
# argument)
sub register_handler($$);
# Replaces the callback function previously associated to a message code
sub replace_handler($$);
# Returns the callback function associated to a message code
sub get_handler($);

# All these handlers are callback functions for incoming messages
# they all take three arguments : the message code, the connector from which
# the message comes and the message body

# Handler to use for message that need to wait for a particular event before
# being processed (e.g. the ready state for broadcast).
# Actually it should only be used by 'block_until_event'
sub handler_blocked($$$);
# Handler for reception of arguments for the taktuk command
sub arguments($$$);
# Handler for broadcasting a message contained in the body
# (the message is processed by all the nodes except the local one)
sub broadcast($$$);
# handler that does nothing
sub empty($$$);
# Closes all read channel of local commands
sub eof($$$);
# Handler for timeouts on executions
sub execute_timeout($);
# Execute a command on the localnode redirecting all I/Os
sub execute($$$);
# helper function to be called at the end of file reception
sub file_finalize($);
# Receives a file send from a remote node
sub file($$$);
# Propagates the message to the root
sub forward_up($$$);
# Get a file from some hosts
sub get($$$);
# Gets some information from TakTuk
sub get_info($$$);
# Input to be delivered to each local command
sub input($$$);
# Sends a signal to local commands
sub kill($$$);
# Sends a message to another node
sub message($$$);
# Compute the logical number of each remote peer given the number of the
# local node passed as argument. The total count is also passed as argument
sub numbered($$$);
# Output to be printed. Should only be processed on the root node (use
# forward_up if necessary)
sub output($$$);
# Changes an option specification
sub option($$$);
# Fetch options line to TakTuk
sub options($$$);
# Opens and add as a new source of data a pipe-like file
sub pipe($$$);
# Tell local taktuk instance its position on the command line
sub position($$$);
# Put a file to some hosts
sub put($$$);
# Ask for termination of the local node
sub quit($$$);
# Inform local node of readiness of the remote peer (used by father usually)
sub ready($$$);
# Handler for a timeout on recv call
sub recv_timeout($);
# This type of reduce count the number of deployed taktuk intance and calls
# the numbered sub once the count is completed
sub reduce_count($$$$);
# This type of reduce gather the tree structure of the deployed taktuk network
# and calls print_tree on the root
sub reduce_tree($$$$);
# This type of reduce wait for the completion of local commands on all hosts
# implied
sub reduce_wait($$$$);
# Auxiliary function intended to complete a waits by signaling the end of
# some local command
sub local_command_completed($);
# General purpose reduce mechanics. Additional handlers are defined for each
# type of reduce
sub reduce($$$);
sub reduce_status_analysis($);
sub reduce_result($$$);
# Check wether some reduces have completed or not. Should be called when a
# connection is lost : no answer will come back from the connector but it might
# have been the last waited
sub check_ongoing_reduces($);
# Give up ongoing connections and propagate the message through the other hosts
sub resign($$$);
# Sends the encapsuled message to the specified host(s) (logical number)
sub send_to($$$);
# Handler for broadcasting a message contained in the body
# (the message is processed by all the nodes including the local one)
sub spread($$$);
# Steal request
sub steal($$$);
# Function that does nothing (process a given message) but is expected to be
# strongly synchrnoized (as exec or send_to for instance)
sub synchronize($$$);
# Handler for reception of the taktuk code
sub taktuk_code($$$);
# Executes a perl interpreter already fetched with the taktuk package
sub taktuk_perl($$$);
# Numbering update failed on the current node
sub update_failed($$$);
# Wait the completion of local commands
sub wait($$$);
# Sent by recv to signal that a message is waited and possibly timeouted
sub wait_message($$$);
# Work in answer to a steal request
sub work($$$);
# register all the handlers
sub init();

###############################################
### MAIN                                    ###
### main program                            ###
###############################################

package main;

# Returns the full command name if the first argument is the prefix of exactly
# one of the following full commands names. Returns the prefix unchanged
# otherwise.
sub is_one_of($@);
# Returns a packed string of execution attributes
sub get_attributes();
# Translates a taktuk command line into internal message
# returns a message or a connector (if the message has to wait)
sub translate();
# Routine that waits the taktuk interpreter child and exits
sub terminate_interpreter();
# Forks the process into
# - a loop that process command line read from stdin
# - a process connected via stdin/out to the other process and that will
# eventually run the taktuk engine at the end of this function
sub fork_taktuk_interpreter();
# Handle a taktuk command depending on local fork or not
sub handle_message($);
# Processes batch commands remaining as arguments after options parsing
# including initial TakTuk configuration commands
sub process_commands();

# This is the only package that contains raw code that will be the main
# program for taktuk

###############################################
### OPTION                                  ###
### options management                      ###
###############################################

package option;

# Clones the given scalar or ref to hash
sub clone($);
# Adds a new option to the list of recognized options
# arguments are : short name, long name, type and ref
# Types are the following
# empty string means that the option is a boolean flag
# i means integer argument value
# f means floating point argument value
# s means string argument value
# ref is either a reference to a scalar (which is assigned the value of the
# option argument) or a reference to a function (which is called when the
# option is encountered and take the option value as argument if the option
# type is not boolean
# Optionally these arguments might be followed by a default value and a
# transfer mode
sub register($$$$@);
# Changes the value of some option
# parameters are the option name and the value
sub set($$);
# Remove the value of some option from current state
# Does not change the affected ref in TakTuk but just removes the entry from
# the current state thereby preventing its propagation to children nodes
sub unset($);
# Returns TakTuk configuration as a flat string for the command line and
# an array of other TakTuk options
sub get_config();
# Saves the current options context into an internal stack
sub push_context();
# Restores the options context saved on the top of the internal stack
sub pop_context();
# Reapplies the given option using the given internally stored value
sub apply_option($$);

use constant COMMAND_LINE => 0;
use constant MESSAGE => 1;

###############################################
### TAKTUK::SELECT                          ###
### my own implementation of select object  ###
###############################################

package TakTuk::Select;

# Creates an empty select object
sub new();
# Adds a descriptor to the set listened by the select
sub add($);
# Removes a descriptor from the select set
# Returns false if the descriptor is not in the set
sub remove($);
# select call
# as in IO::Select, returns an array of three references to arrays
sub select($$$$);
# returns the array of registered handles
sub handles();

###############################################
### TAKTUK                                  ###
### base protocol encoding                  ###
### This is also the exported package for   ###
### external communication (which explains  ###
### the name)                               ###
###############################################

package TakTuk;

# Turns autoflush on for the given filehandle
sub no_flush($);
# Unpacks stuff in a buffer begining by something packed
# Returns a couple : the unpacked stuff and the remaining of the buffer
sub unpack($);
# Packs some string so that it can be unpacked when it begining is found into
# a stream of bytes
sub pack($);
# Decode a previously coded message
sub decode($);
# Encode a message code and a message body into a single decodable string
sub encode($$);
# Same as CORE::syswrite with some error coping code
sub syswrite($$);
# Reads data from a given file descriptor and bufferizes it into a buffer
# managed by the taktuk package
sub read_data($);
# Returns the next available message for the given descriptor or the empty
# string if none available
sub get_message($);
# Find the next occurence of the required regexp (second argument) in the
# buffer associated to descriptor (first argument) and returns it
# Returns an empty string if the regexp do not match
# \n is treated as a delimiter by this function and cannot be part of the
# sequence
sub find_sequence($$);
# Returns the content of the buffer associated to a descriptor and empty it
sub flush_buffer($);
# Returns a textual description of any error that occured using send or recv
sub error_msg($);
# Sends a message to another node arguments are the node number and the message
sub send(%);
# Receive a message from another node under the form ($to, $from, $message)
sub recv(%);
# Waits for one of the given TakTuk messages. Returns its code and body
sub wait_message(@);
# Get some info from TakTuk
sub get($);
 
BEGIN {
    die "FATAL : Perl interpreter too old ($]), Taktuk require Perl >= 5.6.1\n"
        if ($] < 5.006001);
}

our $VERSION = "3.7.5";
our $VERSION_NETPROTO = 1;
our $RELEASE = sprintf "%d", q$Rev: 569 $ =~ /(\d+)/g;
# syscalls default granularity
our $read_size = 32768;
our $write_size = 32768;
our $error = undef;

# These are codes for available messages
our $action="A";
our $wait="B";
our $id="C";
our $eof="D";
our $taktuk_perl="E";
our $gateway="F";
our $get="G";
our $invalid="H";
our $info="I";
our $command_send_to="J";
our $command_message="K";
our $option="N";
our $timeout="O";
our $put="P";
our $reduce_result="Q";
our $reduce="R";
our $spread="S";
our $taktuk_code="T";
our $update_failed="U";
our $options="V";
our $wait_message="W";
our $resign="X";
our $arguments="a";
our $broadcast="b";
our $down="d";
our $execute="e";
our $file="f";
our $get_info="g";
our $input="i";
our $kill="k";
our $message="m";
our $numbered="n";
our $output="o";
our $position="p";
our $quit="q";
our $ready="r";
our $steal="s";
our $send_to="t";
our $forward_up="u";
our $work="w";
our $synchronize="x";
our $pipe="z";

# Reduce types
our $reduce_count = 'c';
our $reduce_tree = 't';
our $reduce_wait = 'w';

# State events
use constant TAKTUK_READY => 0;
use constant TAKTUK_NUMBERED => 1;
use constant TAKTUK_TERMINATED => 2;
use constant CONNECTION_FAILED => 3;
use constant CONNECTION_INITIALIZED => 4;
use constant CONNECTION_LOST => 5;
use constant COMMAND_STARTED => 6;
use constant COMMAND_FAILED => 7;
use constant COMMAND_TERMINATED => 8;
use constant UPDATE_FAILED => 9;
use constant PIPE_STARTED => 10;
use constant PIPE_FAILED => 11;
use constant PIPE_TERMINATED => 12;
use constant FILE_RECEPTION_STARTED =>13;
use constant FILE_RECEPTION_FAILED =>14;
use constant FILE_RECEPTION_TERMINATED =>15;
use constant FILE_SEND_FAILED =>16;
use constant INVALID_TARGET => 17;
use constant NO_TARGET => 18;
use constant MESSAGE_DELIVERED => 19;
use constant INVALID_DESTINATION => 20;
use constant UNAVAILABLE_DESTINATION => 21;
use constant WAIT_COMPLETE => 22;
use constant WAIT_REDUCE_COMPLETE => 23;

###############################################
### SCHEDULER                               ###
### dispatching of connectors execution     ###
###############################################

package scheduler;

# starts a new scheduling group
sub begin_group();
# terminates the current scheduling group
sub end_group();
# sets the dynamic limit of the current scheduling group
sub set_limit($);
# Starts the deployment of a connector and add it to the communicator
# the arguments are the connector and a ref to an array of its arguments
sub deploy_connector($);
# Depending on the current deployment state, deploys the connector, adds it to
# the static list of pending connectors or adds it to the dynamic list
# arguments are the connector command and a reference to an array containing
# its arguments
sub add_connector($);
# Should be called upon completion of a connector initialization
sub connector_initialized($);
# Should be called upon failure of a connector initialization
sub connector_failed($);
# Returns true if the given group has reach its maximal dynamic arity
sub at_limit($);
# Depending on the current deployment state, deploys pending connectors, send
# steal requests or does nothing
sub schedule();
# Returns true if the scheduler has nothing to do
sub is_idle();
# Sends any sendable work (connectors deployment) to the given peer (which
# should have asked for it) returns the number of connectors sent
sub send_work_to($);
# Dispatchs a received stolen connector (propagates downward last)
sub dispatch_work($);
# Handles the arrival of a new steal request from a given connector (first
# argument) using given parameters (second argument)
sub theft_handler($$);
# Send a steal request to father using the given parameter
sub send_steal_request($);
# Routine to cancel all undeployed connexions
sub resign();

###############################################
### STATS BUFFER                            ###
### storage of fixed size data buffers and  ###
### computation of statistical information  ###
###############################################

package stats_buffer;

# Creates a new data buffer of given size
sub new($$);
# Returns true if the buffer is empty
sub is_empty($);
# Adds a new value to the buffer
sub add($$);
# Computes the average of stored values
sub average($);
# Computes the minimum of stored values
sub min($);
# Computes the maximum of stored values
sub max($);

###############################################
### SYNCHRONIZER                            ###
### enforcement of causal constraints       ###
###############################################

package synchronizer;

# Checks if the current taktuk instance is ready
# ready means : father is ready and I've nothing to do
# this function also replace temporary handlers and flushes pending messages
# when changing state from not ready to ready
sub check_ready_state();
# Suspend the handling of some messages until the occurence of the given event
# (first argument). Subsenquent calls to this function using the same event
# have no effect until the occurence of the event.
sub suspend_engine_until($@);
# Should be called when a connector becomes initialized
sub initialization_complete($);
# Should be called when a connector fail to initialize
sub initialization_failed($);
# Should be called when a connector timeouts
sub initialization_timeout($);
# Blocks the set of messages (array argument) as long as the required event
# (first argument) has not been dispatched
sub block_until_event($@);
# Dispatch an event
sub dispatch_event($);
# Adds a new message to the appropriate pending queue
# Should only be used when its usual handler has been previously blocked by
# 'block_until_event'
# The message will be processed as usual at the next according 'dispatch_event'
sub add_pending_message($$$);
# Intialize messages synchronization depending on the numbering scheme
sub setup_synchronization();
# Synchronize newly deployed connector after initial deployment
sub synchronize_unnumbered_subnet();
# Should be called to block engine while waiting for completion of commands
sub set_waiting();

###############################################
### TIMER                                   ###
### time accounting & timeouts management   ###
###############################################

package timer;

# Returns current system time in seconds since Jan. 1, 1970
# Might be fractional and has the precision of gettimeofday (milliseconds)
sub current_time();
# Adds a new callback function (second argument) to be called in the given
# number of seconds (first argument, possibly fractional)
# Returns a handle to the associated timer object.
sub register($$);
# Checks is some registered timers has expired and, in such a case, calls the
# handler and removes the timer
sub check_timeouts();
# Removes an unexpired timer
sub unregister();
# Get the current lifetime of some timer
sub gettime($);
# Prints the internal info of some timer
sub print($);

###############################################
### END OF PROTOTYPES                       ###
###############################################

###############################################
### GENERAL                                 ###
###############################################

package general;
use strict; use bytes;

our $has_hostname = eval("use Sys::Hostname;1")?1:0;

our $af_unix;
our $sock_stream;
our $pf_unspec;
our $has_socket = eval('use Socket; $af_unix=AF_UNIX; $sock_stream=SOCK_STREAM;
                        $pf_unspec=PF_UNSPEC; 1')?1:0;

our $connector_command;
our $connector_timeout;
our $connector_send_files;
our $login_name;
our $host;
our $root=1;
our $taktuk_command;
our $perl_interpreter;
our $path_value;
our $self_propagate;
our $taktuk_code = undef;
our $taktuk_package = undef;
our $template;
our $redirect;

our $current_position = 0;
our $position = 0;
our $numbering_update = 0;

our %taktuk = (gateway=>0, rank=>-1, count=>-1,
               child_min=>-1, child_max=>-1, father=>-1);

sub init() {
    if ($has_hostname) {
        $host = hostname();
        chomp($host);
    } else {
        $host = "localhost";
    }
}

sub has_socketpair() {
    return settings::USE_SOCKETPAIR and $has_socket;
}

sub create_socketpair() {
    my ($fd1, $fd2);
    if (not socketpair($fd1, $fd2, $af_unix, $sock_stream, $pf_unspec)) {
        diagnostic::system;
        return ();
    } else {
        return ($fd1, $fd2);
    }
}

sub apply_gateway_restrictions() {
    if ($taktuk{gateway}) {
        foreach my $message ($TakTuk::execute,
                             $TakTuk::eof,
                             $TakTuk::file,
                             $TakTuk::get,
                             $TakTuk::input,
                             $TakTuk::kill,
                             $TakTuk::command_message,
                             $TakTuk::put,
                             $TakTuk::taktuk_perl) {
            handlers::replace_handler($message, \&handlers::empty);
        }
    }
}

sub expand($%) {
    my $string = shift;
    my $variables = "";
    my %values = @_;
    foreach my $key (keys(%values)) {
        $variables .= "$key=$values{$key} &&";
    }
    diagnostic::debug("Name $string");
    $string = `$variables echo $string`
        if $string =~ m/[\$\`]/;
    chomp($string);
    diagnostic::debug("Expanded to $string");
    return $string;
}

sub open_file($) {
    my $filename = shift;
    my $fd = undef;

    $filename = expand($filename);
    if ($filename and ($filename ne "-")) {
        if (not open $fd, $filename) {
            diagnostic::system;
            diagnostic::error("Trying to open $filename");
            $fd = undef;
        } else {
            binmode($fd) or diagnostic::system;
        }
    } else {
        if ($main::interactive) {
            diagnostic::error("Cannot load STDIN in interactive mode");
        } elsif (not $general::root) {
            diagnostic::error("Cannot load STDIN on a non root node");
        } else {
            $fd = \*STDIN;
        }
    }
    return $fd;
}

sub load_file($) {
    my $filename = shift;
    my $fd = undef;
    my $new_data;
    my $end = 0;
    my $stuff="";
    my $result;

    $fd = open_file($filename);
    return "" if (not defined($fd));
    while (not $end) {
        $result = sysread($fd, $new_data, $TakTuk::read_size);
        (diagnostic::system and $result = 0) if not defined($result);
        if ($result > 0) {
            $stuff = $stuff.$new_data;
        } else {
            $end = 1;
        }
    } 
    if ($fd != \*STDIN) {
        close $fd or diagnostic::system;
    }
    return $stuff;
}

sub load_taktuk_code() {
    if (not defined($taktuk_code)) {
        my $filename = $0;
        my $fd = undef;
        my $new_data;
        my $end = 0;
        my $result;

        if (not -r $filename) {
            $filename = `which $0`;
        }
        if ($filename) {
            if (not $fd = open_file($filename)) {
                diagnostic::error("Trying to open $filename");
                return "";
            }
        } else {
            diagnostic::error("Cannot find own taktuk executable");
            return "";
        }
        $taktuk_code = "";
        while (not $end) {
            $result = sysread($fd, $new_data, $TakTuk::read_size);
            (diagnostic::system and $result = 0) if not defined($result);
            if ($result > 0) {
                # not really more efficient...
                #$new_data =~ s/^\s*//gmo;
                #$new_data =~ s/^\#.*$//gmo;
                $taktuk_code = $taktuk_code.$new_data;
            } else {
                $end = 1;
            }
        } 
        close $fd or diagnostic::system;
    }
}

sub load_taktuk_package($) {
    my $package_name = shift;
    my $state = 0;
    my $last_pos;

    if (not defined($taktuk_package)) {
        load_taktuk_code;
        $taktuk_package = "";
        my $last_pos = 0;
        while ($taktuk_code =~ /(?=package\s+([^;\s]*)\s*;\s*$)/gmi) {
            my $pos = pos($taktuk_code);
            $taktuk_package .= substr($taktuk_code,$last_pos, $pos - $last_pos)
                if $state;
            if ($1 eq $package_name) {
                $state = 1;
            } else {
                $state = 0;
            }
            $last_pos = $pos;
        }
        $taktuk_package .= substr($taktuk_code, $last_pos) if $state;
        $taktuk_package .= "1;\n";
    }
}

sub print_help() {
    communicator::get_root->output('info', <<END_HELP);
Usage :
taktuk [ options ] [ TakTuk commands ]

If one or more commands are given, TakTuk will execute them sequentially.
Otherwise, TakTuk enter interactive mode, waiting for commands.

TakTuk commands, denoted TC, are (brackets can be replaced by any delimiter):
<set> <TC>               : sends the command to all the peers of the set
                           (see TakTuk manual for set specification syntax)
broadcast <TC>           : broadcasts TakTuk command to all the remote peers
                           not including the node initiating the broadcast
downcast <TC>            : spreads TakTuk command to all the children of the
                           node initiating the command (not including itself)
exec <param> [ command ] : executes the given shell command on the local node
                           using optional execution parameters
get [ src ] [ dest ]     : copies some file from destination node(s)
help                     : prints this help
input [ data ]           : sends input to all commands being executed locally
input data [ data ]      : same as input [ data ]
input line [ data ]      : same as input but adds a newline at the end of data
input file [ filename ]  : sends the content of a file as input
input pipe [ filename ]  : sends the content of a pipe-like file as input
input close              : closes stdin of all commands being executed locally
kill <signal>            : sends a signal to local commands processes groups
                           (signal default to 15 if not given)
network                  : prints the TakTuk deployment tree
network state            : same as network
network cancel           : cancels all ongoing connections
network renumber         : recomputes TakTuk logical numbering
network update           : updates TakTuk logical numbering if possible
option name [ value ]    : changes some TakTuk option on destination node(s)
option [ line ]          : gives TakTuk options line to destination node(s)
put [ src ] [ dest ]     : copies some local file to destination node(s)
quit                     : quit TakTuk and shutdown its logical network
synchronize <TC>         : forces the following command to wait for deployment,
                           numbering and preceding commands before executing
taktuk_perl [ args ]     : forks a perl interpreter on the local node aware of
                           the taktuk package and communication routines (see
                           manual for a description of the taktuk package which
                           contains point-to-point communication routines).
                           Similar in principle to 'exec perl args'.
                           WARNING: due to limited parser, you have to give
                           args (even if empty) and to use '--' to explicitely
                           terminate switches if any
version                  : prints TakTuk version

Deployment options:
-b, --begin-group        : starts a new deployment group
-c, --connector command  : defines the connector commands used for following
                           remote machines
-d, --dynamic limit      : turns dynamic mode on (work stealing) for all the
                           following remote machines specifications.
                           Uses limit as a maximal arity (0 = no limit).
                           A negative value for limit turns dynamic mode off.
                           Warning, currently it is a bad idea to use several
                           -d options in the same deployment group (the
                           resulting arity is not specified)
-e, --end-group          : ends a deployment group
-f, --machines-file name : name is the name of a file that contains remote
                           machines names (equivalent to several -m opions)
-l, --login name         : sets the login name for the following hosts
-m, --machine name -[ -] : name is the name of a remote host to be deployed
                           with its optional arguments between -[ and -]
-s, --self-propagate     : propagate the TakTuk executable through connectors
                           (eliminates the need for a TakTuk installation on
                           remote machines)
-z, --dont-self-propagate: turns self propagation off
-F, --args-file name     : name is the name of a file that contains options
-G, --gateway name       : name is the name of a forward only remote host to be
                           deployed. Arguments can be given as with -m
-I, --perl-interpreter   : the command to use as a perl interpreter (for
                           auto propagation mode and taktuk_perl command)
-L, --localhost name     : sets the name of localhost as viewed by TakTuk
-S, --send-files files   : send files at connection for further connections
-T, --taktuk-command com : com is the name of the TakTuk command that should
                           be used for the following hosts
-V, --path-value list    : changes the PATH value on remote hosts

Command line parsing options:
-C, --command-separator  : changes the set of characters considered as command
      separators set       separators
-E, --escape-character   : defines an escape character that protects any
      character            following character from TakTuk interpretation
-O, --option-separator   : changes the set of characters considered as option
      separators set       separators

I/O options:
-o, --output-template    : set an output template specification for one of the
      name=specification   output streams (see man for details about
                           templates). When giving only a name (without
                           specification) this disables the stream
-R, --output-redirect    : sets an output redirection for one of the output
      name=filename        streams (see man for details about output streams)

Performance tuning options:
-g, --time-granularity n : sets to n the maximal interval between timeouts
                           checks (usually checks are made more often)
-n, --no-numbering       : disable taktuk nodes numbering, speed up deployment
-t, --timeout time       : sets the timeout for connectors (0 = no timeout)
-u, --cache-limit n      : sets a limit n to the size of pending write data.
                           A negative value for n means no limit
-w, --window number      : sets initial window size to number (pipeline width)
-W, --window-adaptation  : sets the windows adaptation scheme to number
      number               (0: no adaptation, 1: experimental algorithm)

Miscellaneous options:
-M, --my                 : makes the next option local (not inherited)
-h, --help               : prints this help
-i, --interactive        : forces interactive mode afer command line parsing
-v, --version            : prints TakTuk version and exits
-P, --print-defaults     : prints default settings

Environment variables defined by TakTuk for commands execution (see man for
details about variables that change TakTuk settings):
TAKTUK_COUNT             : total number of successfully deployed nodes
TAKTUK_HOSTNAME          : hostname of the local node as given to TakTuk
TAKTUK_PIDS              : pids list of commands executed by the local TakTuk
TAKTUK_POSITION          : host position on the command line
TAKTUK_RANK              : logical number of local node (in [1..TAKTUK_COUNT])
END_HELP
}

sub print_help_quit() {
    print_help;
    $main::terminate = 1;
}

sub decode_host_set($) {
    my $host_set = shift;
    my $full_set = [];

    $host_set = "" if not defined($host_set);
    while (length($host_set)) {
        $host_set =~ m/^((?:[^[,]*(?:\[[^]]*\])?)*)(?:,(.*))?$/o;
        my $host_entry = $1;
        $host_set = defined($2)?$2:"";

        if (length($host_entry)) {
            my $set;

            $set = [];
            diagnostic::debug("Host entry $host_entry");
            while ($host_entry =~ s/^([^[]*)\[([^]]*)\](.*)$/$3/o) {
                my ($prefix, $set_spec) = ($1,$2);
                my $values;

                $values = [];
                push @$set, $prefix;
                foreach my $range (split /,/, $set_spec) {
                    # I want to be sure to comply with magical auto increment
                    $range =~ m/^([a-zA-Z]*\d*)(?:-([a-zA-Z]*\d*))?$/o;
                    my ($min, $max) = ($1,$2);

                    $max = $min if not defined($max);
                    # This is complex but necessary to ensure the iteration
                    # eventually terminates : I need to check that the iterator
                    # will reach the upper bound although it might be
                    # alphanumeric (i.e. no direct numeric comparison)
                    if (not defined($min) or (length($min) > length($max)) or
                        ((length($min) == length($max)) and ($min gt $max))) {
                        diagnostic::error("Error in set spec");
                        exit 1;
                    } else {
                        push @$values, $min, $max;
                    }
                }
                push @$set, $values;
            }
            push @$set, $host_entry;
            push @$full_set, $set if scalar(@$set);
        }
    }
    return $full_set;
}

sub first_in_host($) {
    my $host_spec = shift;
    my $range_mode = 0;
    my $result = [];

    foreach my $part (@$host_spec) {
        if ($range_mode) {
            push @$result, 0, $part->[0];
        }
        $range_mode = not $range_mode;
    }
    return $result;
}

sub increment_host_vector($$) {
    my $vector = shift;
    my $vector_index = $#$vector - 1;
    my $host = shift;
    my $host_index = $#$host - 1;
    my $carry = 1;

    while ($carry and ($vector_index >= 0)) {
        my $position = $vector->[$vector_index];
        my $value = $vector->[$vector_index+1];
        my $range = $host->[$host_index];

        if ($value eq $range->[$position+1]) {
            $position += 2;
            if ($position < $#$range) {
                $vector->[$vector_index] = $position;
                $vector->[$vector_index+1] = $range->[$position];
                $carry = 0;
            } else {
                $vector->[$vector_index] = 0;
                $vector->[$vector_index+1] = $range->[0];
            }
        } else {
            $value = "".$value;
            $value++;
            $vector->[$vector_index+1] = $value;
            $carry = 0;
        }
        $vector_index -= 2;
        $host_index -= 2;
    }
    return $carry;
}

sub host_vector_to_value($$) {
    my $vector = shift;
    my $vector_index = 1;
    my $host = shift;
    my $range_mode = 0;
    my $result = "";

    foreach my $part (@$host) {
        if ($range_mode) {
            $result .= $vector->[$vector_index];
            $vector_index += 2;
        } else {
            $result .= $part;
        }
        $range_mode = not $range_mode;
    }
    return $result;
}

sub decode_exclusion_set($) {
    my $set = decode_host_set(shift);
    my $hash = {};

    foreach my $host_spec (@$set) {
        my $index = first_in_host($host_spec);
        my $carry;

        do {
            my $name = host_vector_to_value($index, $host_spec);
            $hash->{$name} = 1;
            $carry = increment_host_vector($index, $host_spec);
        }
        while (not $carry);
    }
    return $hash;
}

sub in_exclusion_set($$) {
    my $value = shift;
    my $set = shift;

    return exists($set->{$value});
}

sub add_peer($$@) {
    my $actual_command;
    my $peer_name = shift;
    my $is_gateway = shift;
    my ($command_args, $message_args) = option::get_config;

    if ($self_propagate) {
        $actual_command = "echo $connector::connector_functional_string;".
                          "exec $perl_interpreter -- - -r ";
    } else {
        $actual_command = "exec $taktuk_command -r ";
    }
    $actual_command .= "-n " if $taktuk{rank} > -1;
    $actual_command = $actual_command.$command_args." ";
    if (defined($path_value)) {
        $actual_command = 'exec /bin/sh -c "PATH='.$path_value.
                          ';export PATH;'.$actual_command.'"';
    }
    foreach my $element (@_) {
        $message_args = $message_args.TakTuk::pack($element);
    }

    # Traversal of hosts sets to create actual connectors
    $peer_name = expand($peer_name);
    my ($set, $exclusion) = split '/', $peer_name;
    $set = decode_host_set($set);
    $exclusion = decode_exclusion_set($exclusion);
    foreach my $host_spec (@$set) {
        my $index = first_in_host($host_spec);
        my $carry;
        do {
            my $value = host_vector_to_value($index, $host_spec);
            if (not in_exclusion_set($value, $exclusion)) {
                $current_position++;
                my $position_prefix = $position?$position.".":"";
                my $connector=connector::new(
                             login     => defined($login_name)?$login_name:"",
                             peer      => $value,
                             taktuk    => $actual_command." -L '$value'",
                             arguments => $message_args,
                             position  => $position_prefix.$current_position,
                             group     => $scheduler::current_group,
                             gateway   => $is_gateway,
                             propagate => $self_propagate,
                             files     => $connector_send_files,
                             timeout   => $connector_timeout);

                diagnostic::debug("New external connector command to $value:".
                                  " $connector->{line}");
                scheduler::add_connector($connector);
            }
            $carry  = increment_host_vector($index, $host_spec);
        }
        while (not $carry);
    }
}

sub print($) {
    my $message=shift;
    TakTuk::syswrite(\*STDOUT,$message) or diagnostic::system;
}

sub print_tree($$) {
    my $prefix = shift;
    my $data = shift;

    communicator::get_root->output('info',$prefix.(shift @$data)."\n");
    foreach my $subtree (@$data) {
        print_tree($prefix."    ",$subtree);
    }
}

sub decode_set($$) {
    my $string = shift;
    my $upper_bound = shift;
    my @result = ();
    my $interval;
    my $i;

    ($interval,$string) = split /\//,$string,2;
    while (length($interval)) {
        my ($min, $plus, $max) = ($interval =~ m/^(\d+)(?:(\+)|-(\d+))?$/);
        my @replacement = ();
        my $state = 0;
        my $length = 0;

        return () if not defined($min);
        $i = $#result;
        if (not defined($max)) {
            if (defined($plus)) {
                $max = $upper_bound;
            } else {
                $max = $min;
            }
        }
        return () if ($min !~ /^\d+$/o) or ($max !~ /^\d+$/o) or
                     ($min > $max);
        while (($i > -1) and ($max < $result[$i])) {
            $i--;
            $state = 1 - $state;
        }
        unshift(@replacement, $max) if not $state;
        while (($i > -1) and ($min <= $result[$i])) {
            $i--;
            $state = 1 - $state;
            $length++;
        }
        unshift(@replacement, $min) if not $state;
        $i++;
        splice @result, $i, $length, @replacement;

        if (defined($string)) {
            ($interval,$string) = split /\//,$string,2;
        } else {
            $interval = "";
        }
    }
    for ($i=1; $i<$#result; $i+=2) {
        splice @result, $i, 2
            while (($i<$#result) and ($result[$i]+1 == $result[$i+1]));
    }
    return @result;
}

sub encode_set(@) {
    my @set = @_;
    my $result = "";

    while (scalar(@set)) {
        my $min = shift @set;
        my $max = shift @set;

        $result .= "/" if ($result);
        if (defined($max)) {
            if ($min eq $max) {
                $result .= "$min";
            } else {
                $result .= "$min-$max";
            }
        } else {
            $result .= "$min+";
        }
    }
    return $result;
}

###############################################
### OPTION                                  ###
###############################################

package option;
use strict; use bytes;

our $local_option=0;
our %handler;
our %long_name;
our %short_name;
our %type;
our %transmission_mode;
our $current_value = {};
our @current_config;
our $current_config_outdated = 1;
our @contexts = ( {} );

sub clone($) {
    my $scalar = shift;
    my $ref = ref($scalar);
    my $return_value;

    if ($ref eq 'HASH') {
        $return_value = {};
        foreach my $key (keys(%$scalar)) {
            $return_value->{$key} = clone($scalar->{$key});
        }
    } else {
        $return_value = $scalar;
    }

    return $return_value;
}

sub register($$$$@) {
    my $short = shift;
    my $long = shift;
    my $opt_type = shift;
    my $opt_handler = shift;

    $long_name{$short} = $long;
    $short_name{$long} = $short;
    $handler{$short} = $opt_handler;
    $type{$short} = $opt_type;

    if (scalar(@_)) {
        if (ref($opt_handler) eq 'CODE') {
            &$opt_handler(shift);
        } else {
            $$opt_handler = shift;
            $contexts[0]->{$short} = clone($$opt_handler);
        }
        if (scalar(@_)) {
            $transmission_mode{$short} = shift;
        }
    }
}

sub set($$) {
    my $name = shift;
    my $value = shift;
    my $key = undef;
    my $current_type;

    # Hash values with type for value following
    if ($type{$name} =~ m/^h(.)$/) {
        $current_type = $1;
        if ($value =~ m/^([^=]+)(?:=(.+))?$/) {
            $key = $1;
            $value = $2;
        } else {
            diagnostic::warning("Option $name needs a well formed key=value ".
                                "pair ($value doesn't match)");
            $value = "";
        }
    } else {
        $current_type = $type{$name};
    }

    # Check if value is well formed
    if (($current_type eq "i") and defined($value) and ($value !~ /^-?\d+$/o)) {
        diagnostic::warning("Option $name needs a numeric argument ".
                            "($value doesn't match)");
    } elsif (($current_type eq "f") and defined($value) and ($value !~
                                /^(?:\d+(?:\.\d*)?|\.\d+)$/o)) {
        diagnostic::warning("Option $name needs a floating point argument ".
                            "($value doesn't match)");
    } else {
        my $destination = $handler{$name};
        if (defined($key)) {
            if (ref($destination) eq 'CODE') {
                # Not handled (see apply_option)
                diagnostic::error("NOT EXPECTED: Found option $name with ".
                                    "code handler and hash value (key=$key)");
                &$destination($key, $value);
            } else {
                diagnostic::debug("Found option $name with scalar ".
                                  "handler and hash value (key=$key)");
                $$destination->{$key} = $value;
            }
        } else {
            if (ref($destination) eq 'CODE') {
                diagnostic::debug("Found option $name with code handler and ".
                                  "scalar value ". $value);
                &$destination($value);
            } else {
                diagnostic::debug("Found option $name with scalar ".
                                  "handler and scalar value ". $value);
                $$destination = $value;
            }
        }
        if (not $local_option) {
            if (exists($transmission_mode{$name})) {
                if ($key) {
                    $current_value->{$name} = {}
                        if not exists $current_value->{$name};
                    $current_value->{$name}->{$key} = $value;
                } else {
                    $current_value->{$name}=$value;
                }
                $current_config_outdated = 1;
            }
        } else {
            $local_option = 0;
        }
    }
}

sub unset($) {
    my $name = shift;
    my $ref = $handler{$name};

    $current_config_outdated = 1;
    if (exists($contexts[$#contexts]->{$name}) and ($#contexts > 0)) {
        $current_value->{$name} = clone($contexts[$#contexts]->{$name});
        $$ref = clone($current_value->{$name});
    } else {
        delete $current_value->{$name};
        $$ref = clone($contexts[0]->{$name});
    }
}

sub get_config() {
    if ($current_config_outdated) {
        my $command_args = "";
        my $message_args = "";

        foreach my $key (keys(%$current_value)) {
            if (exists($transmission_mode{$key})) {
                if ($transmission_mode{$key} == COMMAND_LINE) {
                    if (ref($current_value->{$key}) eq 'HASH') {
                        foreach my $field (keys(%{$current_value->{$key}})) {
                            $command_args.=" -$key$field";
                            $command_args.="=$current_value->{$key}->{$field}"
                                if defined($current_value->{$key}->{$field});
                        }
                    } else {
                        $command_args.=" -$key";
                        $command_args.="$current_value->{$key}"
                            if ($type{$key});
                    }
                } elsif ($transmission_mode{$key} == MESSAGE) {
                    if (ref($current_value->{$key}) eq 'HASH') {
                        foreach my $field (keys(%{$current_value->{$key}})) {
                            $message_args.=TakTuk::pack("-$key");
                            $message_args.=TakTuk::pack("$field".
                                (defined($current_value->{$key}->{$field})?
                                "=$current_value->{$key}->{$field}":""));
                        }
                    } else {
                        $message_args.=TakTuk::pack("-$key");
                        $message_args.=TakTuk::pack($current_value->{$key})
                            if ($type{$key});
                    }
                } else {
                    diagnostic::warning("Internal bug in get_config");
                }
            }
        }
        diagnostic::debug("Config : $command_args | ".$message_args."\n");
        @current_config = ($command_args, $message_args);
        $current_config_outdated = 0;
    }
    return @current_config;
}

sub push_context() {
    my $save = {};

    $save = clone($current_value);
    push @contexts, $save;
}

sub pop_context() {
    my $restored_context = pop @contexts;
 
    foreach my $key (keys(%{$contexts[0]})) {
        if (exists($restored_context->{$key})) {
            apply_option($key, $restored_context->{$key});
        } else {
            if (exists($current_value->{$key})) {
                apply_option($key, $contexts[0]->{$key});
            }
        }
    }
    $current_value = $restored_context;
}

sub apply_option($$) {
    my $key = shift;
    my $value = shift;
    my $ref = $handler{$key};

    if (ref($value) eq 'HASH') {
        # Here we assume that there are no hash-type options handled with a sub
        # (otherwise we would need some kind of reset routine because of the
        # meaning of default field)
        $$ref = clone($value);
    } else {
        set($key, $value);
    }
}

###############################################
### TAKTUK::SELECT                          ###
###############################################

package TakTuk::Select;
use strict; use bytes;

use constant EDESIS=>1;
use constant EDESNF=>2;
use constant EDESNS=>3;

our @select_errors = (
    "Descriptor already in set",
    "Didn't found descriptor to remove",
    "Descriptor not in set");

sub error_msg($) {
    my $error = shift;

    $error--;
    if ($error <= $#select_errors) {
        return $select_errors[$error];
    } else {
        return "Unknown error";
    }
}

sub new () {
    my $class = shift;
    my $data = { vector=>'', handles=>[] };

    bless $data, $class;
    return $data;
}

sub add ($) {
    my $self = shift;
    my $handle = shift;

    if (vec($self->{vector}, fileno($handle), 1) == 0) {
        vec($self->{vector}, fileno($handle), 1) = 1;
        push @{$self->{handles}}, $handle;
        return 0;
    } else {
        return EDESIS;
    }
}

sub remove ($) {
    my $self = shift;
    my $handle = shift;
    my $i=0;
    
    my $handles_list = $self->{handles};
    if (vec($self->{vector}, fileno($handle), 1) == 1) {
        vec($self->{vector}, fileno($handle), 1) = 0;
        while (($i <= $#$handles_list) and ($handles_list->[$i] != $handle)) {
            $i++;
        }
        if ($i <= $#$handles_list) {
            splice @$handles_list, $i, 1;
            return  0;
        } else {
            return EDESNF;
        }
    } else {
        return EDESNS;
    }
}

sub select ($$$$) {
    my $read_select = shift;
    my $write_select = shift;
    my $except_select = shift;
    my $timeout = shift;

    my $rin = defined($read_select)?$read_select->{vector}:undef;
    my $win = defined($write_select)?$write_select->{vector}:undef;
    my $ein = defined($except_select)?$except_select->{vector}:undef;
    my $rout;
    my $wout;
    my $eout;
    my ($nfound, $timeleft) =
        CORE::select($rout=$rin, $wout=$win, $eout=$ein, $timeout);

    if ($nfound == -1) {
        return ();
    } elsif ($nfound == 0) {
        return ([],[],[]);
    } else {
        my $read_set = [];
        my $write_set = [];
        my $except_set = [];
        my $handle;
        
        foreach $handle (@{$read_select->{handles}}) {
            push(@$read_set, $handle) if (vec($rout,fileno($handle),1) == 1);
        }
        foreach $handle (@{$write_select->{handles}}) {
            push(@$write_set, $handle) if (vec($wout,fileno($handle),1) == 1);
        }
        foreach $handle (@{$except_select->{handles}}) {
            push(@$except_set, $handle) if (vec($eout,fileno($handle),1) == 1);
        }
        return ($read_set, $write_set, $except_set);
    }
}

sub handles () {
    my $self=shift;
    return @{$self->{handles}};
}

###############################################
### ARGUMENTS                               ###
###############################################

package arguments;
use strict; use bytes;

our $has_readline = eval("use Term::ReadLine;1")?1:0;
our $terminal = undef;

our $command_separator;
our $option_separator;
our $escape;

use constant NONE => 0;
use constant BUFFER => 1;
use constant LINE => 2;
use constant ARGUMENT => 3;

our $arguments_ended = 1;
our $again=0;
our @arguments = ();
our $current_argument = undef;
our $current_command = undef;
our $current_command_separators = undef;
our $current_stuff = undef;
our $current_separators = undef;
our $current_separators_prefix = undef;
our $is_first_argument = 0;
our $unescaped_stuff = undef;
our $options_ended=0;

sub initialize_terminal() {
    if ($has_readline and -t \*STDIN and -t \*STDOUT) {
        $terminal = Term::ReadLine->new("TakTuk");
    }
}

sub fetch_arguments(@) {
    if (scalar(@_)) {
        unshift @arguments, @_;
        $arguments_ended = 0;
        $options_ended = 0;
    }
}

sub fetch_line($) {
    my $line = shift;
    unshift @arguments, \$line;
    $arguments_ended = 0;
    $options_ended = 0;
}

sub restore_last_argument() {
    if ($again) {
        diagnostic::warning("Cannot restore an ungeted argument");
    } else {
        $again = 1;
    }
}

sub restore_last_command() {
    if ($current_stuff) {
        $current_stuff = $current_command.$current_command_separators.
                         $current_stuff;
    } else {
        $current_stuff = $current_command;
        $current_separators = $current_command_separators.$current_separators;
    }
    restore_last_argument if not $again;
}

sub get_next_command() {
    get_next_stuff($option_separator.$command_separator);
    # if command is read from arguments, it might still contain separators
    # these are harmfull when parsing commands
    if ($current_stuff =~
                   m/^(.*?)([$option_separator.$command_separator]+)(.*)$/g)  {
        $current_command = $1;
        $current_command_separators = $2;
        $current_stuff = $3;
        restore_last_argument if length($current_stuff);
    } else {
        $current_command = $current_stuff;
        $current_command_separators = $current_separators;
        $current_stuff = "";
        $current_separators = "";
    }
    # restores command separator just in case option_separators overlap it
    if ($current_command_separators =~ m/[$command_separator]/) {
        $current_stuff = $current_command_separators.$current_stuff;
        $current_command_separators = "";
        # conditional because of the first restoration of this function
        restore_last_argument if not $again;
    }
    diagnostic::debug("Command found : [$current_command]");
    return $current_command;
}

sub get_next_argument() {
    get_next_stuff($option_separator);
    $current_argument = $current_stuff;
    diagnostic::debug("Argument found : [$current_argument]");
    return $current_stuff;
}

our %buffer;
our %end;

sub read_buffer_data($) {
    my $argument = shift;
    my $old_pos = undef;
    my $new_data;
    my $result;

    if (defined($terminal) and ($argument == \*STDIN)) {
        $new_data = $terminal->readline("");
        if (defined($new_data)) {
            $new_data .= "\n";
            $result = length($new_data);
        } else {
            $result = 0;
        }
    } else {
        $result = sysread($argument,$new_data,$TakTuk::read_size);
    }

    $old_pos = pos($buffer{$argument});
    (diagnostic::system and $result = 0) if not defined($result);
    if ($result) {
        $buffer{$argument} .= $new_data if $result;
        pos($buffer{$argument}) = $old_pos;
    } else {
        $end{$argument} = 1;
        CORE::close $argument if ($argument != \*STDIN);
    }
    return $result;
}

sub delete_buffer($) {
    my $argument = shift;

    diagnostic::warning("Bug") if not exists($end{$argument});
    delete $buffer{$argument};
    delete $end{$argument};
}
    
sub get_data_buffer() {
    my $data = undef;
    my $data_type = NONE;
    my $args_remaining = 1;

    $args_remaining = 0 if not scalar(@arguments);
    while (not defined($data) and $args_remaining) {
        my $argument = $arguments[0];

        if (ref($argument) eq 'GLOB') {
            if ($end{$argument}) {
                delete_buffer($argument);
                shift @arguments;
                $args_remaining = 0 if not scalar(@arguments);
            } else {
                $buffer{$argument} = "" if not exists($buffer{$argument});
                read_buffer_data($argument) if not length($buffer{$argument});
                if (length($buffer{$argument})) {
                    $data = \$buffer{$argument};
                    $data_type = BUFFER;
                }
            }
        } elsif (ref($argument) eq 'SCALAR') {
            if (length($$argument)) {
                $data = $argument;
                $data_type = LINE;
            } else {
                shift @arguments;
                $args_remaining = 0 if not scalar(@arguments);
            }
        } else {
            $data = \$arguments[0];
            $data_type = ARGUMENT;
        }
    }
    return ($data, $data_type);
}

sub get_next_stuff($) {
    my $separator = shift;
    my $done = 0;
    my $data = 1;
    my $data_type;

    if ($again) {
        $again = 0;
    } else {
        $current_stuff = "";
        $current_separators = "";
        $current_separators_prefix = "";
        my $data_prefix = "";

        while (not $done and defined($data)) {
            ($data, $data_type) = get_data_buffer;
            if (defined($data)) {
                if ($data_type == ARGUMENT) {
                    $current_stuff = $$data;
                    shift @arguments;
                    $is_first_argument = 1;
                    $done = 1;
                } else {
                    $$data = $data_prefix.$$data if $data_prefix;
                    $data_prefix = "";
                    my $regexp;
                    my $escape_found = 1;

                    if (defined($escape)) {
                        $regexp = qr/([$separator$escape])/;
                    } else {
                        $regexp = qr/([$separator])/;
                    }
                    while ($escape_found) {
                        $escape_found = 0;
                        if ($$data =~ m/$regexp/g) {
                            my $character = $1;

                            if (defined($escape) and ($character eq $escape)) {
                                if (pos($$data) >= length($$data)) {
                                    $data_prefix =
                                             substr $$data,length($$data)-1,1;
                                    $current_stuff .=
                                             substr $$data,0,length($$data)-1;
                                    $$data = "";
                                } else {
                                    $escape_found = 1;
                                    pos($$data) = pos($$data) + 1;
                                }
                            } else {
                                my $position = pos($$data);
                                $current_separators = $character;
                                if ($$data =~ m/\G([$separator]+)/g) {
                                    # isolates and stores terminal separators
                                    $current_separators .= $1;
                                    $position = defined(pos($$data))?
                                                    pos($$data):length($$data);
                                } else {
                                    pos($$data) = $position;
                                }
                                $current_stuff .= substr $$data, 0,
                                         $position-length($current_separators);
                                $$data = substr $$data, $position;
                                if (length($current_stuff)) {
                                    $is_first_argument = 0;
                                    $done = 1;
                                } else {
                                    $current_separators_prefix .=
                                                           $current_separators;
                                }
                            }
                        } else {
                            $current_stuff .= $$data;
                            $$data = "";
                            $done = 1 if $data_type == LINE;
                        }
                    }
                }
            }
        }
        $unescaped_stuff = $current_stuff;
        if (defined($escape)) {
            $current_stuff =~ s/$escape(.)/$1/g;
        }
        $arguments_ended = 1 if not length($current_stuff);
    }
}

sub get_parameters() {
    my $left_brace = undef;
    my $right_brace;
    my $parameters = "";
    my $end_expression;

    get_next_stuff($option_separator);
    if (length($current_stuff) != 1) {
        if (length($current_stuff)) {
            diagnostic::error("TakTuk has changed: now commands parameters ".
                "should be separated from braces in $current_stuff");
        } else {
            diagnostic::error("Missing brace in parameters");
        }
        return undef;
    }
    $left_brace = $current_stuff;
    $right_brace = $left_brace;
    if ($left_brace =~ m/[({[]/) {
        $right_brace =~ tr/({[/)}]/;
    }
    
    my $separator = $option_separator.$command_separator;
    my $last_separators = "";
    my $done = 0;

    get_next_stuff($separator);
    $current_separators_prefix =~ s/^[^$command_separator]+//;
    while (not $done) {
        if ($arguments_ended) {
            diagnostic::error("Missing closing brace or separator before ".
                              "closing brace in $parameters");
            return undef;
        } elsif (length($parameters) and ($unescaped_stuff eq $right_brace)) {
            my $remaining = $last_separators.$current_separators_prefix;
            $remaining =~ s/[^$command_separator]+$//;
            $parameters .= $remaining;
            if ($current_separators =~ /[$command_separator]/) {
                $current_stuff = $current_separators;
                $current_separators = "";
                restore_last_argument;
            }
            $done = 1;
        } elsif (length($parameters) and $is_first_argument and
              ($unescaped_stuff =~ s/^$right_brace([$separator].*)$/$1/)) {
            $current_stuff = substr $current_stuff,1;
            restore_last_argument if ($current_stuff =~ /[^$option_separator]/);
            $done = 1;
        } else {
            $parameters .= $last_separators.$current_separators_prefix.
                           $current_stuff;
            $last_separators = $current_separators;
            $last_separators = " " if not length($last_separators);
            get_next_stuff($separator);
        }
    }
    diagnostic::debug("Parameters found : [$parameters]");
    return $parameters;
}

sub skip_command_separator() {
    my $done = 0;
    my $data;
    my $data_type = NONE;

    if ($again) {
        $data = \$current_stuff;
    } else {
        ($data, $data_type) = get_data_buffer;
    }
    while (not $done and not $arguments_ended) {
        if (defined($data)) {
            if ($$data =~ s/^[$option_separator]*[$command_separator]+[$option_separator]*//) {
                $done = 1;
                shift @arguments if (not length($$data) and
                                                    ($data_type == ARGUMENT));
            } else {
                if ($$data =~ m/^[$option_separator]*$/) {
                    $$data = "";
                    shift @arguments if ($data_type == ARGUMENT);
                    ($data, $data_type) = get_data_buffer;
                } else {
                    diagnostic::warning("Missing command separator");
                    $done = 1;
                }
            }
        } else {
            $arguments_ended = 1;
        }
    }
    $again = 0 if not length($current_stuff);
}

sub terminate_arguments_parsing() {
    while (scalar(@arguments)) {
        my $argument = shift @arguments;
        CORE::close $argument if ref($argument) eq 'GLOB';
    }
    $arguments_ended = 1;
}

sub args_file($) {
    my $file = shift;
    my $file_handle = undef;
    if (not ($file_handle = general::open_file($file))) {
        $main::terminate = 1;
    } else {
        fetch_arguments($file_handle);
    }
}

sub dont_self_propagate() {
    if ($general::self_propagate) {
        option::set("s", 0);
    }
}

sub machines_file($) {
    my $file = shift;
    my $file_handle = undef;
    if (not ($file_handle = general::open_file($file))) {
        $main::terminate = 1;
    } else {
        while (my $line = <$file_handle>) {
            my ($peer_name, $comment) = split /\s+/,$line,2;
            general::add_peer($peer_name, 0) if $peer_name;
        }
        CORE::close $file_handle if $file_handle != \*STDIN;
    }
}

my $is_gateway = 0;

sub machine($) {
    my $peer = shift;
    my @peer_arguments=();

    get_next_argument;
    if ($current_argument eq "-[") {
        my $count = 1;
        while ($count and !$arguments_ended) {
            get_next_argument;
            $count-- if ($current_argument eq "-]");
            $count++ if ($current_argument eq "-[");
            push @peer_arguments, $current_argument;
        }
        if ($count) {
            diagnostic::error("Invalid -[ and -] imbrication");
            exit(1);
        } else {
            pop @peer_arguments;
        }
    } else {
        restore_last_argument;
    }
    general::add_peer($peer, $is_gateway, @peer_arguments);
    $is_gateway = 0;
}

sub gateway($) {
    $is_gateway = 1;
    machine(shift);
}

sub localhost($) {
    my $hostname = shift;
    $general::host = $hostname;
    $ENV{TAKTUK_HOSTNAME} = $hostname;
}

sub not_root() {
    if ($general::root) {
        # as soon as I know I'm not root I need a source connector for
        # the diagnostic package to work
        my $connector = connector::new(
                              write =>\*STDIN,
                              read  =>\*STDOUT,
                              type  =>settings::FD);
        # DO NOT CLOSE STDERR !!!
        # Actually some errors (such as error produced by connectors) use
        # STDERR to print a diagnostic message.
        # If I close STDERR, future forked connectors will redirect the
        # descriptor they know as STDERR wich is likely to have been reused by
        # some call to socketpair when creating the connector.
        # The result is that the connector is polluted by message which are not
        # conformant to the protocol.
        # This used to cause freeze in some parts of the taktuk deployment.
        #close(STDERR) or diagnostic::system;
        $connector->{remove_handler} = \&communicator::remove_source;
        communicator::add_connector($connector, 'sources');
        $general::root = 0;
    }
}

sub print_defaults() {
    foreach my $key (keys(%long_name)) {
        if (not (ref($handler{$key}) eq 'CODE')) {
            my $name = $long_name{$key};
            if ($type{$key} =~ m/^h.$/) {
                foreach my $field (keys(%${$handler{$key}})) {
                    my $line = uc("TAKTUK_".$name."_".$field);
                    my $value = defined(${$handler{$key}}->{$field})?
                                ${$handler{$key}}->{$field}:"";
                    $line =~ tr/-/_/;
                    communicator::get_root->output('info',
                                  $line."=".$value."\n");
                }
            } else {
                my $line = uc("TAKTUK_".$name);
                my $value = defined(${$handler{$key}})?
                            ${$handler{$key}}:"";
                $line =~ tr/-/_/;
                communicator::get_root->output('info', $line."=".$value."\n");
            }
        }
    }
    $main::terminate = 1;
}  

sub print_package($) {
    my $package_name = shift;

    general::load_taktuk_package($package_name);
    communicator::get_root->output('info',$general::taktuk_package);
    $main::terminate = 1;
}

sub print_version() {
    communicator::get_root->output('info', "TakTuk version $TakTuk::VERSION ".
             "release $TakTuk::RELEASE netproto $TakTuk::VERSION_NETPROTO\n");
}

sub print_version_quit() {
    print_version;
    $main::terminate = 1;
}

sub print_k() {
    my $source="A-Za-z0-9 ,.;:?!";
    my $dest="M-Za-z0-9 ,.;:?!A-L";
    my $line = <<END;
XmFo0zru563qFp'03mzsq4Fp6FP3Fe530zsFJ
Uzs3qpuqz54FJFDwsFp'03mzsq4GF:wsFpqF46o3qFqzF106p3q
Ym5q3uqxFJF6zqFnm44uzqFqzFo6u73qFym44urF(oqxxqFpqF7053qFs3mzp-yq3q)

Yqxmzsq,FA..sFpqF46o3qFmF6zF1q6Fp'qm6Fotm6pqFpqFymzuq3qFmFxqFpu4406p3q
505mxqyqz5HFRmu5q4Fom3myqxu4q3FxqF4u301F3q46x5mz5FmFrq6F7urHFgzqFr0u4FxmFn0zzq
5quz5qF0n5qz6qGF45011q,FxmFom3myqxu4m5u0zFqzF Fmv065mz5F6zF1q6Fp'qm6
n06uxxmz5qHFb3qxq7q,Fxq4F,q45q4FpqF;GBwsFpq4F03mzsq4Fq5F3q4q37q,Fxq4HFbqxq,F( 
o0y13u4FxmF1m35uqFnxmzotq)F5065q4Fxq4F03mzsq4GFo061q,Fxq4FqzF1q5u54Fy03oqm69Fq5
mv065q,Fxq4Fm6Fom3myqxHFO0y1xq5q,FxqFyqxmzsqFm7qoFxqF3q45qFp6F46o3qFq5Fxq4
,q45q4Fruzqyqz5Fqyuzoq4HFb035q,FmFqn6xxu5u0zF16u4Frmu5q4Fyuv05q3FBFmFDtFmFrq6
53q4Fp069GFv6426'mF0n5qzu3F6zqFo0z4u45mzoqF4u361q64qHFUxFzqF3q45qF1x64F26'm
qy105q3F(m55qz5u0zFmFxmFo0z4u45mzoqFJFxqFyqxmzsqFq1mu44u5FqzF3qr30upu44mz5)H
END

    eval "\$line =~ tr/$dest/$source/";
    communicator::get_root->output('info', $line);
    $main::terminate = 1;
}

sub init() {
    option::register("B","worksteal-behavior","hs", \$scheduler::worksteal, {
        initial => 1,
        growth  => '$last_given * 2',
        limit   => '$available / 2'
    }, option::MESSAGE);
    option::register("C","command-separator","s",
                    \$arguments::command_separator,',;\n',option::MESSAGE);
    option::register("D","debug","hi",\$diagnostic::package_level, { default=>2 },option::COMMAND_LINE);
    option::register("E","escape-character","s",\$arguments::escape,undef,
                    option::MESSAGE);
    option::register("F","args-file","s",\&args_file);
    option::register("G","gateway","s",\&gateway);
    option::register("I","perl-interpreter","s",\$general::perl_interpreter,
                    "perl",option::MESSAGE);
    option::register("L","localhost","s",\&localhost);
    option::register("M","my","",\$option::local_option);
    option::register("O","option-separator","s",
                    \$arguments::option_separator,'\s',option::MESSAGE);
    option::register("P","print-defaults","",\&print_defaults);
    option::register("R","output-redirect","hs",\$general::redirect, { "default" => ">&=1", "taktuk" => ">&=2" },
                     option::MESSAGE);
    option::register("S","send-files","s",\$general::connector_send_files,
                    "", option::MESSAGE);
    option::register("T","taktuk-command","s",\$general::taktuk_command,
                    $0,option::MESSAGE);
    option::register("V","path-value","s",\$general::path_value, undef,
                    option::MESSAGE);
    option::register("W","window-adaptation","i",\$scheduler::window_adaptation,
                    0,option::MESSAGE);
    option::register("b","begin-group","",\&begin_group);
    option::register("c","connector","s",\$general::connector_command,
                    "ssh -o StrictHostKeyChecking=no -o BatchMode=yes", 
                    option::MESSAGE);
    option::register("d","dynamic","i",\&dynamic,0,option::MESSAGE);
    option::register("e","end-group","",\&end_group);
    option::register("f","machines-file","s",\&machines_file);
    option::register("g","time-granularity","f",\$communicator::select_timeout,
                    1, option::MESSAGE);
    option::register("h","help","",\&general::print_help_quit);
    option::register("i","interactive","",\$main::forced_interactive);
    option::register("k","cook","",\&arguments::print_k);
    option::register("l","login","s",\$general::login_name, undef,
                    option::MESSAGE);
    option::register("m","machine","s",\&machine);
    option::register("n","no-numbering","",\$main::no_numbering,0,
                    option::COMMAND_LINE);
    option::register("o","output-template","hs",\$general::template, {
        default   => '"$host-$rank: $command ($pid): $type > $line\n"',
        connector => '"$host: $peer ($pid): $type > $line\n"',
        info      => '"$line$eol"',
        state     => '($line == TakTuk::CONNECTION_FAILED)?'.
                     '"$host: $peer ($pid): $type > ".'.
                     'event_msg($line)."\n":undef',
        status    => '"$host-$rank: $command ($pid): $type > ".
           "Exited with status $line\n"',
           # The following is only available when using POSIX package
           #  (WIFEXITED($line)?"Exited with status ".WEXITSTATUS($line)
           # :(WIFSIGNALED($line)?"Signaled with signal ".WTERMSIG($line)
           # :(WIFSTOPPED($line)?"Stopped with signal ".WSTOPSIG($line)
           # :"")))."\n"',
        taktuk    => '"[ TAKTUK $level_name ] $host (PID $pid) Line ".
            "$line_number ($package) Release $release\n$line\n"',
        message   => '"$host-$rank: message from $from: $line\n"'
    }, option::MESSAGE);
    option::register("p","print-package","s",\&print_package);
    option::register("r","not-root","",\&not_root);
    option::register("s","self-propagate","",\$general::self_propagate,
                    0,option::MESSAGE);
    option::register("t","timeout","f",\$general::connector_timeout,0,
                    option::MESSAGE);
    option::register("u","cache-limit","i",\$communicator::cache_limit,
                    -1, option::MESSAGE);
    option::register("v","version","",\&print_version_quit);
    option::register("w","window","i",\$scheduler::window, 10, option::MESSAGE);
    option::register("z","dont-self-propagate","",\&dont_self_propagate);

    foreach my $full_name (keys(%ENV)) {
        my $variable;
        if ($full_name =~ m/^TAKTUK_(MY_)?(.+)$/) {
            $option::local_option = $1?1:0;
            $variable = $2;
        } else {
            undef($variable);
        }
        if (defined($variable)) {
            my $prefix;
            my $qualifier;

            $variable = lc($variable);
            $variable =~ m/^(.*?)(?:_([^_]+))?$/;
            ($prefix, $qualifier) = ($1, $2);
            $prefix =~ tr/_/-/;
            if (defined($qualifier)) {
                if (exists($short_name{$prefix})) {
                    my $short = $short_name{$prefix};
                    option::set($short, "$qualifier=$ENV{$full_name}");
                } else {
                    $prefix .= "-$qualifier";
                    $qualifier = undef;
                }
            }
            if (not defined($qualifier)) {
                if (exists($short_name{$prefix})) {
                    my $short = $short_name{$prefix};
                    option::set($short, $ENV{$full_name});
                } else {
                    diagnostic::warning("Unknown setting $full_name");
                }
            }
        }
        $option::local_option = 0;
    }
}
                    
sub parse_options() {
    get_next_argument();

    while (not $options_ended) {
        if ($current_argument =~ s/^-//o) {
            my @names;

            if ($current_argument =~ s/^-(.*)$//o) {
                my $name = $1;
                if ($name) {
                    my $short = $short_name{$name};
                    if (not defined($short)) {
                        diagnostic::warning("Unknown long option $name");
                        general::print_help_quit if ($general::root);
                    } else {
                        $current_argument = $short;
                    }
                } else {
                    $options_ended = 1;
                }
            }
      
            while ($current_argument) {
                $current_argument =~ s/^(.)//o;
                my $name = $1;
      
                if (exists($type{$name})) {
                    if ($type{$name}) {
                        get_next_argument if not length $current_argument;
                        if ($arguments_ended) {
                            diagnostic::error("Missing argument")
                        } else {
                            option::set($name, $current_argument);
                        }
                        $current_argument = "";
                    } else {
                        option::set($name, 1);
                    }
                } else {
                    diagnostic::warning("Unknown short option $name");
                    general::print_help_quit if ($general::root);
                }
            } 
            get_next_argument;
        } else {
            # As a special case, the empty option might appear when using
            # custom option separator characters
            if (($current_argument =~ m/^\s*$/) and not $arguments_ended) {
                get_next_argument;
            } else {
                $options_ended=1;
                restore_last_argument if ($current_argument !~ m/^\s*$/);
            }
        }
    }
    check_separators_integrity();
}

sub check_separators_integrity() {
    diagnostic::warning("Options and command separators intersect")
        if ($option_separator =~ m/[$command_separator]/) or
           ($command_separator =~ m/[$option_separator]/);
    my $chaine =
        "-/0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    diagnostic::warning("Options or command separators contain one of :".
                        "-/1-9a-zA-Z")
        if ($chaine =~ m/[$command_separator]/) or
           ($chaine =~ m/[$option_separator]/);
}

sub begin_group() {
    scheduler::begin_group;
    option::push_context;
}

sub end_group() {
    option::pop_context;
    scheduler::end_group;
}

sub dynamic($) {
    scheduler::set_limit(shift);
}

###############################################
### DIAGNOSTIC                              ###
###############################################

package diagnostic;
use strict; use bytes;

our $package_level;
our $depth = 0;
our $level="";
our $level_name="";
our $package="";
our $filename="";
our $line_number="";
our $special_enabled=0;

sub print_info($$$) {
    $level = shift;
    $level_name = shift;
    ($package, $filename, $line_number) = caller(1);

    my $level_ok = defined($package_level->{$package})?
                   $package_level->{$package}<=$level:
                   $package_level->{default}<=$level;
    # depth is here to avoid infinite recursion when calling print_info from
    # the code executed by print_info (this is the case for instance when
    # debugging the send_message sub)
    $depth++;
    if ($level_ok and ($depth < 3)) {
        communicator::get_root->output('taktuk',shift);
    }
    $depth--;
}

sub system () {
    print_info(3,"ERROR : SYSTEM", "Error $!");
}

sub debug ($) {
    print_info(1,"DEBUG", shift);
}

sub error ($) {
    print_info(3,"ERROR", shift);
}

sub warning ($) {
    print_info(2,"WARNING", shift);
}

sub special ($) {
    print_info(3, "SPECIAL", shift) if $special_enabled;
}

###############################################
### TAKTUK                                  ###
###############################################

package TakTuk;
use strict; use bytes;

our %buffer;

sub no_flush($) {
    my $new_fd = shift;
    binmode($new_fd);
    my $old_fd=select($new_fd);
    $|=1;
    select($old_fd);
}

sub unpack($) {
    my $buffer = shift;

    if (length($buffer) >= 4) {
        my $size;
        ($size) = CORE::unpack("N",$buffer);
        if (length($buffer) >= $size+4) {
            return (substr($buffer, 4, $size), substr($buffer, $size+4));
        } else {
            return (undef, $buffer);
        }
    } else {
        return (undef, $buffer);
    }
}

sub pack($) {
    my $full_message = shift;
    my $size = length($full_message);
    return CORE::pack("N",$size).$full_message;
}

sub decode($) {
    my $message = shift;
    my $message_code = substr($message, 0, 1);
    my $body = substr($message, 1);
    return ($message_code, $body);
}

sub encode($$) {
    my $message = shift;
    my $body = shift;
    return ($message).($body);
}

sub syswrite ($$) {
    my $unrecoverable = 0;
    my $write_fd = shift;
    my $full_message = shift;
    my $result;
    my $total_expected = length($full_message);
    my $call_expected = $write_size;
    my $offset = 0;

    while ($total_expected and not $unrecoverable) {
        $call_expected = $total_expected if $call_expected > $total_expected;
        $result =
            CORE::syswrite($write_fd, $full_message, $call_expected, $offset);
        if ($result) {
            $total_expected -= $result;
            $offset += $result;
        } else {
            if ($!{EAGAIN}) {
                # In this case the ressource is temporarily unavailable
                # This happens on a heavily loaded system in which too many
                # writes are pending
                # Here there are two options :
                # 1) we sleep for some time loosing potential write
                # opportunities
                # 2) we make another try right now potentially overloading the
                # system
                # In any case the message server is blocked and it would be
                # better to find another solution
                #print STDERR "Delayed write ... $total_expected more to go";
                #sleep 1;
            } else {
                # This is more serious, here we probably eventually end badly
                print STDERR "Unrecoverable write error\n";
                $unrecoverable = 1;
                # I guess we should end up even more badly by killing any child
                # connector (to avoid partially deployed crashed instances)
            }
        }
    }
    if ($unrecoverable) {
        return undef;
    } else {
        return 1;
    }
}

sub read_data ($) {
    my $descriptor = shift;
    my $new_data;

    my $result = sysread($descriptor, $new_data, $read_size);
    return undef if not defined($result);

    if ($result and exists($buffer{$descriptor})) {
        $buffer{$descriptor} .= $new_data;
    } else {
        $buffer{$descriptor} = $new_data;
    }
    return $result;
}

sub get_message ($) {
    my $descriptor = shift;

    if (exists($buffer{$descriptor})) {
        my ($message, $new_buffer) = TakTuk::unpack($buffer{$descriptor});

        if (defined($new_buffer)) {
            $buffer{$descriptor} = $new_buffer;
        } else {
            delete($buffer{$descriptor});
        }
        if (defined($message)) {
            return $message;
        } else {
            return "";
        }
    } else {
        return "";
    }
}

sub find_sequence($$) {
    my $descriptor = shift;
    my $sequence = shift;
    my $found = undef;

    if (exists($buffer{$descriptor})) {
        my $position;

        $position = index($buffer{$descriptor},"\n");
        while (($position >= 0) and not defined($found)) {
            my $string;

            $string = substr($buffer{$descriptor}, 0, $position);
            $buffer{$descriptor} = substr($buffer{$descriptor}, $position+1);
            if ($string =~ m/($sequence)/) {
                $found = $1;
            } else {
                $position = index($buffer{$descriptor},"\n");
            }
        }
    }
    return defined($found)?$found:"";
}

sub flush_buffer($) {
    my $descriptor = shift;

    if (exists($buffer{$descriptor})) {
        my $result = $buffer{$descriptor};
        delete($buffer{$descriptor});
        return $result;
    } else {
        return "";
    }
}

our $control_channel_read;
our $control_channel_write;

if ($ENV{TAKTUK_CONTROL_READ}) {
    open($control_channel_read, "<&=". $ENV{TAKTUK_CONTROL_READ})
        or print("Error opening taktuk control channel : $!\n");
    binmode($control_channel_read);
}
if ($ENV{TAKTUK_CONTROL_WRITE}) {
    open($control_channel_write, ">&=". $ENV{TAKTUK_CONTROL_WRITE})
        or print("Error opening taktuk control channel : $!\n");
    no_flush($control_channel_write);
}

use constant ESWRIT=>1;
use constant EFCLSD=>2;
use constant ESREAD=>3;
use constant EARGTO=>4;
use constant EARGBD=>5;
use constant ETMOUT=>6;
use constant EINVST=>7;
use constant EINVAL=>8;
use constant ENOERR=>9;

our @taktuk_errors = (
  '"TakTuk::syswrite failed, system message : $!"',
  '"TakTuk engine closed the communication channel"',
  '"sysread error, system message : $!"',
  '"field \"to\" not defined"',
  '"field \"body\" not defined"',
  '"timeouted"',
  '"invalid destination set specification"',
  '"invalid field required in get"',
  '"no error"'
);
  

sub error_msg($) {
    my $error = shift;

    $error--;
    if ($error <= $#taktuk_errors) {
        return eval($taktuk_errors[$error]);
    } else {
        return "Unknown error";
    }
}

sub send(%) {
    my %argument = @_;
    my $from = $ENV{TAKTUK_RANK};
    my $target;

    if (not exists($argument{to})) {
        $error=EARGTO;
        return undef;
    }
    my $to = $argument{to};
    if (not exists($argument{body})) {
        $error=EARGBD;
        return undef;
    }
    my $body = $argument{body};
    if (not exists($argument{target})) {
        $target = "any";
    } else {
        $target = $argument{target};
    }

    my $full_message = TakTuk::encode($TakTuk::send_to,
                                  TakTuk::pack($to).
                                  TakTuk::encode($TakTuk::message,
                                  TakTuk::pack($target).
                                  TakTuk::pack($from).
                                  $body));
    my $result = TakTuk::syswrite($control_channel_write,
                                  TakTuk::pack($full_message));
    $error=ESWRIT if not $result;
    return $result?$result:undef;
}

sub recv(%) {
    my %argument = @_;
    my $result;
    my $message;

    # Notification of the recv to the server
    # Necessary in all cases as a timer should not be created if a message is
    # already there (we have to count waiters internally)
    if (exists($argument{timeout})) {
        $message = TakTuk::encode($TakTuk::wait_message, $argument{timeout});
    } else {
        $message = $TakTuk::wait_message;
    }
    $result = TakTuk::syswrite($control_channel_write,TakTuk::pack($message));
    if (not $result) {
        $error=ESWRIT;
        return ();
    }

    # Now we actually get the message
    my $message_code;
    ($message_code,$message) = wait_message($TakTuk::timeout,$TakTuk::message);

    if (defined($message_code)) {
        my $from;
        if ($message_code eq $TakTuk::timeout) {
            $error=ETMOUT;
            return ();
        }
        ($from, $message) = TakTuk::unpack($message);

        return ($from, $message);
    } else {
        return ();
    }
}

our @messages;

sub wait_message(@) {
    my @codes = @_;
    my ($code, $body);
    my $result = 1;
    my $message;

    for (my $i=0; $i<$#messages; $i+=2) {
        foreach my $message_code (@codes) {
            if ($messages[$i] eq $message_code) {
                ($code, $body) = ($messages[$i], $messages[$i+1]);
                splice @messages, $i, 2;
                return ($code, $body);
            }
        }
    }
    while ($result) {
        $message = get_message($control_channel_read);
        while ($message) {
            ($code, $body) = TakTuk::decode($message);
            foreach my $message_code (@codes) {
                return ($code, $body) if ($message_code eq $code);
            }
            push @messages, $code, $body;
            $message = get_message($control_channel_read);
        }
        $result = read_data($control_channel_read);
    }
    if (defined($result)) {
        $error=EFCLSD;
    } else {
        $error=ESREAD;
    }
    return ();
}

sub get($) {
    my $result;
    my $message;

    # Infos query
    $message = TakTuk::encode($TakTuk::get_info, shift);
    $result = TakTuk::syswrite($control_channel_write,TakTuk::pack($message));
    if (not $result) {
        $error=ESWRIT;
        return -1;
    }

    # Now we actually get the message
    my $message_code;
    ($message_code,$message) = wait_message($TakTuk::info,$TakTuk::invalid);

    if (defined($message_code)) {
        if ($message_code eq $TakTuk::invalid) {
            $error=EINVAL;
            return -1;
        } else {
            $error=ENOERR;
        }
        return $message;
    } else {
        return -1;
    }
}

###############################################
### COMMAND                                 ###
###############################################

package command;
use strict; use bytes;
use Fcntl;

sub new (%) {
    my $data = { @_ };
    if (exists($data->{line}) and
        (exists($data->{read}) or exists($data->{write}) or
         exists($data->{error}) or exists($data->{type}))) {
        diagnostic::error("Command built from both a command line and fds");
    }
    bless($data);
    return $data;
}

sub run ($) {
    my $self=shift;
    my $command=shift;
    my ($father_read,$father_write,$father_error);
    my ($child_read,$child_write,$child_error);

    # Creates communication channel
    undef($father_read);
    undef($father_write);
    undef($child_read);
    undef($child_write);
    if (general::has_socketpair) {
        ($father_read, $child_read) = general::create_socketpair();
        return 0 unless defined($father_read) and defined($child_read);
        $father_write = $father_read;
        $child_write = $child_read;
        $self->{type} = settings::SOCKET;
    } else {
        if (not pipe($child_read, $father_read)) {
            diagnostic::system;
            return 0;
        }
        if (not pipe($father_write, $child_write)) {
            diagnostic::system;
            return 0;
        }
        $self->{type} = settings::FD;
    }
    undef($father_error);
    undef($child_error);
    if (not pipe($father_error,$child_error)) {
        diagnostic::system;
        return 0;
    }

    # Creates a control channel if this is a new command
    # Be sure to store the control side in a persistent place, otherwise
    # Perl frees it and closes the descriptors !!!
    my ($taktuk_side, $command_side);
    if ($command) {
        ($taktuk_side, $command_side) = communicator::create_channel;
        if (defined($command_side)) {
            $taktuk_side->{pending_messages} = 0;
            $taktuk_side->{remove_handler} = \&communicator::remove_control;
            communicator::add_connector($taktuk_side, 'control');
            $self->{control} = $taktuk_side;
        } else {
            # Annoying, without control channel half of the functionnalities
            # are missing...
            diagnostic::error("Degradated mode (no control channel)");
        }
    }

    # Fork a new process to execute the connector command
    $self->{start_date} = timer::current_time;
    my $pid;
    $pid = fork;
    if (not defined($pid)) {
         diagnostic::system;
         return 0;
    }
    $self->{pid} = $pid;
    $communicator::c_from_pid{$pid} = $self;
    if ($pid) {
        # father
        diagnostic::debug("New child with pid $pid created".
                     " to execute $self->{line}");
        CORE::close($child_read) or diagnostic::system;
        (CORE::close($child_write) or diagnostic::system)
            unless general::has_socketpair;
        CORE::close($child_error) or diagnostic::system;
        $self->{read} = $father_read;
        $self->{write} = $father_write;
        $self->{error} = $father_error;
        return $self;
    } else {
        # We create a new grp to be able to kill the command and its
        # subprocesses (if any)
        setpgrp(0,0) or diagnostic::system;
        # child
        if ($command) {
            # in this case, this is a command, we have to maintain control
            $ENV{TAKTUK_CONTROL_READ} = fileno($command_side->{write});
            $ENV{TAKTUK_CONTROL_WRITE} = fileno($command_side->{read});
            fcntl($command_side->{read}, F_SETFD, 0) or die $!;
            fcntl($command_side->{write}, F_SETFD, 0) or die $!;
        }
        CORE::close($father_read) or die $!;
        (CORE::close($father_write) or die $!)
            unless general::has_socketpair;
        CORE::close($father_error) or die $!;
        open(STDIN,"<&".fileno($child_read)) or die $!;
        open(STDOUT,">&".fileno($child_write)) or die $!;
        open(STDERR,">&".fileno($child_error)) or die $!;
        CORE::close($child_read) or die $!;
        CORE::close($child_error) or die $!;
        exec($self->{line}) or die "Exec failed : $!";
    }
}

sub cleanup() {
    my $self = shift;
    foreach my $part ('read','write','error') {
        if (exists $self->{$part}) {
            #diagnostic::warning("$part still exists at connector termination");
            #diagnostic::warning("Connector details ".join(' ', %$self));
            $self->close($part);
        }
    }
}

sub my_shutdown($$) {
    my $fd = shift;
    my $how = shift;
    if (not shutdown($fd,$how)) {
        # Socket was already disconnected ? could be worse
        diagnostic::system if not $!{ENOTCONN};
    }
}

sub close($) {
    my $self=shift;
    my $part=shift;

    if ($part eq 'error') {
        if (exists($self->{error})) {
            TakTuk::flush_buffer($self->{error});
            CORE::close($self->{error}) or diagnostic::system;
            delete $self->{error};
        } else {
            diagnostic::debug("Cannot close error : does not exists");
        }
    } else {
        if (exists($self->{type}) and exists($self->{$part})) {
            if ($self->{type} == settings::FD) {
                TakTuk::flush_buffer($self->{write}) if $part eq 'write';
                # here we close a simple fd (e.g. read or write from stdin/out)
                CORE::close($self->{$part}) or diagnostic::system;
                delete $self->{$part};
            } elsif ($self->{type} == settings::SOCKET) {
                if ($part eq 'read') {
                    # finished writing to read channel of child command
                    my_shutdown($self->{read},1);
                    delete $self->{read};
                } elsif ($part eq 'write') {
                    TakTuk::flush_buffer($self->{write});
                    # finished reading from write channel of child command
                    my_shutdown($self->{write},0);
                    delete $self->{write};
                } else {
                    diagnostic::warning("Invalid part for socket close");
                }
            } else {
                diagnostic::warning("Unknown command type : BUG");
            }
        } else {
            # We do not want of a warning if things come from several
            # successive eof
            diagnostic::warning("Closing a non existant command type or part")
                unless (exists($self->{type}) and ($part eq 'read'));
        }  
    }
}

sub output($$) {
    my $self = shift;
    my $type = shift;
    my $message = shift;
    my $template;
    my $fd;

    if (exists($general::template->{$type})) {
        $template = $general::template->{$type};
    } else {
        $template = $general::template->{default};
    }
    if (exists($general::redirect->{$type})) {
        $fd = $general::redirect->{$type};
    } else {
        $fd = $general::redirect->{default};
    }
    if (defined($template)) {
        my $command = exists($self->{line})?$self->{line}:"";
        my $count = $general::taktuk{count};
        my $filename = $diagnostic::filename;
        my $host = $general::host;
        my $level = $diagnostic::level;
        my $level_name = $diagnostic::level_name;
        my $line_number = $diagnostic::line_number;
        my $package = $diagnostic::package;
        my $peer = exists($self->{peer})?$self->{peer}:"";
        my $peers_given = exists($self->{given_list})?$self->{given_list}:"";
        my $peer_position = exists($self->{position})?$self->{position}:"";
        my $pid = exists($self->{pid})?$self->{pid}:$$;
        my $position = $general::position;
        my $rank = $general::taktuk{rank};
        my $release = $TakTuk::RELEASE;
        my $version = $TakTuk::VERSION;
        my $netproto = $TakTuk::VERSION_NETPROTO;
        my $start_date = exists($self->{start_date})?$self->{start_date}:"";
        my $stop_date = exists($self->{stop_date})?$self->{stop_date}:"";
        my $reply_date = exists($self->{reply_date})?$self->{reply_date}:"";
        my $init_date = exists($self->{init_date})?$self->{init_date}:"";
        my $from = $handlers::from;

        my $line;
        my $eol;
        my $to_be_sent = "";

        pos($message) = 0;
        while ($message =~ /\G([^\n]*)(\n|$)/go) {
            $line = $1;
            $eol = $2;
            if (length($line) or length($eol)) {
                my $result = eval("no strict 'vars'; $template");
                $to_be_sent .= $result if defined($result) and length($result);
            }
        }
        if (length($to_be_sent)) {
            communicator::process_message($self,
                TakTuk::encode($TakTuk::forward_up,
                    TakTuk::encode($TakTuk::output,
                        TakTuk::pack($fd).$to_be_sent)));
        }
    }
}

our @event_messages = (
"TakTuk is ready",
"TakTuk is numbered",
"TakTuk is terminated",
"Connection failed",
"Connection initialized",
"Connection lost",
"Command started",
"Command failed",
"Command terminated",
"Numbering update failed",
"Pipe input started",
"Pipe input failed",
"Pipe input terminated",
"File reception started",
"File reception failed",
"File reception terminated",
"File send failed",
"Invalid target",
"No target",
"Message delivered",
"Invalid destination",
"Destination not available anymore",
"Local wait complete",
"Wait of all instances complete"
);

sub event_msg($) {
    my $event = shift;

    if (($event < 0) or ($event > $#event_messages)) {
        return "Unknown event code";
    } else {
        return $event_messages[$event];
    }
}

###############################################
### CONNECTOR                               ###
###############################################

package connector;
use strict; use bytes;
use File::Basename;

our @ISA=qw(command);
our $init_string="Taktuk initialization, version ";
our $connector_functional_string="Taktuk connector functional";
# It is important to keep the temporal total order on state
# as it will be used later
our $pre_load=1;
our $simple_connector=2;
our $initialized=3;

sub new (%) {
    my $data=command::new(@_,
             data_handler=>\&communicator::process_messages);
    return 0 if not $data;
    $data->{given} = [];
    $data->{last_given} = 0;
    $data->{count} = 0;
    $data->{pending_results} = {};
    if (exists($data->{peer})) {
        if ($data->{propagate}) {
            $data->{state}=$pre_load;
        } else {
            $data->{state}=$simple_connector;
        }
        my $command_line = $general::connector_command;
        $command_line .= " -l $data->{login}" if ($data->{login});
        $data->{line} = "$command_line $data->{peer} '$data->{taktuk}'";
    } else {
        $data->{state} = $initialized;
    }
    bless($data);
    return $data;
}

sub read_data ($) {
    my $self = shift;
    my $descriptor = shift;

    my $result = TakTuk::read_data($descriptor);
    (diagnostic::system and $result = 0) if not defined($result);

    #diagnostic::debug("Data read @TakTuk::buffer");
    my $write = undef;
    my $error = undef;
    $write = $self->{write} if exists $self->{write};
    $error = $self->{error} if exists $self->{error};

    if ($write and ($descriptor == $write)) {
        if (($result >0) and not $self->{timeouted}) {
            if ($self->{state} < $initialized) {
                my $argument = 0;

                $self->{reply_date} = timer::current_time
                    unless exists($self->{reply_date});
                if ($self->{state} == $pre_load) {
                    if (length(TakTuk::find_sequence($descriptor,
                                   ".*$connector_functional_string"))) {
                        $argument = 1;
                    }
                } elsif ($self->{state} == $simple_connector) {
                    my $sequence = TakTuk::find_sequence($descriptor,
                                       ".*$init_string"."[0-9]+[.0-9]*");
                    if (length($sequence)) {
                        $argument = $sequence;
                        $argument =~ s/.* (.*)$/$1/o;
                    }
                } else {
                    diagnostic::warning("Wrong connector state : ".
                                        $self->{state});
                }
                    
                if ($argument > 0) {
                    my $connector_input = $self->{read};

                    if ($self->{state} < $simple_connector) {
                        general::load_taktuk_code;
                        communicator::post_write($connector_input,
                            $general::taktuk_code) or diagnostic::system;
                    } else {
                        diagnostic::warning("Protocol versions do not match")
                            if $argument != $TakTuk::VERSION_NETPROTO;
                    }

                    $self->{state} += 1;
                    diagnostic::debug("Connector $self->{line} promoted to ".
                                      "state ".$self->{state});
                    synchronizer::initialization_complete($self)
                        if ($self->{state} == $initialized);
                }
            }
        }
    } elsif ($error and ($descriptor == $error)) {
        if ($result >0) {
            my $new_data = TakTuk::flush_buffer($descriptor);
            $self->output('connector', $new_data);
        } 
    } else {
        diagnostic::warning("Unknown descriptor");
    }
    return $result;
}

sub send_parameters() {
    my $self = shift;

    if ($self->{propagate}) {
        general::load_taktuk_code;
        $self->send_message(TakTuk::encode($TakTuk::taktuk_code,
                                           $general::taktuk_code));
    }
    $self->send_message(TakTuk::encode($TakTuk::position,"$self->{position}"));
    $self->send_message($TakTuk::gateway) if $self->{gateway};
    if (length($self->{files})) {
        foreach my $transfer (split /,/,$self->{files}) {
            my ($source, $destination) = split /:/, $transfer;

            $self->send_file("", $source, $destination);
        }
    } 
    my $arguments = $self->{arguments};
    diagnostic::debug("Arguments : ".$arguments);
    $self->send_message(TakTuk::encode($TakTuk::arguments, $arguments));
}

sub get_message () {
    my $self = shift;

    if ($self->{state} >= $initialized) {
        if (exists($self->{write})) {
            return TakTuk::get_message($self->{write});
        } else {
            return "";
        }
    } else {
        return "";
    }
}

sub send_message($) {
    my $self = shift;
    my $write_fd = $self->{read};
    my $message = shift;
    my $full_message = TakTuk::pack($message);

    if (not communicator::post_write($write_fd, $full_message)) {
        diagnostic::error("Error in send message [$full_message], error : $!");
    }
}

sub route_file_part($$) {
    my $self = shift;
    my $prefix = shift;
    my $message = shift;

    if ($prefix) {
        $message = TakTuk::encode($prefix, $message);
        communicator::process_message($self, $message);
    } else {
        $self->send_message($message);
    }
}

sub send_file($$$) {
    my $self = shift;
    my $prefix = shift;
    my $source = shift;
    my $destination = shift;
    my $permissions;
    my $file = undef;
    my $result;
    my $type;

    $source = general::expand($source, position=>$general::position,
                                       host=>$general::host,
                                       rank=>$general::taktuk{rank});
    if (-d $source) {
        $type = 1;
        $result = open($file,"cd $source && tar c . |");
    } else {
        $type = 0;
        $result = open($file, $source);
    }
    if ($result) {
        my $read_result;
        my $buffer;
        my $message;

        binmode($file) or diagnostic::system;
        $permissions=(stat($source))[2] & 07777;
        $message = TakTuk::pack($general::position).
                   TakTuk::pack($general::host).
                   TakTuk::pack($general::taktuk{rank}).
                   TakTuk::pack($type).
                   TakTuk::pack($permissions).
                   TakTuk::pack(basename($source)).
                   $destination;
        $message = TakTuk::encode($TakTuk::file, $message);
        $self->route_file_part($prefix, $message);
        while ($read_result = sysread($file, $buffer, $TakTuk::read_size/2)) {
            $message = TakTuk::encode($TakTuk::file,
                                    TakTuk::pack($general::position).$buffer);
            $self->route_file_part($prefix, $message);
        }
        diagnostic::system if not defined($read_result);
        $message = TakTuk::encode($TakTuk::file,
                                            TakTuk::pack($general::position));
        $self->route_file_part($prefix, $message);
        CORE::close($file) or diagnostic::system;
    } else {
        diagnostic::system;
        $self->output('state',TakTuk::FILE_SEND_FAILED);
    }
}

our @pack_fields = ('login', 'peer', 'taktuk', 'arguments', 'position',
'gateway', 'propagate', 'files', 'timeout');

sub pack() {
    my $self = shift;
    my $result = "";

    foreach my $field (@pack_fields) {
        $result .= TakTuk::pack($self->{$field});
    }
    return $result;
}

sub unpack($) {
    my $buffer = shift;
    my %data = ();

    foreach my $field (@pack_fields) {
        ($data{$field}, $buffer) = TakTuk::unpack($buffer);
    }
    my $connector = connector::new(%data);
    return ($connector, $buffer);
}

sub cancel() {
    my $connector = shift;

    # On some platforms (such as grid 5000) the connection processus has an
    # elevated status and cannot be killed. Thus, the safest method is to
    # disconnect the process from TakTuk before trying to kill it (possibly
    # without success).
    $connector->{canceled} = 1;
    communicator::remove_descriptor($connector, $connector->{write})
        if exists($connector->{write});
    communicator::remove_descriptor($connector, $connector->{error})
        if exists($connector->{error});

    # whe should also avoid to remove the connector a second time when reaping
    # the children
    if (exists($communicator::c_from_pid{$connector->{pid}})) {
        delete $communicator::c_from_pid{$connector->{pid}};
    }
    CORE::kill -9, $connector->{pid};
}

###############################################
### COMMUNICATOR                            ###
###############################################

package communicator;
use strict; use bytes;
use POSIX ":sys_wait_h";
use Errno;
use Fcntl;

our $sinks_number = 0;
our $initialized_sinks_number = 0;
our $target_number = 0;

our $select;
our $pending_writes_select;
our $select_timeout;

our $connections;
our $end = 0;
our %c_from_fd;
our %c_from_target;
our %c_from_pid;

our %pending_writes;
our $pending_writes_number = 0;
our $pending_size = 0;
our $cache_limit;
our %pending_termination_handler;
our %pending_termination_argument;

# default connector to which it is only possible to write
# (used by get_root as a last ressort, useful for diagnostic)
our $default_root = connector::new(
                              read => \*STDOUT,
                              type => settings::FD);

sub create_channel() {
    # Now I create the control channel
    my $communicator_read = undef;
    my $communicator_write = undef;
    my $control_read = undef;
    my $control_write = undef;
    my $type = undef;

    if (general::has_socketpair) {
        ($communicator_read, $control_read) = general::create_socketpair();
        return () unless defined($communicator_read) and defined($control_read);
        $communicator_write = $communicator_read;
        $control_write = $control_read;
        $type = settings::SOCKET;
    } else {
        if (not pipe($communicator_read, $control_write) or
            not pipe($control_read, $communicator_write)) {
            diagnostic::system;
            return ();
        }
        $type = settings::FD;
    }
    # Probably redundant with what's done in add_connector, but doesn't harm
    TakTuk::no_flush($communicator_write);
    TakTuk::no_flush($control_write);
    my $communicator_connector = connector::new('read'  =>$communicator_write,
                                                'write' =>$communicator_read,
                                                'type'  =>$type);
    my $control_connector = connector::new('read'  =>$control_write,
                                           'write' =>$control_read,
                                           'type'  =>$type);
    return ($communicator_connector, $control_connector);
} 

sub init() {
    $select = TakTuk::Select->new() or diagnostic::error("Select creation");
    $pending_writes_select =
                 TakTuk::Select->new() or diagnostic::error("Select creation");
    $connections = {};
    $connections->{sources} = [];
    $connections->{sinks} = [];
    $connections->{control} = [];
    $connections->{interpreter} = [];
    $connections->{local_commands} = [];
    $connections->{pipe} = [];

    $ENV{TAKTUK_HOSTNAME} = $general::host;
}

sub cleanup() {
    foreach my $connector
                       (@{$connections->{sinks}}, @{$connections->{control}}) {
        $connector->cleanup;
    }
}

sub get_connections($) {
    my $set_name = shift;
    my $list = $connections->{$set_name};
    return @$list;
}

sub get_root() {
    my $sources = $connections->{sources};

    if (defined($sources) and scalar(@$sources)) {
        return $sources->[0];
    } else {
        return $default_root;
    }
}

sub process_message($$) {
    my $connector = shift;
    my ($message, $body) = TakTuk::decode(shift);
    my $function = handlers::get_handler($message);

    if (defined($function)) {
        &$function($message, $connector, $body);
    } else {
        diagnostic::warning("Unknown message : $message (body: $body)");
    }
}

sub process_messages($$) {
  my $connector = shift;
  my $descriptor = shift;

  my $result = $connector->read_data($descriptor);
  my $message = $connector->get_message;

  while ($message) {
      process_message($connector, $message);
      $message = $connector->get_message;
    }
  return $result;
}

sub process_command_output($$) {
    my $command = shift;
    my $descriptor = shift;

    my $buffer;
    my $read_result;

    $read_result = sysread($descriptor, $buffer, $TakTuk::read_size);
    (diagnostic::system and $read_result = 0) if not defined($read_result);
    if ($read_result > 0) {
        my $type;
        if (exists($command->{write}) and ($descriptor == $command->{write})) {
            $type = "output";
        } else {
            $type = "error";
        }
        $command->output($type, $buffer);
    }
    return $read_result;
}

sub process_pipe_output($$) {
    my $command = shift;
    my $descriptor = shift;

    my $buffer;
    my $read_result;

    if (not $end) {
        $read_result = sysread($descriptor, $buffer, $TakTuk::read_size);
        (diagnostic::system and $read_result = 0) if not defined($read_result);
        if ($read_result > 0) {
            process_message($command, TakTuk::encode($command->{message},
                                                                     $buffer));
        }
        return $read_result;
    } else {
        return 1;
    }
}

sub run() {
    my @select_result;
    my $sinks = $connections->{sinks};
    my $local_commands = $connections->{local_commands};

    while ((not $end) or scalar(@$sinks) or scalar(@$local_commands) or
           $pending_writes_number) {
        #diagnostic::debug("Select loop ($end, @$sinks, @$local_commands)");
        if (($pending_size > $cache_limit) and ($cache_limit >= 0)) {
            # In this case, too much memory is occupied by pending write : we
            # stop any further reading until pending writes volume gets smaller
            @select_result = TakTuk::Select::select(
                         undef,$pending_writes_select,undef,$select_timeout);
        } else {
            @select_result = TakTuk::Select::select(
                         $select,$pending_writes_select,undef,$select_timeout);
        }
        if (scalar(@select_result)) {
            my ($read_set, $write_set, $exception_set) = @select_result;
            while (scalar(@$read_set)) {
                my $descriptor = shift @$read_set;
                my $cobidule = $c_from_fd{$descriptor};

                if (exists($cobidule->{data_handler})) {
                    my $handler = $cobidule->{data_handler};
                    my $result = &$handler($cobidule, $descriptor);
                    remove_descriptor($cobidule, $descriptor) if (not $result);
                } else {
                    diagnostic::error("Bug : connector has no data handler");
                }
            }
            while (scalar(@$write_set)) {
                my $descriptor = shift @$write_set;

                write_pending_stuff($descriptor);
            }
            if (scalar(@$exception_set)) {
                diagnostic::warning("Unexpected exceptional fds : ".
                    join(' ', @$exception_set));
            }
        } else {
            # Here we might have been thrown out of select by a timeout
            # but we have to test for error conditions (just in case)
            if ($!{EBADF}) {
                my $error_msg="Selected an invalid descriptor ($!)... Very ".
                              "bad\nRegistered handles = ";
                foreach my $handle ($select->handles) {
                    $error_msg.="$handle (".fileno($handle).") "
                        if defined(fileno($handle));
                }
                diagnostic::error($error_msg);
                exit 1;
            } elsif ($!{EINTR}) {
                diagnostic::warning("Select exited because of a signal");
            } elsif ($!{EINVAL}) {
                diagnostic::error("Invalid time limit for select");
            } else {
                diagnostic::error("Unknown error");
            }
        }
        timer::check_timeouts;
        # Time to reap children
        my $pid;
        while (($pid = waitpid -1, WNOHANG) > 0) {
            diagnostic::debug("Reaping $pid");
            if (exists($c_from_pid{$pid})) {
                my $cobidule = $c_from_pid{$pid};
                $cobidule->{status} = $?;
                $cobidule->{stop_date} = timer::current_time;
                # Removes the cobidule if done
                remove_cobidule($cobidule);
                delete $c_from_pid{$cobidule};
            }
        }
        diagnostic::error("Waiting child, $!") unless defined($pid);
    }
}

sub terminate () {
    $end = 1;
}

sub add_descriptors($) {
    my $command = shift;
    my $error;
    if (exists($command->{write})) {
        $error = $select->add($command->{write});
        diagnostic::warning(TakTuk::Select::error_msg($error)) if $error;
        $c_from_fd{$command->{write}} = $command;
        binmode($command->{write}) or diagnostic::system;
    }
    if (exists($command->{error})) {
        $error = $select->add($command->{error});
        diagnostic::warning(TakTuk::Select::error_msg($error)) if $error;
        $c_from_fd{$command->{error}} = $command;
        binmode($command->{error}) or diagnostic::system;
    }
}

sub remove_descriptor($$) {
    my $cobidule = shift;
    my $descriptor = shift;
    my $type;

    diagnostic::debug("Removing $cobidule / $descriptor");
    my $write = undef;
    my $error = undef;
    $write = $cobidule->{write} if exists $cobidule->{write};
    $error = $cobidule->{error} if exists $cobidule->{error};

    if (defined($descriptor)) {
        if (defined($write) and ($write == $descriptor)) {
            $type = 'write';
        } elsif (defined($error) and ($error == $descriptor)) {
            $type = 'error';
        } else {
            diagnostic::error("Invalid descriptor, serious BUG !");
        }
        if (exists $c_from_fd{$descriptor}) {
            my $error = $select->remove($descriptor);
            diagnostic::warning(TakTuk::Select::error_msg($error)) if $error;
            delete $c_from_fd{$descriptor};
            $cobidule->close($type);
            # Removes the cobidule if done
            remove_cobidule($cobidule);
        } else {
            diagnostic::warning("Descriptor not present in hash");
        }
    } else {
        diagnostic::warning("Should not be called with undefined descriptor");
    }
}

sub remove_cobidule($) {
    my $cobidule = shift;

    # To be removed, a cobidule should have both of its output channels closed
    # and should have somehow terminated
    if ((exists($cobidule->{canceled}) or exists($cobidule->{status}) or
         not exists($cobidule->{pid})) and
        not exists($cobidule->{write}) and not exists($cobidule->{error})) {
        diagnostic::debug("Removing cobidule $cobidule");
        # While write and error channels should be automatically closed
        # and removed, this is not the case of the read channel (which
        # requires an explicit eof message).
        if (exists($cobidule->{read})) {
            my $read = $cobidule->{read};
            cleanup_pending_stuff($read)
               if exists($pending_writes{$read});
               $cobidule->close('read');
        }

        my $found = remove_from_set($cobidule);
        diagnostic::warning("Connector to remove not found!") unless $found;

        if (exists($cobidule->{remove_handler})) {
            my $handler = $cobidule->{remove_handler};
            &$handler($cobidule);
        }
    }
}

sub no_pending_connectors() {
    diagnostic::debug("Connectors situation, sinks_number : $sinks_number, ".
                      "initialized : $initialized_sinks_number");
    dagnostic::warning("More initialized than sinks")
        if ($sinks_number<$initialized_sinks_number);
    return $sinks_number == $initialized_sinks_number;
}

sub add_connector($$) {
    my $connector = shift;
    my $set_name = shift;
    my $set = $connections->{$set_name};

    diagnostic::debug("Adding connector: ".join(' ',%$connector));
    if (exists($connector->{read})) {
        TakTuk::no_flush($connector->{read});
        # Non blocking flag is set here to avoid making non blocking the
        # default root which would make STDIN non blocking as side effect thus
        # making interactive mode unsuable
        fcntl($connector->{read}, F_SETFL, O_NONBLOCK) or diagnostic::system;
    }

    $connector->{set} = $set_name;
    add_descriptors($connector);
    push(@$set,$connector);
    $sinks_number++ if $set_name eq 'sinks';
}

sub connector_initialized($) {
    my $connector = shift;

    $initialized_sinks_number++;
}

sub remove_from_set($) {
    my $cobidule = shift;
    my $set_name = $cobidule->{set};
    my $set = $connections->{$set_name};
    my $i = 0;

    $i++ while (($i <= $#$set) and ($set->[$i] != $cobidule));
    if ($i <= $#$set) {
        splice @$set, $i, 1;
        diagnostic::debug("Cobidule $cobidule, ".
                          ($cobidule->{line}?$cobidule->{line}." ":"").
                          ($cobidule->{pid}?$cobidule->{pid}." ":"").
                          "deleted from set $set_name at position $i");
        return 1;
    } else {
        return 0;
    }
}

sub remove_source($) {
    my $connector = shift;

    if (not scalar(@{$connections->{sources}})) {
        # useless to do anything cleanly now as I lost connection
        # might change if some commands running have side effects
        # but even in this last case, its better to handle it through
        # usual synchronization because of resulting hanged zombies
        # general::print("Exiting after loosing my sources ($$)\n");
        exit 1;
    }
} 

sub remove_interpreter($) {
    my $connector = shift;

    if ($general::root) {
        process_message(get_root, $main::quit_message) unless $end;
    } else {
        diagnostic::warning("Lost interpreter connector in child (bug) !");
    }
} 

sub remove_sink($) {
    my $connector = shift;

    # Remove it first because synchronizer::initialization failed
    # checks for ready state
    $sinks_number--;
    if ($connector->{state} >= $connector::initialized) {
        if (not $communicator::end) {
            $connector->{given_list} = join(' ',
                map { $_->{peer}.":".$_->{position} } @{$connector->{given}});
            $connector->output('state', TakTuk::CONNECTION_LOST);
        }
        $initialized_sinks_number--;
    } else {
        synchronizer::initialization_failed($connector);
    }
    # in any case, I've to check ongoing reduces to avoid blocking
    # current instance (e.g. in the case of the initial reduce_count)
    # For now reduces only propagate upward, so only sinks might change
    # a reduce result.
    handlers::check_ongoing_reduces($connector);
} 

sub remove_control($) {
    my $connector = shift;

    delete($c_from_target{$connector});
} 

sub remove_local_command($) {
    my $command = shift;

    if (exists($command->{timers})) {
        my $timers = $command->{timers};
        foreach my $timer (@$timers) {
            $timer->unregister if not $timer->{elapsed};
        }
    }
    if (exists($command->{status})) {
        $command->output('status', $command->{status})
    } else {
        diagnostic::warning("Some command terminated without status");
    }
    $command->output('state', TakTuk::COMMAND_TERMINATED);
    handlers::local_command_completed($command);
}

sub remove_pipe($) {
    my $command = shift;

    communicator::get_root->output('state', TakTuk::PIPE_TERMINATED);
}

sub post_write($$@) {
    my $file = shift;
    my $data = shift;
    my $length = scalar(@_)?shift:length($data);
    my $offset = scalar(@_)?shift:0;
    my $result = 1;

    (diagnostic::warning("Null length write") and return) if not $length;
    diagnostic::warning("Null file") if not $file;
    if (not exists($pending_writes{$file})) {
        $result = CORE::syswrite($file, $data, $length, $offset);
        if ($result) {
            $length -= $result;
            $offset += $result;
        }
    }
    if ((defined($result) and $length) or $!{EAGAIN}) {
        if (not exists($pending_writes{$file})) {
            $pending_writes{$file} = [];
            my $error = $pending_writes_select->add($file);
            diagnostic::warning(TakTuk::Select::error_msg($error)) if $error;
        }
        my $list = $pending_writes{$file};
        push @$list, [ $file, $data, $length, $offset ];
        $pending_writes_number++;
        $pending_size += $length;
        return 1;
    } else {
        diagnostic::system unless defined($result);
        return $result;
    }
}

sub post_close($) {
    my $cobidule = shift;

    if (exists($cobidule->{read})) {
        post_termination($cobidule->{read}, \&close_cobidule_read, $cobidule);
    }
}

sub post_termination($$$) {
    my $descriptor = shift;
    my $handler = shift;
    my $handler_arg = shift;

    if (exists($pending_writes{$descriptor})) {
        $pending_termination_handler{$descriptor} = $handler;
        $pending_termination_argument{$descriptor} = $handler_arg;
    } else {
        &$handler($handler_arg);
    }
}

sub cleanup_pending_stuff($) {
    my $descriptor = shift;

    if (exists($pending_writes{$descriptor})) {
        foreach my $length (@{$pending_writes{$descriptor}}) {
            $pending_size -= $length->[2];
        }
        $pending_writes_number -= scalar(@{$pending_writes{$descriptor}});
        $error = $pending_writes_select->remove($descriptor);
        diagnostic::warning(TakTuk::Select::error_msg($error)) if $error;
        delete($pending_writes{$descriptor});
        if (exists($pending_termination_handler{$descriptor})) {
            my $handler = $pending_termination_handler{$descriptor};
            my $argument = $pending_termination_argument{$descriptor};
            &$handler($argument);
            delete($pending_termination_handler{$descriptor});
            delete($pending_termination_argument{$descriptor});
        }
    }
}

sub write_pending_stuff($) {
    my $descriptor = shift;

    if (exists($pending_writes{$descriptor})) {
        my $list = $pending_writes{$descriptor};
        my $chunk = shift @$list;
        my ($file, $data, $length, $offset) = @$chunk;
        my $result;

        $result = CORE::syswrite($file, $data, $length, $offset);
        if ($result) {
            $length -= $result;
            $pending_size -= $result;
            $offset += $result;
        }
        if ((defined($result) and $length) or $!{EAGAIN}) {
            $chunk->[2] = $length;
            $chunk->[3] = $offset;
            unshift @$list, $chunk;
        } else {
            diagnostic::system unless defined($result);
            $pending_writes_number--;
        }
        if (not scalar(@$list)) {
            cleanup_pending_stuff($descriptor);
        }
    }
}

sub flush_pending_stuff() {
    while (scalar(keys(%pending_writes))) {
        foreach my $descriptor (keys(%pending_writes)) {
            write_pending_stuff($descriptor);
        }
    }
}

sub close_cobidule_read($) {
    my $cobidule = shift;

    if (exists($cobidule->{read})) {
        $cobidule->close('read');
    }
}

sub assign_target($$) {
    my $command = shift;
    my $target = shift;

    if (exists($c_from_target{$target})) {
        my $second_command = $c_from_target{$target};
        diagnostic::warning("Target $target already assigned, overwriting")
            if not exists($second_command->{auto_target});
        assign_next_target($second_command);
    }
    $command->{target} = $target;
    $c_from_target{$target} = $command;
}

sub assign_next_target($) {
    my $command = shift;

    while (exists($c_from_target{$target_number})) {
        $target_number++;
    }
    assign_target($command, $target_number);
    $command->{auto_target} = 1;
    $target_number++;
}

sub get_target_set($$) {
    my $target = shift;
    my $set = shift;
    my @result = ();
    my @connections = get_connections($set);

    if ($target eq "all") {
        return @connections;
    } else {
        my @target_list = general::decode_set($target, $target_number - 1);

        while (scalar(@target_list)) {
            my $min = shift @target_list;
            my $max = shift @target_list;

            for (my $i=$min; $i <= $max; $i++) {
                if (exists ($c_from_target{$i})) {
                    push @result, $c_from_target{$i};
                } else {
                    diagnostic::warning("Invalid target $i");
                    communicator::get_root->output('state',
                                                       TakTuk::INVALID_TARGET);
                }
            }
        }
        if (not scalar(@result)) {
            diagnostic::warning("No target");
            communicator::get_root->output('state', TakTuk::NO_TARGET);
        }
        return @result;
    }
}

###############################################
### STATS_BUFFER                            ###
###############################################

package stats_buffer;
use strict; use bytes;

sub new($$) {
  my $type = shift;
  my $depth = shift;
  my $data = { depth=>$depth, data=>[] };
  bless ($data, $type);
  return $data;
}

sub is_empty($) {
  my $self = shift;
  return not scalar(@{$self->{data}});
}

sub add($$) {
  my $self = shift;
  my $value = shift;
  my $data = $self->{data};

  push @$data, $value;
  if ($#$data > $self->{depth}) {
      shift @$data;
    }
}

sub average($) {
  my $self = shift;
  my $average;
  my $data = $self->{data};

  if (scalar(@$data)) {
      $average = 0;
      foreach my $value (@$data) {
          $average += $value;
        }
      return $average / scalar(@$data);
    } else {
      return undef;
    }
}

sub min($) {
  my $self = shift;
  my $data = $self->{data};
  my $min;

  if (scalar(@$data)) {
      $min = $self->{data}[0];

      foreach my $value (@$data) {
          $min = $value if $min > $value;
        }
      return $min;
    } else {
      return undef;
    }
}

sub max($) {
  my $self = shift;
  my $data = $self->{data};
  my $max;

  if (scalar(@$data)) {
      $max = $self->{data}[0];

      foreach my $value (@$data) {
          $max = $value if $max < $value;
        }
      return $max;
    } else {
      return undef;
    }
}

###############################################
### SCHEDULER                               ###
###############################################

package scheduler;
use strict; use bytes;

our $window;
our $window_adaptation;

# in progress
our $undeployed_connectors = 0;
our $current_window = 0;
our $steal_request_sent = 0;
our $worksteal;
our @waiting_thieves = ();

# stats
our %stats = (connections=>stats_buffer->new(5), shifts=>stats_buffer->new(5));
our $last_time = undef;

# adaptation
our $threshold_low = 0.1;
our $threshold_high = 0.2;
our $max_increase = 1.5;

# groups
our @group = ( { static => [], dynamic => [], limit => 0, arity => 0 } );
our $current_group = 0;
our $last_group = 0;
our @groups_stack = ();

sub begin_group() {
    my $limit = $group[$current_group]->{limit};
    push @groups_stack, $current_group;
    push @group, { static => [], dynamic => [], limit => $limit, arity => 0 };
    $current_group = $#group;
}

sub end_group() {
    $current_group = pop @groups_stack;
}

sub set_limit($) {
    $group[$current_group]->{limit} = shift;
}

sub deploy_connector($) {
    my $connector = shift;

    if ($connector->run(0)) {
        my $timer = timer->register($connector->{timeout},
                                   \&synchronizer::initialization_timeout);
        $connector->{timer} = $timer;
        $timer->{connector} = $connector;
        $connector->{remove_handler} = \&communicator::remove_sink;
        communicator::add_connector($connector, 'sinks');
        diagnostic::debug("Connector added : ".$connector->{line});
        $group[$connector->{group}]->{arity}++;
        $current_window++;
        # The following will have any effect only when already ready
        # It is necessary when new deployments are initiated after the
        # very first setup and the initial propagation of ready state
        synchronizer::synchronize_unnumbered_subnet;
    } else {
        # Ok, there's probably too many forks

        # Old code that try to guess the proper fix
        # actually this end up in deployment failures when system is higly
        # loaded (in this case the test succeed, hum)
        # So I changed to a more basic solution
        #if ($current_window < 1)
        #  {
        #    # We're in a big trouble, I have to deploy but I cannot ...
        #    # In this case I give up
        #    diagnostic::error("Cannot deploy connector due to fork ".
        #                      "unavailability");
        #}
        #else
        #  {
        #    diagnostic::warning("Delaying connector due to fork error");
        #    $window=$current_window;
        #    scheduler::add_connector($command_line, $arguments);
        #}
        #diagnostic::warning("Delaying connector due to fork error");
        #sleep 1;
        #scheduler::add_connector($connector);
        diagnostic::warning("Giving up connection to $connector->{peer}");
        # I guess a better long term solution would be to send connector to
        # children when failure repeats on the local node
    }
}

sub add_connector($) {
    my $connector = shift;
    my $number = $connector->{group};
    my $static = $group[$number]->{static};
    my $dynamic = $group[$number]->{dynamic};
    my $arity = $group[$number]->{arity};
    my $limit = $group[$number]->{limit};

    # I should test whether this accelerates or not now that group scheduling
    # is implemented (should be hindering in presence of groups)
    # If this is to be removed, should also initialize $last_group to -1
    if (($current_window < $window) and not at_limit($group[$number])) {
        deploy_connector($connector);
    } else {
        if ($limit < 0) {
            push @$static, $connector;
        } else {
            push @$dynamic, $connector;
        }
        $undeployed_connectors++;
    }
}

sub connector_initialized($) {
    my $connector = shift;
    my $time = $connector->{init_date} - $connector->{start_date};

    if ($window_adaptation) {
        my $threshold;
        my $current_time;
        my $shift = 0;

        $stats{connections}->add($time);
        # not used
        $threshold = $stats{connections}->min?
                     $time/$stats{connections}->min - 1:0;
        $current_time = timer::current_time;
        if ($last_time) {
            $shift = $current_time - $last_time;
            $stats{shifts}->add($shift);
        }
        $last_time = $current_time;
        #diagnostic::warning("Connection time $time Shift $shift Min ".
        #    ($stats{connections}->min?$stats{connections}->min:"undef").
        #    " Threshold $threshold Average shift ".
        #    ($stats{shifts}->average?$stats{shifts}->average:"undef"));
        if ($threshold) {
            my $adapt = 0;
            my $old_window = $window;
 
            if (($threshold < $threshold_low) and $stats{shifts}->average) {
                my $max_window;

                $max_window = floor($window * $max_increase);
                $window = floor($stats{connections}->min / 
                                $stats{shifts}->average);
                $window = $max_window if $window > $max_window;
            } elsif ($threshold > $threshold_high) {
                $window -= floor($threshold*$window);
            }
            $window = 1 if $window < 1;
            diagnostic::debug("Window gone from $old_window to $window");
        }
    }
    $current_window--;
    schedule;
}

sub connector_failed($) {
    my $connector = shift;

    $current_window--;
    $group[$connector->{group}]->{arity}--;
    schedule;
}

sub at_limit($) {
    my $group = shift;

    if (($group->{limit} > 0) and ($group->{arity} >= $group->{limit})) {
        return 1;
    } else {
        return 0;
    }
}

sub schedule() {
    my $deployed = 1;
    my $new_group = $last_group + 1;
    $new_group %= scalar(@group);
    while ($undeployed_connectors
           and ($deployed or ($new_group != $last_group))
           and ($current_window < $window)) {
        my $group = $group[$new_group];
        my $connector = undef;

        if (scalar(@{$group->{static}})) {
            $connector = shift @{$group->{static}};
        } elsif (scalar(@{$group->{dynamic}}) and not at_limit($group)) {
            $connector = shift @{$group->{dynamic}};
        }
        if (defined($connector)) {
            deploy_connector($connector);
            $undeployed_connectors--;
            $last_group = $new_group;
            $deployed = 1;
        } else {
            $deployed = 0;
        }
        $new_group++;
        $new_group %= scalar(@group);
    }
    $last_group = $new_group;
    # Voir si on a vraiment besoin du test sur $undeployed_connectors
    if (not $general::root and not $steal_request_sent and
        not at_limit($group[0]) and
        ($undeployed_connectors == 0) and ($current_window < $window)) {
        send_steal_request("");
        diagnostic::debug("Steal request sent");
    }  else {
        diagnostic::debug("Nothing done in scheduler");
    }
}

sub is_idle() {
    return $undeployed_connectors == 0;
}

sub send_work_to($) {
    my $thief = shift;
    my $group = $group[$thief->{group}];
    my $work_to_give = scalar(@{$group->{dynamic}});
    my $given=0;

    diagnostic::debug("Theft in group $thief->{group}, ".
                      "dynamic connectors : ".scalar(@{$group->{dynamic}}).
                      ", work to give : $work_to_give"); 
    if ($work_to_give) {
        my $available = scalar(@{$group->{dynamic}});
        my $last_given = $thief->{last_given};
        my $limit = eval($worksteal->{limit});
        my $to_give = 0;
        my $workpack="";

        if ($last_given) {
            $to_give = eval($worksteal->{growth});
        } else {
            $to_give = eval($worksteal->{initial});
        }
        $to_give = $limit if $to_give > $limit;
        for ($given=0; $given < $to_give; $given++) {
            my $connector_to_deploy = shift @{$group->{dynamic}};

            $workpack = $workpack.$connector_to_deploy->pack();
            $undeployed_connectors--;
            push @{$thief->{given}}, $connector_to_deploy;
        }

        $thief->send_message(TakTuk::encode($TakTuk::work, $workpack));
        diagnostic::debug("Work sent : ".$workpack);
    }
    return $given;
} 

sub dispatch_work($) {
    my $workpack = shift;
    my $connector;

    while ($workpack) {
        ($connector, $workpack) = connector::unpack($workpack);
        $connector->{group} = 0;
        diagnostic::debug("Unpacked connector: $connector");
        push @{$group[0]->{dynamic}}, $connector;
        $undeployed_connectors++;
    }
    # reset steal information
    $steal_request_sent = 0;
    # priority to local schedule (ASAP)
    schedule;
    my $satisfied = 1;
    while (scalar(@waiting_thieves) and $satisfied) {
        my $thief = shift @waiting_thieves;
        $satisfied = send_work_to($thief);
        unshift @waiting_thieves, $thief unless $satisfied;
    }
    send_steal_request("") unless $satisfied;
}

sub theft_handler($$) {
    my $connector = shift;
    my $parameters = shift;

    my $given = send_work_to($connector);
    push @waiting_thieves, $connector unless $given or $connector->{group};
    if (scalar(@waiting_thieves) and not $general::root and
        not $steal_request_sent) {
        send_steal_request($parameters);
        diagnostic::debug("Forwarded steal request, parameters : $parameters");
    } elsif (scalar(@waiting_thieves)) {
        if ($general::root) {
            diagnostic::debug("Cannot satisfy steal request : no more dynamic ".
                              "work");
        } elsif ($steal_request_sent) {
            diagnostic::debug("Request already sent");
        }
        
    }
}

sub send_steal_request($) {
    my $parameters = shift;

    communicator::get_root->send_message(
          TakTuk::encode($TakTuk::steal, $parameters));
    $steal_request_sent = 1;
}

sub resign() {
    foreach my $group (@group) {
        $group->{static} = [];
        $group->{dynamic} = [];
    }
    $undeployed_connectors = 0;
}

###############################################
### TIMER                                   ###
###############################################

package timer;
use strict; use bytes;
our $has_timehires = eval("use Time::HiRes;1")?1:0;

our @registered_timers;

sub current_time() {
    if ($has_timehires) {
        my ($seconds, $micro) = Time::HiRes::gettimeofday();
        return $seconds + $micro/1000000;
    } else {
        return time;
    }
}

sub register($$) {
    my $type = shift;
    my $timeout = shift;
    my $handler = shift;
    my $current = current_time;
    my $data = { 'handler'=>$handler,
                 'birth'=>$current,
                 'elapsed'=>0 };
    bless($data, $type);
    if ($timeout) {
        $data->{timeout} = $current+$timeout;
        my $i=$#registered_timers;
        $i-- while (($i >= 0) and
                    ($registered_timers[$i]->{timeout} > $data->{timeout}));
        splice @registered_timers, $i+1, 0, $data;
    } else {
        $data->{timeout} = 0;
    }
    diagnostic::debug("Registered new timer $data, ".$data->print.
                      ", list = @registered_timers");
    return $data;
}

sub check_timeouts() {
    my $current = current_time;
    while (scalar(@registered_timers) and
           ($registered_timers[0]->{timeout} <= $current)) {
        my $timer = shift @registered_timers;
        $timer->{elapsed} = 1;
        my $handler = $timer->{handler};
        &$handler($timer);
        diagnostic::debug("Timeout handled for $timer, ".$timer->print);
    }
}

sub unregister() {
    my $timer = shift;
    if ($timer->{timeout}) {
        my $i=0;
        $i++ while (($i <= $#registered_timers) and
                    ($registered_timers[$i] != $timer));
        if ($i <= $#registered_timers) {
            splice @registered_timers, $i, 1;
            diagnostic::debug("Unregistered timer $timer, remaining ".
                              "@registered_timers equals ".
                              scalar(@registered_timers));
        } else {
            diagnostic::warning("Unregistering didn't found timer $timer");
        }
    }
}

sub gettime($) {
    my $current = current_time;
    my $timer = shift;
    return $current - $timer->{birth};
}

sub print($) {
    my $current = current_time;
    my $timer = shift;
    return "Timer created at $timer->{birth} timeouting at ".
           "$timer->{timeout} current is $current";
}

###############################################
### SYNCHRONIZER                            ###
###############################################

package synchronizer;
use strict; use bytes;

# messages constituting various engines
our @diffusion_engine = ($TakTuk::broadcast, $TakTuk::spread);
our @execution_engine = ($TakTuk::execute, $TakTuk::eof, $TakTuk::get,
                         $TakTuk::input, $TakTuk::kill,
                         $TakTuk::command_message, $TakTuk::put,
                         $TakTuk::command_send_to, 
                         $TakTuk::taktuk_perl, $TakTuk::wait);
our @internal_engine = ($TakTuk::message, $TakTuk::send_to);
our @synchro_engine = ($TakTuk::synchronize, $TakTuk::quit);

# states
our @states;

# ready state help variables
our $father_is_ready=0;

our %blocked;
our %event_waited;

sub init() {
    $states[TakTuk::WAIT_COMPLETE] = 1;
    $states[TakTuk::TAKTUK_NUMBERED] = 1;
    $states[TakTuk::TAKTUK_READY] = 1;
}

sub check_ready_state() {
    if (!$states[TakTuk::TAKTUK_READY]) {
        if ($father_is_ready && scheduler::is_idle &&
            communicator::no_pending_connectors) {
            # The first network setup enforce complete synchronisation (all
            # commands are initially blocked until its completion), it must be
            # propagated
            # Afterward, nothing can be ensured as conflicting operation might
            # be concurrently started (e.g. a new connector by might be
            # added on root while a broadcast is initiated in a leaf)
            foreach my $connector (communicator::get_connections('sinks')) {
                $connector->send_message($TakTuk::ready);
            }
            dispatch_event(TakTuk::TAKTUK_READY);
            diagnostic::debug("I'm ready");
        } else {
            diagnostic::debug("I'm not ready : father_is_ready = ".
                              "$father_is_ready, is_idle = ".
                              scheduler::is_idle.", no_pending_connector = ".
                              communicator::no_pending_connectors);
        }
    }
}

sub suspend_engine_until($@) {
    my $event = shift;
    if ($states[$event]) {
        block_until_event($event, @_);
    }
}

sub initialization_complete($) {
    my $connector = shift;

    diagnostic::debug("Connector $connector->{line} initialized");
    $connector->{init_date} = timer::current_time;
    $connector->{timer}->unregister;
    delete $connector->{timer};
    communicator::connector_initialized($connector);
    scheduler::connector_initialized($connector);
    $connector->send_parameters;
    $connector->output('state', TakTuk::CONNECTION_INITIALIZED);
    # must be the last operation as it depends on ongoing deployments
    check_ready_state;
}

sub initialization_failed($) {
    my $connector = shift;

    if (exists($connector->{timer})) {
        $connector->{timer}->unregister;
        delete $connector->{timer};
    }
    $connector->output('state', TakTuk::CONNECTION_FAILED);
    # Nothing to be done for communicator as this function should be called from
    # communicator::remove_sink
    scheduler::connector_failed($connector);
    # must be the last operation as it depends on ongoing deployments
    check_ready_state;
    # checking ongoing reduces is useless here as no reduce could have been
    # initiated before the ready state
}

sub initialization_timeout($) {
    my $timer = shift;
    my $connector = $timer->{connector};
    delete $connector->{timer};
    $connector->{timeouted} = 1;
    if ($connector->{state} >= $connector::initialized) {
        diagnostic::warning("Bug, timeouted an initialized connector");
    } else {
        if (exists($connector->{read})) {
            communicator::cleanup_pending_stuff($connector->{read});
        }
        $connector->output('connector', "timeouted");
        $connector->cancel;
    }
}

sub block_until_event($@) {
    my $event = shift;
    my $handlers;
    my $pending;

    $states[$event] = 0;
    if (exists($blocked{$event})) {
        $handlers = $blocked{$event}->{handlers};
        $pending = $blocked{$event}->{pending};
    } else {
        $handlers = {};
        $pending = [];
        $blocked{$event} = { handlers=>$handlers, pending=>$pending };
    }

    foreach my $message (@_) {
        if (exists($event_waited{$message})) {
            diagnostic::warning("Multiple blocking for $message");
        } else {
            $handlers->{$message} = handlers::get_handler($message);
            handlers::replace_handler($message, \&handlers::handler_blocked);
            $event_waited{$message} = $event;
        }
    }
}

sub dispatch_event($) {
    my $event = shift;

    if (not $states[$event]) {
        my $handlers = $blocked{$event}->{handlers};
        my @pending_list = @{$blocked{$event}->{pending}};

        communicator::get_root->output('state', $event);
        $states[$event] = 1;
        foreach my $message (keys(%$handlers)) {
            handlers::replace_handler($message, $handlers->{$message});
            delete $event_waited{$message};
        }
        general::apply_gateway_restrictions;
        # Immediately reset the blocked part of the event to be able to handle
        # it again when handling pending messages
        delete $blocked{$event};
        while (scalar(@pending_list)) {
            my $message = shift @pending_list;
            my $connector = shift @pending_list;
            my $body = shift @pending_list;

            my $function = handlers::get_handler($message);
            &$function($message, $connector, $body);
            diagnostic::debug("Processing $message with body $body");
        }
    } else {
        diagnostic::debug("Dispatching of $event with no effect");
    }
}

sub add_pending_message($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my $event = $event_waited{$message};
    my $pending_list = $blocked{$event}->{pending};
    push @$pending_list, $message, $connector, $body;
}

sub setup_synchronization() {
    if ($main::no_numbering) {
        if ($states[TakTuk::TAKTUK_READY]) {
            diagnostic::warning("Cannot synchronize an unnumbered ready ".
                                "TakTuk");
        } else {
            # in this case we just complete already suspended engine
            block_until_event(TakTuk::TAKTUK_READY, @synchro_engine);
        }
    } else {
        suspend_engine_until(TakTuk::TAKTUK_NUMBERED, @execution_engine,
                                        @internal_engine, @synchro_engine);
    }
}

sub synchronize_unnumbered_subnet() {
        suspend_engine_until(TakTuk::TAKTUK_READY, @diffusion_engine,
                                                   @synchro_engine);
}

###############################################
### HANDLERS                                ###
###############################################

package handlers;
use strict; use bytes;
use Fcntl;

our %handlers;

sub register_handler($$) {
    my $message = shift;

    if (defined($handlers{$message})) {
        diagnostic::error("Handler already defined for $message");
    } else {
        $handlers{$message} = shift;
    }
}

sub replace_handler($$) {
    my $message = shift;

    if (defined($handlers{$message})) {
        $handlers{$message} = shift;
    } else {
        diagnostic::error("Handler not defined for $message");
    }
}

sub get_handler($) {
    my $message = shift;
    return $handlers{$message};
}


sub handler_blocked($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    synchronizer::add_pending_message($message, $connector, $body);
}
    
sub arguments($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $element;
    my @arguments;

    while ($body) {
        ($element, $body) = TakTuk::unpack($body);
        push @arguments, $element;
    }

    # Now I've to handle all the stuff (just as in main)
    arguments::fetch_arguments(@arguments);
    arguments::parse_options;

    main::process_commands;
    # Useful especially for stealing if I've nothing to do
    scheduler::schedule;
}

sub broadcast($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    foreach my $other_connector (communicator::get_connections('sources'),
                                 communicator::get_connections('sinks')) {
        if ($other_connector != $connector) {
            diagnostic::debug("Spreading message to $other_connector");
            $other_connector->send_message(TakTuk::encode(
                                            $TakTuk::spread, $body));
        }
    }
    # this message should not be interpreted on the originating node
    # this is the behavior of spread which is sent to others
    # communicator::process_message($connector, $body);
}

sub down($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my $root_connector = communicator::get_root;
    communicator::process_message($root_connector, $body);
}

sub empty($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
}

sub eof($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $target;
    my @target_set;

    $target = $body;
    @target_set = communicator::get_target_set($target, 'local_commands');
    foreach my $command (@target_set) {
        communicator::post_close($command);
        diagnostic::debug("Posted close inputs for command $command");
    }
}

sub update_failed($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    communicator::get_root->output('state', TakTuk::UPDATE_FAILED)
        if ($general::taktuk{rank} < 0);
    synchronizer::dispatch_event(TakTuk::TAKTUK_NUMBERED)
}

sub execute_timeout($) {
    my $timer = shift;
    my $message_list = $timer->{messages};

    diagnostic::debug("Timeout triggered for $timer->{command}->{line}");
    $ENV{TAKTUK_PID} = $timer->{command}->{pid};
    if (not length($message_list)) {
        CORE::kill -15, $timer->{command}->{pid};
    }
    while (length($message_list)) {
        my ($message, $action);
        ($message, $message_list) = TakTuk::unpack($message_list);
        ($action, $message) = TakTuk::decode($message);
        if ($action eq $TakTuk::action) {
            communicator::process_message($timer->{command}->{control},
                                                                    $message);
        } elsif ($action eq $TakTuk::kill) {
            CORE::kill -$message, $timer->{command}->{pid};
        } else {
            diagnostic::error("Internal error : unknown timeout action");
        }
    }
}

sub execute($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    # More annoying than helpfull
    # diagnostic::warning("Execution has no effect on the root node, you ".
    #  "probably forgot 'broadcast' when typing 'broadcast exec command'");
    my ($attributes, $line) = TakTuk::unpack($body);
    my $timers = [];
    my $command = command::new(line=>$line,
           data_handler=>\&communicator::process_command_output,
           timers=>$timers);
    my $result;

    while (length($attributes)) {
        my $chunk;
        ($chunk, $attributes) = TakTuk::unpack($attributes);
        diagnostic::error("Internal error") if not defined $chunk;
        my ($type, $body) = TakTuk::decode($chunk);
        if ($type eq $TakTuk::id) {
            communicator::assign_target($command, $body);
        } elsif ($type eq $TakTuk::timeout) {
            my $timeout;
            ($timeout, $body) = TakTuk::unpack($body);
            diagnostic::error("Internal error") if not defined $timeout;
        
            my $timer = timer->register($timeout, \&execute_timeout);
            $timer->{command} = $command;
            $timer->{connector} = $connector;
            $timer->{messages} = $body;
            push @$timers, $timer;
        } else {
            diagnostic::error("Internal error");
        }
    }

    $ENV{TAKTUK_PIDS} = join(' ', map("$_->{pid}",
                        communicator::get_connections('local_commands')));
    communicator::assign_next_target($command)
                                        unless exists($command->{target});
    $ENV{TAKTUK_TARGET} = $command->{target};

    if ($result = $command->run(1)) {
        $command->{remove_handler} = \&communicator::remove_local_command;
        communicator::add_connector($command, 'local_commands');
        $command->output('state', TakTuk::COMMAND_STARTED);
    } else {
        diagnostic::warning("Giving up command $line");
        $command->output('state', TakTuk::COMMAND_FAILED);
    }
    return $result;
}

our %filename;
our %file_perms;
our %file;

sub file_finalize($) {
    my $position = shift;
    if (exists($file{$position})) {
		# we ignore the ECHLD error which match the case in which the open mode
		# is piped output and the child has terminated
        CORE::close($file{$position}) or (not $!{ECHLD} and diagnostic::system);
        chmod $file_perms{$position}, $filename{$position}
            or diagnostic::system;
    }
}

sub file($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $position;
    ($position, $body) = TakTuk::unpack($body);

    if (not exists($file{$position})) {
        my ($host, $rank, $type, $permissions, $source, $destination);
        ($host, $body) = TakTuk::unpack($body);
        ($rank, $body) = TakTuk::unpack($body);
        ($type, $body) = TakTuk::unpack($body);
        ($permissions, $body) = TakTuk::unpack($body);
        ($source, $body) = TakTuk::unpack($body);
        $destination = $body;
        my $result = undef;

        $destination = general::expand($destination,
                                           position=>$position,
                                           host=>$host,
                                           rank=>$rank);
        if ($type) {
            if (-d $destination) {
                if (-d "$destination/$source" or mkdir "$destination/$source") {
                    $filename{$position} = "$destination/$source";
                } else {
                    diagnostic::system;
                }
            } elsif (mkdir $destination) {
                $filename{$position} = $destination;
            } else {   
                diagnostic::system;
            }
            if (exists($filename{$position})) {
                $result = open($file{$position},
                                       "| cd $filename{$position} && tar x");
            }
        } else {
            if (-d $destination) {
                $filename{$position} = "$destination/$source";
            } else {
                $filename{$position} = $destination;
            }
            $result = open($file{$position}, ">", $filename{$position});
        }
        if (defined($result)) {
            binmode($file{$position}) or diagnostic::system;
            $file_perms{$position} = $permissions;
            fcntl($file{$position}, F_SETFL, O_NONBLOCK) or diagnostic::system;
            $connector->output('state',TakTuk::FILE_RECEPTION_STARTED);
        } else {
            diagnostic::system;
            $file{$position} = undef;
            $connector->output('state',TakTuk::FILE_RECEPTION_FAILED);
        }
    } else {
        if (not length($body)) {
            if (defined($file{$position})) {
                communicator::post_termination($file{$position},
                    \&file_finalize, $position);
                $connector->output('state',
                                    TakTuk::FILE_RECEPTION_TERMINATED);
            } else {
                diagnostic::warning("End file message but no descritor");
            }
            delete($file{$position}) if exists($file{$position});
            delete($file_perms{$position}) if exists($file_perms{$position});
            delete($filename{$position}) if exists($filename{$position});
        } else {
            if (defined($file{$position})) {
                communicator::post_write($file{$position},$body) or
                    diagnostic::system;
            } else {
                diagnostic::warning("Undefined file descriptor for data");
            }
        }
    }
}

sub forward_up($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    if ($general::root) {
        communicator::process_message($connector, $body);
    } else {
        foreach my $other_connector (communicator::get_connections('sources')) {
            $other_connector->send_message(
                              TakTuk::encode($TakTuk::forward_up, $body));
        }
    }
}

sub gateway($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    $general::taktuk{gateway} = 1;
}

sub get($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $put_prefix;
    my $get_prefix;
    ($get_prefix, $body) = TakTuk::unpack($body);
    
    $put_prefix=TakTuk::encode($TakTuk::send_to,
                                         TakTuk::pack($general::taktuk{rank}));
    communicator::process_message($connector, TakTuk::encode($get_prefix,
        TakTuk::encode($TakTuk::put, TakTuk::pack($put_prefix).$body)));
}

sub get_info($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $info = undef;

    if ($body eq "target") {
        $info = $connector->{target} if exists($connector->{target});
    } else {
        $info = $general::taktuk{$body} if exists($general::taktuk{$body});
    }
    if (defined($info)) {
        $connector->send_message(TakTuk::encode($TakTuk::info, $info));
    } else {
        $connector->send_message($TakTuk::invalid);
    }
}

sub input($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $result;
    my $target;
    my @target_set;

    ($target, $body) = TakTuk::unpack($body);
    @target_set = communicator::get_target_set($target, 'local_commands');
    foreach my $command (@target_set) {
        if (exists($command->{read})) {
            $result = communicator::post_write($command->{read}, $body);
        } else {
            $result = 1;
        }
        if (not $result) {
            if ($!{EPIPE}) {
                # Ok, a broken pipe, the remote command has left but I still
                # haven't cleaned the connector
                diagnostic::debug("Broken pipe when sending input");
            } else {
                # Well, I don't know what to do in other cases
                diagnostic::system;
            }
        }
    }
}

sub kill($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $target;
    my @target_set;

    ($target, $body) = TakTuk::unpack($body);
    @target_set = communicator::get_target_set($target, 'local_commands');
    foreach my $command (@target_set) {
        CORE::kill -$body, $command->{pid};
    }
}

our $from;
our $to;

our @messages_pool;
our @pending_recv;

sub message($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $target;
    my @target_set = ();

    # For message handling, we always turn to the internal form
    $message = $TakTuk::message;
    ($target, $body) = TakTuk::unpack($body);
    diagnostic::debug("In message, target is $target, body is $body");
    if ($target ne "output") {
        if ($target eq "any") {
            if (scalar(@pending_recv)) {
                push @target_set, shift @pending_recv;
            } else {
                push @messages_pool, TakTuk::encode($message,
                                                  TakTuk::pack($target).$body);
            } 
        } else {
            @target_set = communicator::get_target_set($target, 'control');
        }
        foreach my $control (@target_set) {
            $control->send_message(TakTuk::encode($message, $body));
            $control->{pending_messages}++;
            if (($control->{pending_messages} == 0) and
                exists($control->{timer})) {
                $control->{timer}->unregister
                    if not $control->{timer}->{elapsed};
                delete $control->{timer};
            }
        }
    } else {
        my $root = communicator::get_root;

        ($from, $body) = TakTuk::unpack($body);
        $root->output('message', $body);
    }
}

sub numbered($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my ($father_rank, $rank, $count, $update) = split / /,$body;
    my @connections = communicator::get_connections('sinks');
    my $current = $rank;

    diagnostic::debug("Numbering from $rank, count = $count");

    if ($general::taktuk{gateway}) {
        $general::taktuk{rank} = -1;
        $ENV{TAKTUK_RANK} = -1;
    } else {
        $general::taktuk{rank} = $rank;
        $ENV{TAKTUK_RANK} = $rank;
        # Pretend to my children that I'm my father
        $rank = $father_rank;
        $current++;
    }
    $general::taktuk{count} = $count;
    $ENV{TAKTUK_COUNT} = $count;
    $general::taktuk{father} = $father_rank;
    $ENV{TAKTUK_FATHER} = $father_rank;

    $general::taktuk{child_min} = $current;
    for (my $i=0; $i<=$#connections; $i++) {
        my $other_connector = $connections[$i];
        if ($other_connector != $connector) {
            my $min = $current;
            my $max = $current + $other_connector->{count} - 1;
            if ($update and exists($other_connector->{min})
                and (($min != $other_connector->{min})
                     or (($max != $other_connector->{max})
                         and ($i != $#connections)))) {
                communicator::get_root->output('state',
                                                 TakTuk::UPDATE_FAILED);
                $min = $other_connector->{min};
                $max = $other_connector->{max};
                $other_connector->send_message(TakTuk::encode($TakTuk::spread,
                    $TakTuk::update_failed));
            } else {
                $other_connector->send_message(TakTuk::encode(
                               $TakTuk::numbered,"$rank $min $count $update"));
                $other_connector->{min} = $min;
                $other_connector->{max} = $max;
            }
            $current = $max+1;
        } else {
            diagnostic::warning("Bug : numbered coming from a sink");
        }
    }
    $general::taktuk{child_max} = $current-1;
    
    if ($general::taktuk{child_min} > $general::taktuk{child_max}) {
        $general::taktuk{child_min} = -1;
        $general::taktuk{child_max} = -1;
    }
    $ENV{TAKTUK_CHILD_MIN} = $general::taktuk{child_min};
    $ENV{TAKTUK_CHILD_MAX} = $general::taktuk{child_max};
    synchronizer::dispatch_event(TakTuk::TAKTUK_NUMBERED);
}

our %filehandles;

sub output($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    if ($general::root) {
        my ($fd, $remaining) = TakTuk::unpack($body);

        if (not exists($filehandles{$fd})) {
            open ($filehandles{$fd}, $fd) or diagnostic::system;
            # Making the output on root non blocking seems more annoying than
            # helpful...
            # do not set non blocking output on low numbered fds in root
            # otherwise this unblocks the interpreter
            #my $can_unblock = 1;
            #$can_unblock = 0 if ($fd =~ m/^>&=([0-2])$/o and $general::root);
            #(fcntl($filehandles{$fd}, F_SETFL, O_NONBLOCK)
            #    or diagnostic::system) if $can_unblock;
        }
        communicator::post_write($filehandles{$fd}, $remaining)
            or diagnostic::system;
    } else {
        diagnostic::warning("Output message received on non root node");
    }
}

sub option($$$) {
     my $message = shift;
     my $connector = shift;
     my $body = shift;
 
    my ($name, $value) = split //,$body,2;
    diagnostic::debug("Setting $name to $value in $general::taktuk{rank}");
    option::set($name, $value);
 }

sub options($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Fetching [ $body ] as options line");
    arguments::fetch_line($body);
    arguments::parse_options();
}

sub pipe($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my ($filename, $prefix) = TakTuk::unpack($body);
    my $fd = general::open_file($filename) or diagnostic::system;
    if ($fd) {
        my $command = command::new(write=>$fd, type=>settings::FD,
            data_handler=>\&communicator::process_pipe_output,
            message=>$prefix);
        $command->{remove_handler} = \&communicator::remove_pipe;
        communicator::add_connector($command, 'pipe');
        communicator::get_root->output('state', TakTuk::PIPE_STARTED);
    } else {
        communicator::get_root->output('state', TakTuk::PIPE_FAILED);
    }
}

sub position($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    ($general::position) = $body;
    $ENV{TAKTUK_POSITION} = $body;
}

sub put($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my $prefix;
    my $source;
    my $destination;
    ($prefix, $body) = TakTuk::unpack($body);
    ($source, $body) = TakTuk::unpack($body);
    ($destination, $body) = $body;
    
    diagnostic::debug("Calling send_file with $prefix, $source, ".
                        "$destination from $general::taktuk{rank}");
    $connector->send_file($prefix, $source, $destination);
}

sub quit($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    if (not $communicator::end) {
        handlers::eof($TakTuk::eof, $connector, "all");
        communicator::terminate;
        foreach my $other_connector (communicator::get_connections('sinks')) {
            diagnostic::debug("Sending quit message to $other_connector");
            $other_connector->send_message($TakTuk::quit);
        }
    }
}

sub ready($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Ready received");
    $synchronizer::father_is_ready = 1;
    synchronizer::check_ready_state;
}

sub recv_timeout($) {
    my $timer = shift;
    my $i=0;

    $timer->{connector}->send_message($TakTuk::timeout);
    $timer->{connector}->{pending_messages}++;
    while ($i<=$#pending_recv) {
        if ($pending_recv[$i] == $timer->{connector}) {
            splice @pending_recv, $i, 1;
        }
        $i++;
    }
}

our %reduce_result;
our %reduce_remaining;
our %reduce_connector;
our @reduce_pending;

use constant REDUCE_INITIALIZATION => -1;
use constant REDUCE_FINALIZATION => -2;

our %reduce_handler = ($TakTuk::reduce_count => \&reduce_count,
                       $TakTuk::reduce_tree  => \&reduce_tree,
                       $TakTuk::reduce_wait  => \&reduce_wait);

sub reduce_count ($$$$) {
    my $connector = shift;
    my $rank = shift;
    my $new_value = shift;
    my $data = shift;

    if ($rank == REDUCE_INITIALIZATION) {
        $general::numbering_update = $new_value?1:0;
        synchronizer::suspend_engine_until(TakTuk::TAKTUK_NUMBERED,
            @synchronizer::execution_engine, @synchronizer::internal_engine,
            @synchronizer::synchro_engine);
        if ($general::taktuk{gateway}) {
            return 0;
        } else {
            return 1;
        }
    } elsif ($rank == REDUCE_FINALIZATION) {
        if ($general::root) {
            # the root, numbered 0, is not counted as deployed
            $data--;
            numbered($TakTuk::numbered, communicator::get_root,
                                      "-1 0 $data $general::numbering_update");
            return undef;
        } else {
            return $data;
        }
    } else {
        if (defined($new_value)) {
            $connector->{count} = $new_value;
            return $data + $new_value; 
        } else {
            $connector->{count} = 0;
            return $data;
        }
    }
}

sub reduce_tree($$$$) {
    my $source_connector = shift;
    my $rank = shift;
    my $new_value = shift;
    my $data = shift;
    my $result;

    if ($rank == REDUCE_INITIALIZATION) {
        my $ready = $synchronizer::states[TakTuk::TAKTUK_READY] ?
                 "ready":"busy";
        my $rank = ($general::taktuk{rank} == -1) ? "X":$general::taktuk{rank};
        $result =  "['$general::host ($rank, $ready)'";

        # This reduce is special and not synchronized with connectors...
        my @sinks = communicator::get_connections('sinks');

        foreach my $connector (@sinks) {
            # propagate the reduce by ourselves for the others
            # bypass the usual gathering for uninitialized connectors
            if ($connector->{state} < $connector::initialized) {
                my $number = $connector->{$TakTuk::reduce_tree};
                $reduce_result{$TakTuk::reduce_tree}->[$number] =
                                    ", ['connecting $connector->{peer}']";
                delete $connector->{$TakTuk::reduce_tree};
                $reduce_remaining{$TakTuk::reduce_tree}--;
            } else {
                $connector->send_message(TakTuk::encode($TakTuk::reduce,
                                                        $TakTuk::reduce_tree));
            }
        }
    } elsif ($rank == REDUCE_FINALIZATION) {
        if ($general::root) {
            eval('$new_value = '.$data."]");
            general::print_tree("",$new_value);
            $result = undef;
        } else {
            $result = $data."]";
        }
    } else {
        $result = $data.",".(defined($new_value) ? $new_value : "lost");
    }
    return $result;
}

our $waiting = 0;
our $wait_target;
our $wait_remaining;
our @wait_set;

sub reduce_wait($$$$) {
    my $connector = shift;
    my $rank = shift;
    my $new_value = shift;
    my $data = shift;

    if ($rank == REDUCE_INITIALIZATION) {
        if ($general::root) {
            synchronizer::suspend_engine_until(TakTuk::WAIT_COMPLETE,
                @synchronizer::diffusion_engine, @synchronizer::synchro_engine,
                @synchronizer::execution_engine);
        }
        if ($waiting) {
            # Here we trick the reduce mechanichs to make it wait for an
            # additional result. We will provide this result upon completion of
            # all local commands
            $reduce_remaining{$TakTuk::reduce_wait}++;
        }
        return "";
    } elsif ($rank == REDUCE_FINALIZATION) {
        synchronizer::dispatch_event(TakTuk::WAIT_COMPLETE);
        if ($general::root) {
            $connector->output('state', TakTuk::WAIT_REDUCE_COMPLETE);
            return undef;
        } else {
            return "";
        }
    } else {
        return "";
    }
}

sub local_command_completed($) {
    my $command = shift;

    if ($waiting) {
        if ($wait_target eq "any") {
            $waiting--;
        } elsif ($wait_target eq "all") {
            $wait_remaining--;
            $waiting-- if $wait_remaining == 0;
        } else {
            my $i = 0;
            while (($i <= $#wait_set) and ($wait_set[$i] != $command)) {
                $i++;
            }
            if ($i <= $#wait_set) {
                splice @wait_set, $i, 1;
            }
            $waiting-- if not scalar(@wait_set);
        }
        if (not $waiting) {
            if (exists($reduce_connector{$TakTuk::reduce_wait})) {
                $reduce_remaining{$TakTuk::reduce_wait}--;
                reduce_status_analysis($TakTuk::reduce_wait);
            } else {
                synchronizer::dispatch_event(TakTuk::WAIT_COMPLETE);
            }
        }
    }
}

sub reduce($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my @connectors = (communicator::get_connections('sources'),
                      communicator::get_connections('sinks'));
    my $i;

    diagnostic::debug("Reduce in $general::taktuk{rank}");
    my ($type,$value) = TakTuk::decode($body);

    if (not exists($reduce_connector{$type})) {
        diagnostic::error("Handler not defined for reduce $type")
            if not exists($reduce_handler{$type});
        $reduce_connector{$type} = [];
        $reduce_connector{$type}->[0] = $connector;
        $reduce_remaining{$type} = 0;
        $reduce_result{$type} = [];
        $i = 0;
        foreach my $target (@connectors) {
            if ($target != $connector) {
                $i++;
                $reduce_connector{$type}->[$i] = $target;
                if (exists($target->{pending_results}->{$type})) {
                    my $results = $target->{pending_results}->{$type};
                    $reduce_result{$type}->[$i] = shift @$results;
                    delete($target->{pending_results}->{$type})
                        unless scalar(@$results);
                } else {    
                    $target->{$type} = $i;
                    $reduce_remaining{$type}++;
                }
            }
        }
        my $handler = $reduce_handler{$type};
        $reduce_result{$type}->[0] =
                  &$handler($connector, REDUCE_INITIALIZATION, $value, undef);
        reduce_status_analysis($type);
    } else {
        push @reduce_pending, [ $message, $connector, $body ];
    }
}

sub reduce_status_analysis($) {
    my $type = shift;

    if (exists($reduce_remaining{$type}) and ($reduce_remaining{$type} == 0)) {
        my $data = $reduce_result{$type};
        my $handler = $reduce_handler{$type};
        my $connector = $reduce_connector{$type};
        my $result = $data->[0];
        for (my $i=1; $i<=$#$data; $i++) {
            $result = &$handler($connector->[$i], $i, $data->[$i], $result);
        }
        $result = &$handler($connector->[0], REDUCE_FINALIZATION,
                            undef, $result);
        if (defined($result)) {
            my $reply_connector = $connector->[0];
            $reply_connector->send_message(TakTuk::encode(
                     $TakTuk::reduce_result, TakTuk::encode($type, $result)));
        }
        delete $reduce_connector{$type};
        delete $reduce_remaining{$type};
        delete $reduce_result{$type};
        if (scalar(@reduce_pending)) {
            my $next = pop @reduce_pending;
            reduce($next->[0], $next->[1], $next->[2]);
        }
    }
}

sub reduce_result($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Reduce result from $general::taktuk{rank}");
    my ($type,$value) = TakTuk::decode($body);

    if (exists($connector->{$type})) {
        $reduce_result{$type}->[$connector->{$type}] = $value;
        $reduce_remaining{$type}--;
        delete $connector->{$type};
        reduce_status_analysis($type);
    } else {
        $connector->{pending_results}->{$type} = []
            unless exists($connector->{pending_results}->{$type});
        push @{$connector->{pending_results}->{$type}}, $value;
    }
}

sub check_ongoing_reduces($) {
    my $connector = shift;

    foreach my $type (keys(%reduce_connector)) {
        if (exists($connector->{$type})) {
            $reduce_remaining{$type}--;
            $reduce_result{$type}->[$connector->{$type}] = undef;
            reduce_status_analysis($type);
        }
    }
}

sub resign($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    scheduler::resign;

    foreach my $other_connector (communicator::get_connections('sources'),
                                 communicator::get_connections('sinks')) {
        if ($other_connector != $connector) {
            if ($other_connector->{state} < $connector::initialized) {
                $other_connector->output('connector',"canceled");
                $other_connector->cancel;
            } else {
                $other_connector->send_message($TakTuk::resign);
            }
        }
    }
}

sub send_to($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    my ($to, $remaining) = TakTuk::unpack($body);
    diagnostic::debug("Message to $to and I'm $general::taktuk{rank}");

    my $new_message;
    my @destination_list = general::decode_set($to, $general::taktuk{count});
    if (not scalar(@destination_list)) {
        diagnostic::error("Invalid set specification : $to");
        communicator::get_root->output('state', TakTuk::INVALID_DESTINATION);
    }
    my @upward = ();
    my @downward = ();
    my $delivery = 0;
    my $min = shift @destination_list;
    my $max = shift @destination_list;
    my $local_min;

    if ($general::taktuk{gateway}) {
        $local_min = $general::taktuk{child_min};
    } else {
        $local_min = $general::taktuk{rank};
    }

    # propagation upward of low numbered destinations
    while (defined($min) and ($min < $local_min)) {
        if ($max >= $local_min) {
            push @upward, $min, $local_min-1;
            unshift @destination_list, $local_min, $max;
        } else {
            push @upward, $min, $max;
        }
        $min = shift @destination_list;
        $max = shift @destination_list;
    }
    # local delivering
    if (defined($min) and ($min == $general::taktuk{rank})) {
        $delivery = 1;
        if ($max == $general::taktuk{rank}) {
            $min = shift @destination_list;
            $max = shift @destination_list;
        } else {
            $min++;
        }
    }
    # propagation downward of destination within children interval
    my $i=0;
    my @sinks = communicator::get_connections('sinks');
    while (defined($min) and ($min <= $general::taktuk{child_max})) {
        # propagation upward of high numbered destinations
        if ($max > $general::taktuk{child_max}) {
            push @upward, $general::taktuk{child_max}+1, $max;
            $max = $general::taktuk{child_max};
        }
        # move on to the next involved connector
        while (($i <= $#sinks) and ($min > $sinks[$i]->{max})) {
            # flush any pending forwarding from the last iteration
            if (scalar(@downward)) {
                $new_message = TakTuk::encode($message,
                    TakTuk::pack(general::encode_set(@downward)).$remaining);
                $sinks[$i]->send_message($new_message);
                @downward = ();
            }
            $i++;
        }
        # if some destination are out of range, isolate them
        if (($i <= $#sinks) and ($min < $sinks[$i]->{min}) and
            ($max >= $sinks[$i]->{min})) {
            unshift @destination_list, $sinks[$i]->{min}, $max;
            $max = $sinks[$i]->{min}-1;
        }
        # handle the case where no connector match for a downward destination
        if (($i > $#sinks) or ($min < $sinks[$i]->{min})) {
            # I got a small issue : some destinations are not available
            diagnostic::warning("Send problem, ".
                (($min != $max)?"$min-$max":"$min")." not available anymore");
            communicator::get_root->output('state',
                                             TakTuk::UNAVAILABLE_DESTINATION);
        }
        # otherwise extract the slice matching connector range and add it the
        # the set that must be propagated
        else {
            if ($max > $sinks[$i]->{max}) {
                unshift @destination_list, $sinks[$i]->{max}+1, $max;
                $max = $sinks[$i]->{max};
            }
            push @downward, $min, $max;
        }
        # proceed to the next interval
        $min = shift @destination_list;
        $max = shift @destination_list;
    }
    if (scalar(@downward)) {
        $new_message = TakTuk::encode($message,
            TakTuk::pack(general::encode_set(@downward)).$remaining);
        $sinks[$i]->send_message($new_message);
    }
    # propagation upward of high numbered destinations
    while (defined($min)) {
        push @upward, $min, $max;
        $min = shift @destination_list;
        $max = shift @destination_list;
    }
    if (scalar(@upward)) {
        if ($general::root) {
            diagnostic::warning("Send problem, ".general::encode_set(@upward).
                                " is(are) invalid destination(s)");
        } else {
            $new_message = TakTuk::encode($message,
                TakTuk::pack(general::encode_set(@upward)).$remaining);
            communicator::get_root->send_message($new_message);
        }
    }
    # actual local delivery
    if ($delivery) {
        diagnostic::debug("Delivered message");
        communicator::get_root->output('state', TakTuk::MESSAGE_DELIVERED);
        communicator::process_message($connector, $remaining);
    }
}

sub spread($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    broadcast($message, $connector, $body);
    diagnostic::debug("Handling message locally");
    communicator::process_message($connector, $body);
}

sub steal($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Steal request : $body, connector : $connector");
    scheduler::theft_handler($connector, $body);
    synchronizer::check_ready_state;
}

sub synchronize($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    communicator::process_message($connector, $body);
}

sub taktuk_code($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Taktuk code received");
    $general::taktuk_code = $body;
}

sub taktuk_perl($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my ($options, $arguments, $filename, $attributes);

    ($attributes, $body) = TakTuk::unpack($body);
    if ($body =~ /(?:^|\s)--(?:$|\s)/) {
        ($options, $arguments) = split /(?:^|\s)--(?:$|\s)/,$body,2;
        $arguments = "" if not defined($arguments);
    } else {
        ($options, $arguments) = ("", $body);
    }
    ($filename, $arguments) = split /\s/, $arguments, 2;
    $filename = "" if not defined($filename);
    $arguments = "" if not defined($arguments);
    diagnostic::debug("Taktuk perl execution, options [$options], filename ".
                      "[$filename], arguments [$arguments]");
    my $command = execute($TakTuk::execute, $connector,
                      TakTuk::pack($attributes).
                      "$general::perl_interpreter $options -- - $arguments");
    if ($command) {
        $command->{line} = "taktuk_perl";
        $command->{line} .= " $body" if $body;
        general::load_taktuk_package('TakTuk');
        communicator::post_write($command->{read}, "{")
            or diagnostic::system;
        communicator::post_write($command->{read}, $general::taktuk_package)
            or diagnostic::system;
        communicator::post_write($command->{read}, "}package main;")
            or diagnostic::system;
        if ($filename and ($filename ne "-")) {
            $filename = qx{echo "$filename"};
            chomp($filename);
            communicator::post_write($command->{read},
                          general::load_file($filename)) or diagnostic::system;
            communicator::post_close($command);
        }
    }
}

sub wait($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;
    my $reduce;

    ($reduce, $wait_target) = TakTuk::unpack($body);

    if (not $reduce or not $general::root) {
        if (($wait_target eq "any") or ($wait_target eq "all")) {
            $wait_remaining =
                scalar(communicator::get_connections('local_commands'));
            $waiting++ if $wait_remaining;
        } else {
            @wait_set =
                communicator::get_target_set($wait_target, 'local_commands');
            $waiting++ if scalar(@wait_set);
        }
    }
    if ($reduce) {
        reduce($TakTuk::reduce, $connector, $TakTuk::reduce_wait);
    } elsif ($waiting) {
        synchronizer::suspend_engine_until(TakTuk::WAIT_COMPLETE,
            @synchronizer::execution_engine, @synchronizer::synchro_engine);
    } else {
        synchronizer::dispatch_event(TakTuk::WAIT_COMPLETE);
    }
}

sub wait_message($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    # Notice that the following method works only beacause there is at most one
    # blocked recv per process (other processes match other connectors and the
    # recv is in mutual exclusion).
    $connector->{pending_messages}--;
    if ($connector->{pending_messages} < 0) {
        push @pending_recv, $connector;
        if (scalar(@messages_pool)) {
            my ($code, $remaining) = TakTuk::decode(shift @messages_pool);
            message($code, undef, $remaining);
        }
    }
    if (($connector->{pending_messages} < 0) and $body and ($body > 0)) {
        my $timer = timer->register($body,\&recv_timeout);
        $timer->{connector} = $connector;
        $connector->{timer} = $timer;
    }
}

sub work($$$) {
    my $message = shift;
    my $connector = shift;
    my $body = shift;

    diagnostic::debug("Work received : $body");
    scheduler::dispatch_work($body);
    synchronizer::check_ready_state;
}

sub init() {
    handlers::register_handler($TakTuk::arguments, \&arguments);
    handlers::register_handler($TakTuk::broadcast, \&broadcast);
    handlers::register_handler($TakTuk::command_message, \&message);
    handlers::register_handler($TakTuk::command_send_to, \&send_to);
    handlers::register_handler($TakTuk::down, \&down);
    handlers::register_handler($TakTuk::eof, \&eof);
    handlers::register_handler($TakTuk::execute, \&execute);
    handlers::register_handler($TakTuk::file, \&file);
    handlers::register_handler($TakTuk::forward_up, \&forward_up);
    handlers::register_handler($TakTuk::gateway, \&gateway);
    handlers::register_handler($TakTuk::get, \&get);
    handlers::register_handler($TakTuk::get_info, \&get_info);
    handlers::register_handler($TakTuk::input, \&input);
    handlers::register_handler($TakTuk::kill, \&kill);
    handlers::register_handler($TakTuk::message, \&message);
    handlers::register_handler($TakTuk::numbered, \&numbered);
    handlers::register_handler($TakTuk::output, \&output);
    handlers::register_handler($TakTuk::option, \&option);
    handlers::register_handler($TakTuk::options, \&options);
    handlers::register_handler($TakTuk::pipe, \&pipe);
    handlers::register_handler($TakTuk::position, \&position);
    handlers::register_handler($TakTuk::put, \&put);
    handlers::register_handler($TakTuk::quit, \&quit);
    handlers::register_handler($TakTuk::ready, \&ready);
    handlers::register_handler($TakTuk::reduce, \&reduce);
    handlers::register_handler($TakTuk::reduce_result, \&reduce_result);
    handlers::register_handler($TakTuk::resign, \&resign);
    handlers::register_handler($TakTuk::send_to, \&send_to);
    handlers::register_handler($TakTuk::spread, \&spread);
    handlers::register_handler($TakTuk::steal, \&steal);
    handlers::register_handler($TakTuk::synchronize, \&synchronize);
    handlers::register_handler($TakTuk::taktuk_code, \&taktuk_code);
    handlers::register_handler($TakTuk::taktuk_perl, \&taktuk_perl);
    handlers::register_handler($TakTuk::update_failed, \&update_failed);
    handlers::register_handler($TakTuk::wait, \&wait);
    handlers::register_handler($TakTuk::wait_message, \&wait_message);
    handlers::register_handler($TakTuk::work, \&work);
}

###############################################
### MAIN                                    ###
###############################################

package main;
use strict; use bytes;

our $taktuk_interpreter = undef;
our $in_interpreter = 1;
our $interactive = 0;
our $forced_interactive = 0;
our $no_numbering = 0;
our $terminate = 0;
our $quit_message = $TakTuk::quit;

our $taktuk_side;
our $interpreter_side;

sub is_one_of($@) {
    my $prefix = shift;
    my $found = undef;
    my $number_found = 0;

    foreach my $fullname (@_) {
        if ($fullname =~ m/^$prefix/) {
            $found = $fullname;
            $number_found++;
        }
    }
    $prefix=$found if ($number_found == 1);
    return $prefix;
}

sub get_attributes() {
    my $attributes = "";
    my $timeout_pack = "";
    my $argument = arguments::get_next_argument;

    while ($argument =~ m/^[a-z]+$/o) {
        $argument = is_one_of($argument, qw(timeout action kill));
        if ($argument eq "timeout") {
            my $value = arguments::get_next_argument;
            
            if (length($timeout_pack)) {
                $attributes .= TakTuk::pack($timeout_pack);
                $timeout_pack = "";
            }
            $timeout_pack = TakTuk::encode($TakTuk::timeout,
                            TakTuk::pack($value));
        } elsif ($argument eq "action") {
            my ($message, $type, $data) = translate;
            if (length($timeout_pack)) {
                if (not $type) {
                    $timeout_pack .= TakTuk::pack(
                                     TakTuk::encode($TakTuk::action, $message))
                        if defined($message);
                } else {
                    diagnostic::warning("Invalid attribute action");
                }
            } else {
                diagnostic::warning("Action requires timeout specification");
            }
        } elsif ($argument eq "kill") {
            my $value = arguments::get_next_argument;

            if ($value =~ m/^\d+$/) {
                if (length($timeout_pack)) {
                    $timeout_pack .= TakTuk::pack(TakTuk::encode($TakTuk::kill,
                                                  $value));
                } else {
                    diagnostic::warning("Kill requires timeout specification");
                }
            } else {
                diagnostic::error("Invalid signal number for kill");
            }
        } elsif ($argument eq "target") {
            my $value = arguments::get_next_argument;
            $attributes .= TakTuk::pack(TakTuk::encode($TakTuk::id, $value));
        } else {
            diagnostic::warning("Unknown option $argument for exec");
        }
        $argument = arguments::get_next_argument;
    } 
    $attributes .= TakTuk::pack($timeout_pack) if length($timeout_pack);
    arguments::restore_last_argument;
    diagnostic::debug("Exec attributes : $attributes");
    return $attributes;
}

sub translate() {
    my $message = undef;
    my $type = "";
    my $data = undef;
    my @commands = qw(broadcast downcast exec get help input kill message
                      network option put synchronize taktuk_perl version quit
                      wait);
    my $found="";
    my $number_found=0;
    my $command;

    # because of e.g. help, should take commands separators into account
    $command = arguments::get_next_command;
    if (not $arguments_ended and ($command =~ m/^[a-z]+$/o)) {
        $command = is_one_of($command, @commands);
    }
    
    if ($arguments_ended) {
    } elsif ($command =~ m/^\s*$/o) {
    } elsif ($command =~ /^\d/) {
        ($message, $type, $data) = translate();
        $message = TakTuk::encode($TakTuk::command_send_to,
                    TakTuk::pack($command).$message) if (defined($message));
    } elsif ($command eq "broadcast") {
        ($message, $type, $data) = translate();
        $message = TakTuk::encode($TakTuk::broadcast, $message)
            if (defined($message));
    } elsif ($command eq "downcast") {
        ($message, $type, $data) = translate();
        $message = TakTuk::encode($TakTuk::down, TakTuk::encode(
                         $TakTuk::broadcast, $message)) if (defined($message));
    } elsif ($command eq "exec") {
        my $attributes = get_attributes;
        my $parameters = arguments::get_parameters;
        if (defined($parameters)) {
            $message = TakTuk::encode($TakTuk::execute,
                                       TakTuk::pack($attributes).$parameters);
        } else {
            $terminate = 1;
        }
    } elsif ($command eq "get") {
        my $source = arguments::get_parameters;
        my $destination = arguments::get_parameters;
        if (defined($source) and defined($destination)) {
            $message = "";
            $type = $TakTuk::get;
            $data = [ $source, $destination ];
        } else {
            $terminate = 1;
        }
    } elsif ($command eq "help") {
        general::print_help;
    } elsif (($command eq "input") or ($command eq "message")) {
        my @keywords;
        my $message_code;
        my $target;

        # because of close, should take commands separators into account
        my $name = arguments::get_next_command;
        if (defined($name) and ($name =~ m/^[a-z]+$/)) {
            $name = is_one_of($name, "target");
        }
        if ($name eq "target") {
            $target = arguments::get_next_argument;
            $name = arguments::get_next_command;
        } else {
            $target = ($command eq "input") ? "all" : "any";
        }

        if ($command eq "input") {
            @keywords = qw(close data file line pipe);
            $message_code = TakTuk::encode($TakTuk::input,
                                                        TakTuk::pack($target));
        } else {
            @keywords = qw(data file line pipe);
            $message_code = TakTuk::encode($TakTuk::command_message,
                   TakTuk::pack($target).TakTuk::pack(0));
        }

        if (defined($name) and ($name =~ m/^[a-z]+$/)) {
            $name = is_one_of($name, @keywords);
        } else {
            arguments::restore_last_command;
            $name = "data";
        }

        if (($name eq "close") and ($command eq "input")) {
            $message = TakTuk::encode($TakTuk::eof, $target);
        } else {
            my $parameters = arguments::get_parameters;
            if (defined($parameters)) {
                if ($name eq "data") {
                    $message = TakTuk::encode($message_code, $parameters);
                } elsif ($name eq "line") {
                    $message = TakTuk::encode($message_code,$parameters."\n");
                } elsif ($name eq "file") {
                    $message = "";
                    $type = $TakTuk::file;
                    $data = general::open_file($parameters);
                    $message = $message_code if $data;
                } elsif ($name eq "pipe") {
                    $message = "";
                    $type = $TakTuk::pipe;
                    $data = $parameters;
                    $message = $message_code;
                } else {
                    diagnostic::warning("Unknown input type, ignoring command");
                }
            } else {
                $terminate = 1;
            }
        }
    } elsif ($command eq "kill") {
        my $target;

        my $name = arguments::get_next_command;
        if (defined($name) and ($name =~ m/^[a-z]+$/)) {
            $name = is_one_of($name, "target");
        }
        if ($name eq "target") {
            $target = arguments::get_next_command;
            $name = arguments::get_next_command;
        } else {
            $target = "all";
        }

        if ($name) {
            $message = TakTuk::encode($TakTuk::kill,
                                             TakTuk::pack($target).$name);
        } else {
            $message = TakTuk::encode($TakTuk::kill, TakTuk::pack($target).15);
        }
    } elsif ($command eq "network") {
        my $subcommand = arguments::get_next_command;

        if (defined($subcommand) and ($subcommand =~ m/^[a-z]+$/)) {
            $subcommand = is_one_of($subcommand,
                                             qw(cancel state renumber update));
        }
        if ($subcommand eq "cancel") {
            $message = $TakTuk::resign;
        } elsif (($subcommand eq "state") or ($subcommand eq "")) {
            if ($general::root) {
                $message =
                    TakTuk::encode($TakTuk::reduce, $TakTuk::reduce_tree);
            } else {
                diagnostic::warning("Cannot print tree from non root node");
            }
        } elsif ($subcommand eq "renumber") {
            if ($general::root) {
                $message = TakTuk::encode($TakTuk::spread,
                       TakTuk::encode($TakTuk::reduce, $TakTuk::reduce_count));
            } else {
                diagnostic::warning("Cannot renumber from non root node");
            }
        } elsif ($subcommand eq "update") {
            if ($general::root) {
                $message = TakTuk::encode($TakTuk::spread,
                    TakTuk::encode($TakTuk::reduce, $TakTuk::reduce_count.1));
            } else {
                diagnostic::warning("Cannot update from non root node");
            }
        } else {
            diagnostic::warning("Unknwon network command $subcommand");
        }
    } elsif ($command eq "option") {
        my $name = arguments::get_next_argument;

        if (defined($name) and ($name =~ m/^[-a-z]+$/)) {
            my $parameters = arguments::get_parameters;
            if (defined($parameters)) {
                $name = $option::short_name{$name} if (length($name) > 1);
                $message = TakTuk::encode($TakTuk::option, $name.$parameters);
            } else {
                $terminate = 1;
            }
        } else {
            arguments::restore_last_argument;
            my $parameters = arguments::get_parameters;
            if (defined($parameters)) {
                $message = TakTuk::encode($TakTuk::options, $parameters);
            } else {
                $terminate = 1;
            }
        }
    } elsif ($command eq "put") {
        my $source = arguments::get_parameters;
        my $destination = arguments::get_parameters;
        if (defined($source) and defined($destination)) {
            $message = "";
            $type = $TakTuk::put;
            $data = [ $source, $destination ];
        } else {
            $terminate = 1;
        }
    } elsif ($command eq "quit") {
        $message = $quit_message;
        # Don't terminate here because the quit might be sent to some other node
    } elsif ($command eq "synchronize") {
        ($message, $type, $data) = translate();
        $message = TakTuk::encode($TakTuk::synchronize, $message)
            if (defined($message));
    } elsif ($command eq "taktuk_perl") {
        my $attributes = get_attributes;
        my $parameters = arguments::get_parameters;
        if (defined($parameters)) {
            $message = TakTuk::encode($TakTuk::taktuk_perl,
                                      TakTuk::pack($attributes).$parameters);
        } else {
            $terminate = 1;
        }
    } elsif ($command eq "version") {
        arguments::print_version;
    } elsif ($command eq "wait") {
        my $subcommand = arguments::get_next_command;
        my $reduce = 0;
        my $unknown = 0;
        my $target;

        if (defined($subcommand) and ($subcommand =~ m/^[a-z]+$/)) {
            $subcommand = is_one_of($subcommand, qw(reduce target));
        }
        if ($subcommand eq "reduce") {
            if ($general::root) {
                # Wait all is not implemented directly as the spread of a
                # reduce to be sure successive wait commands are sequentialized
                # with other commands (because reduces are not suspended during
                # the wait, this could hang TakTuk)
                $reduce = 1;
                $message = TakTuk::encode($TakTuk::spread, $TakTuk::wait);
                $subcommand = arguments::get_next_command;
                if (defined($subcommand) and ($subcommand =~ m/^[a-z]+$/)) {
                    $subcommand = is_one_of($subcommand, qw(target));
                }
            } else {
                diagnostic::warning("Cannot wait reduce from non root node");
                $message = "";
            }
        } else {
            $message = $TakTuk::wait;
        }
        if ($subcommand eq "target") {
            $target = arguments::get_next_command;
            $message = TakTuk::encode($message, TakTuk::pack($reduce).$target);
        } else {
            diagnostic::warning("Expected 'target' instead of $subcommand");
            $message = "";
        }
    } else {
        diagnostic::error("Unknown command : $command");
    }
    return ($message, $type, $data);
}

sub terminate_interpreter() {
    exit 0;
}

sub fork_taktuk_interpreter() {
    ($interpreter_side, $taktuk_side) = communicator::create_channel;
    $taktuk_interpreter = fork();
    if (not defined($taktuk_interpreter)) {
        diagnostic::system;
        # I'm quite worried in this case. The fork interpreter is mandatory in
        # the root node
        diagnostic::error("FATAL : cannot continue without forked interpreter");
        exit 1;
    }
    if (not $taktuk_interpreter) {
        $SIG{INT} = \&terminate_interpreter;
        if ($arguments::arguments_ended or $forced_interactive) {
            diagnostic::debug("Interactive mode");
            if ($arguments::arguments_ended) {
                arguments::fetch_arguments(\*STDIN);
            } else {
                $interactive = 1;
            }
        }
        $taktuk_side->cleanup;
        communicator::cleanup;
        arguments::initialize_terminal;
        process_commands();
        $interpreter_side->cleanup;
        exit 0;
    } else {
        # This one is not necessary as the node 0 does not execute anything
        # It will serve to detect interpreter termination
        $interpreter_side->cleanup;
        $taktuk_side->{remove_handler} = \&communicator::remove_interpreter;
        communicator::add_connector($taktuk_side, 'interpreter');
    }
}

sub handle_message($) {
    my $message = shift;

    if (defined($taktuk_interpreter)) {
        $interpreter_side->send_message($message);
        communicator::flush_pending_stuff;
    } else {
        communicator::process_message(undef, $message);
    }
}

sub process_commands() {
    my $message;
    my $type;
    my $data;

    handle_message(TakTuk::encode($TakTuk::spread,
                   TakTuk::encode($TakTuk::reduce, $TakTuk::reduce_count)))
         if (($general::root) and !$no_numbering);
    while (not $arguments::arguments_ended and not $terminate) {
        ($message, $type, $data) = translate();
        #diagnostic::warning("Message $message type $type data $data");
        arguments::skip_command_separator unless $arguments::arguments_ended;
        if (defined($message)) {
            if ($type eq $TakTuk::file) {
                my $result;
                my $partial_message;
                my $buffer;

                # I read half less than $TakTuk::read_size to minimize
                # the chances of having fragmented taktuk packets
                $result = sysread($data, $buffer, $TakTuk::read_size/2);
                while ($result) {
                    $partial_message = TakTuk::encode($message, $buffer);
                    diagnostic::debug("Message to send : $partial_message");
                    handle_message($partial_message);
                    $result = sysread($data, $buffer, $TakTuk::read_size/2);
                }
                diagnostic::system if not defined($result);
                CORE::close($data) if ($data != \*STDIN);
            } elsif ($type eq $TakTuk::pipe) {
                my $new_message = TakTuk::encode($TakTuk::pipe,
                                                TakTuk::pack($data).$message);
                handle_message($new_message);
            } elsif (($type eq $TakTuk::put) or ($type eq $TakTuk::get)) {
                if ($message) {
                    my $new_message = TakTuk::encode($type, TakTuk::pack(
                                $message).TakTuk::pack($data->[0]).$data->[1]);
                    handle_message($new_message);
                } else {
                    diagnostic::warning("get/put require a destination ".
                                        "modifier");
                }
            } else {
                diagnostic::debug("Message to send : $message");
                handle_message($message);
            }
        }
        if ($arguments::arguments_ended and $interactive) {
            arguments::fetch_arguments(\*STDIN);
            $interactive = 0;
        }
    }
    diagnostic::debug("End of process commands");
    diagnostic::debug("Args ended : $arguments::arguments_ended ".
                      "Terminate : $terminate");
}

TakTuk::no_flush(\*STDOUT);
# Order of the following matters:
# general wich sets some general values and does not rely on others inits
# then handlers to enable diagnostic messages (might occur in arguments init)
# then arguments to parse environment
# then communicator that sets some taktuk environment variables that would
# conflict with arguments init if set earlier
general::init;
handlers::init;
arguments::init;
communicator::init;
synchronizer::init;

# suspend the diffusion engine
# This call will synchronize all broadcast-like operations with the deployment
# Must come after handlers::init as it replaces some handlers
# Must come before the ready state check (of course). This implies that this
# should be called before parsing options, because options parsing starts some
# deployments that might get initialized and cause a call to check_ready_state
synchronizer::suspend_engine_until(TakTuk::TAKTUK_READY,
                                   @synchronizer::diffusion_engine);
arguments::fetch_arguments(@ARGV);
arguments::parse_options;
# This call will synchronize all executions (even local ones) with the logical
# nodes numbering (should be ok after options parsing)
synchronizer::setup_synchronization;

if ($general::root) {
    $synchronizer::father_is_ready = 1;
    # Commands in nodes other than root are sent along with arguments using
    # an 'arguments' message
    fork_taktuk_interpreter;
} else {
    general::print($connector::init_string.$TakTuk::VERSION_NETPROTO."\n");
}
$in_interpreter = 0;

# has to be called once after arguments parsing and 'father_is_ready' setting
# for the case in which there are no connectors to deploy
# Other tests will be called on connector initialization complete or on
# connection errors
synchronizer::check_ready_state;

# Useful especially for stealing if I've nothing to do
scheduler::schedule;
communicator::run;
diagnostic::debug("End of the taktuk code");
communicator::get_root()->output('state', TakTuk::TAKTUK_TERMINATED);
# This kills the interpreter (jsut in case the termination came form elsewhere,
# a quit command for instance)
if ($general::root) {
    kill 'INT', $taktuk_interpreter;
    waitpid $taktuk_interpreter, 0;
}
exit 0;
# WARNING : avoid to put anything below the following line if you want the
# autoload feature to run smoothly
__END__