This file is indexed.

/usr/share/singular/LIB/tropical.lib is in singular-data 4.0.3+ds-1.

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

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
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
//
version="version tropical.lib 4.0.0.0 Dec_2013 ";
category="Tropical Geometry";
info="
LIBRARY:         tropical.lib  Computations in Tropical Geometry

AUTHORS:         Anders Jensen Needergard, email: jensen@math.tu-berlin.de
@*               Hannah Markwig,  email: hannah@uni-math.gwdg.de
@*               Thomas Markwig,  email: keilen@mathematik.uni-kl.de

WARNING:
- tropicalLifting will only work with LINUX and if in addition gfan is installed.
@*- drawTropicalCurve and drawTropicalNewtonSubdivision will only display the
@*  tropical curve with LINUX and if in addition latex and kghostview
@*  are installed.
@*- For tropicalLifting in the definition of the basering the parameter t
@*  from the Puiseux series field C{{t}} must be defined as a variable,
@*  while for all other procedures it must be defined as a parameter.

THEORY:
  Fix some base field K and a bunch of lattice points v0,...,vm in the integer
  lattice Z^n, then this defines a toric variety as the closure of (K*)^n in
  the projective space P^m, where the torus is embedded via the map sending a
  point x in (K*)^n to the point (x^v0,...,x^vm).
  The generic hyperplane sections are just the images of the hypersurfaces
  in (K*)^n defined by the polynomials f=a0*x^v0+...+am*x^vm=0. Some properties
  of these hypersurfaces can be studied via tropicalisation.

  For this we suppose that K=C{{t}} is the field of Puiseux series over the
  field of complex numbers (or any other field with a valuation into the real
  numbers). One associates to the hypersurface given by f=a0*x^v0+...+am*x^vm
  the tropical hypersurface defined by the tropicalisation
  trop(f)=min{val(a0)+<v0,x>,...,val(am)+<vm,x>}.
  Here, <v,x> denotes the standard scalar product of the integer vector v in Z^n
  with the vector x=(x1,...,xn) of variables, so that trop(f) is a piecewise
  linear function on R^n. The corner locus of this function (i.e. the points
  at which the minimum is attained a least twice) is the tropical hypersurface
  defined by trop(f).
  The theorem of Newton-Kapranov states that this tropical hypersurface is
  the same as if one computes pointwise the valuation of the hypersurface
  given by f. The analogue holds true if one replaces one equation f by an
  ideal I. A constructive proof of the theorem is given by an adapted
  version of the Newton-Puiseux algorithm. The hard part is to find a point
  in the variety over C{{t}} which corresponds to a given point in the
  tropical variety.

  It is the purpose of this library to provide basic means to deal with
  tropical varieties. Of course we cannot represent the field of Puiseux
  series over C in its full strength, however, in order to compute interesting
  examples it will be sufficient to replace the complex numbers C by the
  rational numbers Q and to replace Puiseux series in t by rational functions
  in t, i.e. we replace C{{t}} by Q(t), or sometimes even by Q[t].
  Note, that this in particular forbids rational exponents for the t's.

  Moreover, in @sc{Singular} no negative exponents of monomials are allowed, so
  that the integer vectors vi will have to have non-negative entries.
  Shifting all exponents by a fixed integer vector does not change the
  tropicalisation nor does it change the toric variety. Thus this does not
  cause any restriction.
  If, however, for some reason you prefer to work with general vi, then you
  have to pass right away to the tropicalisation of the equations, whereever
  this is allowed -- these are linear polynomials where the constant coefficient
  corresponds to the valuation of the original coefficient and where
  the non-constant coefficient correspond to the exponents of the monomials,
  thus they may be rational numbers respectively negative numbers:
  e.g. if f=t^{1/2}*x^{-2}*y^3+2t*x*y+4  then  trop(f)=min{1/2-2x+3y,1+x+y,0}.

  The main tools provided in this library are as follows:
@*  - tropicalLifting    implements the constructive proof of the Theorem of
                         Newton-Kapranov and constructs a point in the variety
                         over C{{t}} corresponding to a given point in the
                         corresponding tropical variety associated to an
                         ideal I; the generators of I have to be in the
                         polynomial ring Q[t,x1,...,xn] considered as a
                         subring of C{{t}}[x1,...,xn]; a solution will be
                         constructed up to given order; note that several
                         field extensions of Q might be necessary throughout
                         the intermediate computations; the procedures use
                         the external program gfan
@*  - puiseuxExpansion   computes a Newton-Puiseux expansion of a plane curve
                         singularity
@*  - drawTropicalCurve  visualises a tropical plane curve either given by a
                         polynomial in Q(t)[x,y] or by a list of linear
                         polynomials of the form ax+by+c with a,b in Z and c
                         in Q; latex must be installed on your computer
@*  - tropicalJInvariant computes the tropical j-invaiant of a tropical
                         elliptic curve
@*  - jInvariant         computes the j-invariant of an elliptic curve
@*  - weierstrassForm     computes the Weierstrass form of an elliptic curve

PROCEDURES FOR TROPICAL LIFTING:
  tropicalLifting()          computes a point in the tropical variety
  displayTropicalLifting()   displays the output of tropicalLifting
  puiseuxExpansion()         computes a Newton-Puiseux expansion in the plane
  displayPuiseuxExpansion()  displays the output of puiseuxExpansion

PROCEDURES FOR DRAWING TROPICAL CURVES:
  tropicalCurve()            computes a tropical curve and its Newton subdivision
  drawTropicalCurve()        produces a post script image of a tropical curve
  drawNewtonSubdivision()    produces a post script image of a Newton subdivision

PROCEDURES FOR J-INVARIANTS:
  tropicalJInvariant()       computes the tropical j-invariant of a tropical curve
  weierstrassForm()          computes the Weierstrass form of a cubic polynomial
  jInvariant()               computes the j-invariant of a cubic polynomial

GENERAL PROCEDURES:
  conicWithTangents()  computes a conic through five points with tangents
  tropicalise()        computes the tropicalisation of a polynomial
  tropicaliseSet()     computes the tropicalisation several polynomials
  tInitialForm()       computes the tInitial form of a polynomial in Q[t,x_1,...,x_n]
  tInitialIdeal()      computes the tInitial ideal of an ideal in Q[t,x_1,...,x_n]
  initialForm()        computes the initial form of poly in Q[x_1,...,x_n]
  initialIdeal()       computes the initial ideal of an ideal in Q[x_1,...,x_n]

PROCEDURES FOR LATEX CONVERSION:
  texNumber()          outputs the texcommand for the leading coefficient of poly
  texPolynomial()      outputs the texcommand for the polynomial poly
  texMatrix()          outputs the texcommand for the matrix
  texDrawBasic()       embeds output of texDrawTropical in a texdraw environment
  texDrawTropical()    computes the texdraw commands for a tropical curve
  texDrawNewtonSubdivision()   computes texdraw commands for a Newton subdivision
  texDrawTriangulation()       computes texdraw commands for a triangulation

AUXILARY PROCEDURES:
  radicalMemberShip()     checks radical membership
  tInitialFormPar()       computes the t-initial form of poly in Q(t)[x_1,...,x_n]
  tInitialFormParMax()    same as tInitialFormPar, but uses maximum
  solveTInitialFormPar()  displays approximated solution of a 0-dim ideal
  detropicalise()         computes the detropicalisation of a linear form
  tDetropicalise()        computes the detropicalisation of a linear form
  dualConic()             computes the dual of an affine plane conic
  parameterSubstitute()   substitutes in the polynomial the parameter t by t^N
  tropicalSubst()         makes certain substitutions in a tropical polynomial
  randomPolyInT()         computes a polynomial with random coefficients
  cleanTmp()              clears /tmp from files created by other procedures

KEYWORDS:        tropical curves; tropical polynomials

";

///////////////////////////////////////////////////////////////////////////////
/// Auxilary Static Procedures in this Library
///////////////////////////////////////////////////////////////////////////////
/// - phiOmega
/// - cutdown
/// - tropicalparametriseNoabs
/// - findzeros
/// - basictransformideal
/// - testw
/// - simplifyToOrder
/// - scalarproduct
/// - intvecdelete
/// - invertorder
/// - ordermaximalidealsNoabs
/// - displaypoly
/// - displaycoef
/// - choosegfanvector
/// - tropicalliftingresubstitute
/// - tropicalparametrise
/// - eliminatecomponents
/// - findzerosAndBasictransform
/// - ordermaximalideals
/// - verticesTropicalCurve
/// - bunchOfLines
/// - clearintmat
/// - sortintvec
/// - sortintmat
/// - intmatcoldelete
/// - intmatconcat
/// - minInIntvec
/// - positionInList
/// - sortlist
/// - minInList
/// - vergleiche
/// - koeffizienten
/// - minOfPolys
/// - shorten
/// - minOfStringDecimal
/// - decimal
/// - stringcontainment
/// - stringdelete
/// - stringinsert
/// - texmonomial
/// - texcoefficient
/// - abs
/// - findNonLoopVertex
/// - coordinatechange
/// - weierstrassFormOfACubic
/// - weierstrassFormOfA4x2Curve
/// - weierstrassFormOfA2x2Curve
/// - jInvariantOfACubic
/// - jInvariantOfA4x2Curve
/// - jInvariantOfA2x2Curve
/// - jInvariantOfAPuiseuxCubic
//////////////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////////////
LIB "random.lib";
LIB "solve.lib";
LIB "poly.lib";
LIB "elim.lib";
LIB "linalg.lib";
LIB "polymake.lib";
LIB "primdec.lib";
LIB "absfact.lib";
LIB "hnoether.lib";
LIB "ring.lib";
//////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
/// Procedures concerned with tropical parametrisation
///////////////////////////////////////////////////////////////////////////////

proc tropicalLifting (ideal i,intvec w,int ordnung,list #)
"USAGE:  tropicalLifting(i,w,ord[,opt]); i ideal, w intvec, ord int, opt string
ASSUME:  - i is an ideal in Q[t,x_1,...,x_n], w=(w_0,w_1,...,w_n)
           and (w_1/w_0,...,w_n/w_0) is in the tropical variety of i,
           and ord is the order up to which a point in V(i) over Q{{t}}
           lying over (w_1/w_0,...,w_n/w_0) shall be computed;
           w_0 may NOT be ZERO
@*       - the basering should not have any parameters on its own
           and it should have a global monomial ordering,
           e.g. ring r=0,(t,x(1..n)),dp;
@*       - the first variable of the basering will be treated as the
           parameter t in the Puiseux series field
@*       - the optional parameter opt should be one or more strings among
           the following:
@*         'isZeroDimensional'  : the dimension i is zero (not to be checked);
@*         'isPrime'            : the ideal is prime over Q(t)[x_1,...,x_n]
                                  (not to be checked);
@*         'isInTrop'           : (w_1/w_0,...,w_n/w_0) is in the tropical
                                  variety (not to be checked);
@*         'oldGfan'            : uses gfan version 0.2.1 or less
@*         'findAll'            : find all solutions of a zero-dimensional
                                  ideal over (w_1/w_0,...,w_n/w_0)
@*         'noAbs'              : do NOT use absolute primary decomposition
@*         'puiseux'            : n=1 and i is generated by one equation
@*         'noResubst'          : avoids the computation of the resubstitution
RETURN:  IF THE OPTION 'findAll' WAS NOT SET THEN:
@*       list, containing one lifting of the given point (w_1/w_0,...,w_n/w_0)
               in the tropical variety of i to a point in V(i) over Puiseux
               series field up to the first ord terms; more precisely:
@*             IF THE OPTION 'noAbs' WAS NOT SET, THEN:
@*             l[1] = ring Q[a]/m[[t]]
@*             l[2] = int
@*             l[3] = intvec
@*             l[4] = list
@*             IF THE OPTION 'noAbs' WAS SET, THEN:
@*             l[1] = ring Q[X(1),...,X(k)]/m[[t]]
@*             l[2] = int
@*             l[3] = intvec
@*             l[4] = list
@*             l[5] = string
@*       IF THE OPITON 'findAll' WAS SET, THEN:
@*       list, containing ALL liftings of the given point ((w_1/w_0,...,w_n/w_0)
               in the tropical variety of i to a point in V(i) over Puiseux
               series field up to the first ord terms, if the ideal is
               zero-dimensional over Q{{t}};
               more precisely, each entry of the list is a list l as computed
               if  'findAll' was NOT set
@*       WE NOW DESCRIBE THE LIST ENTRIES IF 'findAll' WAS NOT SET:
@*       - the ring l[1] contains an ideal LIFT, which contains
           a point in V(i) lying over w up to the first ord terms;
@*       - and if the integer l[2] is N then t has to be replaced by t^1/N
           in the lift, or alternatively replace t by t^N in the defining ideal
@*       - if the k+1st entry of l[3] is  non-zero, then the kth component of
           LIFT has to be multiplied t^(-l[3][k]/l[3][1]) AFTER substituting t
           by t^1/N
@*       - unless the option 'noResubst' was set, the kth entry of list l[4]
           is a string which represents the kth generator of
           the ideal i where the coordinates have been replaced by the result
           of the lift;
           the t-order of the kth entry should in principle be larger than the
           t-degree of LIFT
@*       - if the option 'noAbs' was set, then the string in l[5] defines
           a maximal ideal in the field Q[X(1),...,X(k)], where X(1),...,X(k)
           are the parameters of the ring in l[1];
           the basefield of the ring in l[1] should be considered modulo this
           ideal
REMARK:  - it is best to use the procedure displayTropicalLifting to
           display the result
@*       - the option 'findAll' cannot be used if 'noAbs' is set
@*       - if the parameter 'findAll' is set AND the ideal i is zero-dimensional
           in Q{{t}}[x_1,...,x_n] then ALL points in V(i) lying over w are
           computed up to order ord; if the ideal is not-zero dimenisonal, then
           only the points in the ideal after cutting down to dimension zero
           will be computed
@*       - the procedure requires that the program GFAN is installed on your
           computer; if you have GFAN version less than 0.3.0 then you must
           use the optional parameter 'oldGfan'
@*       - the procedure requires the @sc{Singular} procedure absPrimdecGTZ to be
           present in the package primdec.lib, unless the option 'noAbs' is set;
           but even if absPrimdecGTZ is present it might be necessary to set
           the option 'noAbs' in order to avoid the costly absolute primary
           decomposition; the side effect is that the field extension which is
           computed throughout the recursion might need more than one
           parameter to be described
@*       - since Q is infinite, the procedure finishes with probability one
@*       - you can call the procedure with Z/pZ as base field instead of Q,
           but there are some problems you should be aware of:
@*         + the Puiseux series field over the algebraic closure of Z/pZ is
             NOT algebraicall closed, and thus there may not exist a point in
             V(i) over the Puiseux series field with the desired valuation;
             so there is no chance that the procedure produced a sensible output
             - e.g. if i=tx^p-tx-1
@*         + if the dimension of i over Z/pZ(t) is not zero the process of
             reduction to zero might not work if the characteristic is small
             and you are unlucky
@*         + the option 'noAbs' has to be used since absolute primary
             decomposition in @sc{Singular} only works in characteristic zero
@*       - the basefield should either be Q or Z/pZ for some prime p;
           field extensions will be computed if necessary; if you need
           parameters or field extensions from the beginning they should
           rather be simulated as variables possibly adding their relations to
           the ideal; the weights for the additional variables should be zero
EXAMPLE: example tropicalLifting;   shows an example"
{
  // if the basering has parameters, then exit with an error message
  if (parstr(basering)!="")
  {
    ERROR("The procedure is not implemented for rings with parameters. See: help tropicalLifting; for more information");
  }
  // in order to avoid unpleasent surprises with the names of the variables
  // we change to a ring where the variables have names t and x(1),...,x(n)
  def ALTERRING=basering;
  if (nvars(basering)==2)
  {
    execute("ring BASERING=("+charstr(ALTERRING)+"),(t,x(1)),("+ordstr(ALTERRING)+");");
  }
  else
  {
    execute("ring BASERING=("+charstr(ALTERRING)+"),(t,x(1.."+string(nvars(ALTERRING)-1)+")),("+ordstr(ALTERRING)+");");
  }
  map altphi=ALTERRING,maxideal(1);
  ideal i=altphi(i);
  int j,k,l,jj,kk;  // index variables
  // work through the optionional parameters
  int isprime,iszerodim,isintrop,gfanold,findall,noabs,nogfan,noresubst,puiseux;
  for (j=1;j<=size(#);j++)
  {
    if (#[j]=="isZeroDimensional")
    {
      iszerodim=1;
    }
    if (#[j]=="isPrime")
    {
      isprime=1;
    }
    if (#[j]=="isInTrop")
    {
      isintrop=1;
    }
    if (#[j]=="oldGfan")
    {
      gfanold=1;
    }
    if (#[j]=="findAll")
    {
      findall=1;
    }
    if (#[j]=="noAbs")
    {
      noabs=1;
    }
    if (#[j]=="puiseux")
    {
      int puiseuxgood=0;
      // test, if the option puiseux makes sense, i.e. we are considering a plane curve
      if ((size(i)==1) and (nvars(basering)==2))
      {
        puiseuxgood=1;
      }
      // the case, where the base field has a parameter and a minimal polynomial is
      // treated by an additional variable (which should be the last variable)
      // and an ideal containing the minimal polynomial as first entry
      if ((size(i)==2) and (nvars(basering)==3))
      {
        // check if the first entry is the minimal polynomial
        poly mpcheck=i[1];
        if (substitute(mpcheck,var(1),0,var(2),0)==mpcheck)
        {
          puiseuxgood=1;
        }
        kill mpcheck;
      }
      if (puiseuxgood==0)
      {
        ERROR("The option puiseux is not allowed for this ring. See: help tropicalLifting; for more information");
      }
      puiseux=1;
      nogfan=1;  // if puiseux is set, then gfan should not be used
    }
    // this option is not documented -- it prevents the execution of gfan and
    // just asks for wneu to be inserted -- it can be used to check problems
    // with the precedure without calling gfan, if wneu is know from previous
    // computations
    if (#[j]=="noGfan")
    {
      nogfan=1;
    }
    if (#[j]=="noResubst")
    {
      noresubst=1;
    }
  }
  // if the basering has characteristic not equal to zero,
  // then absolute factorisation
  // is not available, and thus we need the option noAbs
/*
  if ((char(basering)!=0) and (noabs!=1))
  {
    ERROR("If the characteristic is not zero the procedure should be called with option 'noAbs'");
  }
*/
  int N=1; // we are working with the variable t^1/N - the N may be changed
  // w_0 must be non-zero!
  if (w[1]==0)
  {
    Error("The first coordinate of your input w must be NON-ZERO, since it is a DENOMINATOR!");
  }
  // if w_0<0, then replace w by -w, so that the "denominator" w_0 is positive
  if (w[1]<0)
  {
    w=-w;
  }
  intvec prew=w; // stores w for later reference
  // for our computations, w[1] represents the weight of t and this
  // should be -w_0 !!!
  w[1]=-w[1];
  // if w_0!=-1 then replace t by t^-w_0 and w_0 by -1
  if (w[1]<-1)
  {
    i=subst(i,t,t^(-w[1]));
    N=-w[1];
    w[1]=-1;
  }
  // if some entry of w is positive, we have to make a transformation,
  // which moves it to something non-positive
  for (j=2;j<=nvars(basering);j++)
  {
    if (w[j]>0)
    {
      // transform x_j to t^(-w[j])*x_j in the ideal i
      i=phiOmega(i,j,w[j]);
      w[j]=0;
    }
  }
  prew[1]=prew[1]+w[1];
  prew=prew-w; // this now contains the positive part of the original w,
  // but the original first comp. of w
  // pass to a ring which represents Q[t]_<t>[x1,...,xn]
  // for this, unfortunately, t has to be the last variable !!!
  ideal variablen;
  for (j=2;j<=nvars(basering);j++)
  {
    variablen=variablen+var(j);
  }
  execute("ring GRUNDRING=("+charstr(basering)+"),("+string(variablen)+",t),(dp("+string(nvars(basering)-1)+"),lp(1));");
  ideal variablen;
  for (j=1;j<=nvars(basering)-1;j++)
  {
    variablen=variablen+var(j);
  }
  map GRUNDPHI=BASERING,t,variablen;
  ideal i=GRUNDPHI(i);
  // compute the initial ideal of i and test if w is in the tropical
  // variety of i
  // - the last entry 1 only means that t is the last variable in the ring
  ideal ini=tInitialIdeal(i,w,1);
  if (isintrop==0) // test if w is in trop(i) only if isInTrop has not been set
  {
    poly product=1;
    for (j=1;j<=nvars(basering)-1;j++)
    {
      product=product*var(j);
    }
    if (radicalMemberShip(product,ini)==1) // if w is not in Trop(i) - error
    {
      ERROR("The integer vector is not in the tropical variety of the ideal.");
    }
  }
  // compute next the dimension of i in K(t)[x] and cut the ideal down to dim 0
  if (iszerodim==0) // do so only if is_dim_zero is not set
  {
    execute("ring QUOTRING=("+charstr(basering)+",t),("+string(variablen)+"),dp;");
    ideal i=groebner(imap(GRUNDRING,i));
    int dd=dim(i);
    setring GRUNDRING;
    // if the dimension is not zero, we cut the ideal down to dimension zero
    // and compute the
    // t-initial ideal of the new ideal at the same time
    if(dd!=0)
    {
      // the procedurce cutdown computes a new ring, in which there lives a
      // zero-dimensional
      // ideal which has been computed by cutting down the input with
      // generic linear forms
      // of the type x_i1-p_1,...,x_id-p_d for some polynomials
      // p_1,...,p_d not depending
      // on the variables x_i1,...,x_id; that way we have reduced
      // the number of variables by dd !!!
      // the new zero-dimensional ideal is called i, its t-initial
      // ideal (with respect to
      // the new w=CUTDOWN[2]) is ini, and finally there is a list
      // repl in the ring
      // which contains at the polynomial p_j at position i_j and
      //a zero otherwise;
      if (isprime==0) // the minimal associated primes of i are computed
      {
        list CUTDOWN=cutdown(i,w,dd);
      }
      else // i is assumed to be prime
      {
        list CUTDOWN=cutdown(i,w,dd,"isPrime");
      }
      def CUTDOWNRING=CUTDOWN[1];
      intvec precutdownw=w;  // save the old w for later reference
      w=CUTDOWN[2];          // the new w - some components have been eliminated
      setring CUTDOWNRING;
    }
  }
  else
  {
    int dd=0; // the dimension of i
  }
  list liftrings; // will contain the final result
  // if the procedure is called without 'findAll' then it may happen, that no
  // proper solution is found when dd>0; in that case we have
  // to start all over again;
  // this is controlled by the while-loop
  intvec ordnungskontrollvektor=N,-w[2]; // used with the option puiseux
  while (size(liftrings)==0)
  {
    // compute lifting for the zero-dimensional ideal via tropicalparametrise
    if (noabs==1) // do not use absolute primary decomposition
    {
      list TP=list(tropicalparametriseNoabs(i,w,ordnung,gfanold,nogfan,puiseux,ini));
    }
    else // use absolute primary decomposition
    {
      list TP=tropicalparametrise(i,w,ordnung,ordnungskontrollvektor,gfanold,findall,nogfan,puiseux,ini);
    }
    // compute the liftrings by resubstitution
    kk=1;  // counts the liftrings
    int isgood;  // test in the non-zerodimensional case
                 // if the result has the correct valuation
    for (jj=1;jj<=size(TP);jj++)
    {
      // the list TP contains as a first entry the ring over which the
      // tropical parametrisation
      // of the (possibly cutdown ideal) i lives
      def LIFTRING=TP[jj][1];
      // if the dimension of i originally was not zero,
      // then we have to fill in the missing
      // parts of the parametrisation
      if (dd!=0)
      {
        // we need a ring where the parameters X_1,...,X_k
        // from LIFTRING are present,
        // and where also the variables of CUTDOWNRING live
        execute("ring REPLACEMENTRING=("+charstr(LIFTRING)+"),("+varstr(CUTDOWNRING)+"),dp;");
        list repl=imap(CUTDOWNRING,repl); // get the replacement rules
                                          // from CUTDOWNRING
        ideal PARA=imap(LIFTRING,PARA);   // get the zero-dim. parametrisatio
                                          // from LIFTRING
        // compute the lift of the solution of the original ideal i
        ideal LIFT;
        k=1;
        // the lift has as many components as GRUNDRING has variables!=t
        for (j=1;j<=nvars(GRUNDRING)-1;j++)
        {
          // if repl[j]=0, then the corresponding variable was not eliminated
          if (repl[j]==0)
          {
            LIFT[j]=PARA[k]; // thus the lift has been
                             // computed by tropicalparametrise
            k++; // k checks how many entries of PARA have already been used
          }
          else  // if repl[j]!=0, repl[j] contains replacement rule for the lift
          {
            LIFT[j]=repl[j]; // we still have to replace the vars
                             // in repl[j] by the corresp. entries of PARA
            // replace all variables!=t (from CUTDOWNRING)
            for (l=1;l<=nvars(CUTDOWNRING)-1;l++)
            {
              // substitute the kth variable by PARA[k]
              LIFT[j]=subst(LIFT[j],var(l),PARA[l]);
            }
          }
        }
        setring LIFTRING;
        ideal LIFT=imap(REPLACEMENTRING,LIFT);
        // test now if the LIFT has the correct valuation !!!
        // note: it may happen, that when resubstituting PARA into
        //       the replacement rules
        //       there occurred some unexpected cancellation;
        //       we only know that for SOME
        //       solution of the zero-dimensional reduction NO
        //       canellation will occur,
        //       but for others this may very well happen;
        //       this in particular means that
        //       we possibly MUST compute all zero-dimensional
        //       solutions when cutting down!
        intvec testw=precutdownw[1];
        for (j=1;j<=size(LIFT);j++)
        {
          testw[j+1]=-ord(LIFT[j]);
        }
        if (testw==precutdownw)
        {
          isgood=1;
        }
        else
        {
          isgood=0;
        }
      }
      else
      {
        setring LIFTRING;
        ideal LIFT=PARA;
        isgood=1;
      }
      kill PARA;
      // only if LIFT has the right valuation we have to do something
      if (isgood==1)
      {
        // it remains to reverse the original substitutions,
        // where appropriate !!!
        // if some entry of the original w was positive,
        // we replace the corresponding
        // variable x_i by t^-w[i]*x_i, so we must now replace
        // the corresponding entry
        // LIFT[i] by t^-w[i]*LIFT[i] --- the original w is stored in prew
        // PROBLEM: THIS CANNOT BE DONE SINCE -w[i] IS NEGATIVE
        // INSTEAD: RETURN prew IN THE LIST
        /*
          for (j=2;j<=size(prew);j++)
          {
          if (prew[j]>0)
          {
          LIFT[j-1]=t^(-prew[j])*LIFT[j-1];
          }
          }
        */
        // if LIFTRING contains a parameter @a, change it to a
        if ((noabs==0) and (defined(@a)==-1))
        {
          // pass first to a ring where a and @a
          // are variables in order to use maps
          poly mp=minpoly;
          ring INTERRING=char(LIFTRING),(t,@a,a),dp;
          poly mp=imap(LIFTRING,mp);
          ideal LIFT=imap(LIFTRING,LIFT);
          kill LIFTRING;
          // replace @a by a in minpoly and in LIFT
          map phi=INTERRING,t,a,a;
          mp=phi(mp);
          LIFT=phi(LIFT);
          // pass now to a ring whithout @a and with a as parameter
          ring LIFTRING=(char(INTERRING),a),t,ls;
          minpoly=number(imap(INTERRING,mp));
          ideal LIFT=imap(INTERRING,LIFT);
          kill INTERRING;
        }
        // then export LIFT
        export(LIFT);
        // test the  result by resubstitution
        setring GRUNDRING;
        list resubst;
        if (noresubst==0)
        {
          if (noabs==1)
          {
            resubst=tropicalliftingresubstitute(substitute(i,t,t^(TP[jj][2])),list(LIFTRING),N*TP[jj][2],TP[jj][3]);
          }
          else
          {
            resubst=tropicalliftingresubstitute(substitute(i,t,t^(TP[jj][2])),list(LIFTRING),N*TP[jj][2]);
          }
        }
        setring BASERING;
        // Finally, if t has been replaced by t^N, then we have to change the
        // third entry of TP by multiplying by N.
        if (noabs==1)
        {
          liftrings[kk]=list(LIFTRING,N*TP[jj][2],prew,resubst,TP[jj][3]);
        }
        else
        {
          liftrings[kk]=list(LIFTRING,N*TP[jj][2],prew,resubst);
        }
        kk++;
        kill resubst;
      }
      setring BASERING;
      kill LIFTRING;
    }
    // if dd!=0 and the procedure was called without the
    // option findAll, then it might very well
    // be the case that no solution is found, since
    // only one solution for the zero-dimensional
    // reduction was computed and this one might have
    // had cancellations when resubstituting;
    // if so we have to restart the process with the option findAll
    if (size(liftrings)==0)
    {
      "The procedure was called without findAll and no proper solution was found.";
      "The procedure will be restarted with the option 'findAll'.";
      "Go on by hitting RETURN!";
      findall=1;
      noabs=0;
      setring CUTDOWNRING;
      int hadproblems;
      "i";i;
      "ini";tInitialIdeal(i,w,1);

/*
      setring GRUNDRING;
      list repl=imap(CUTDOWNRING,repl);
      i=imap(CUTDOWNRING,i);
      for (j=1;j<=nvars(basering)-1;j++)
      {
        if (repl[j]!=0)
        {
          i=i+ideal(var(j)-repl[j]);
        }
      }
      ini=tInitialIdeal(i,precutdownw,1);
      w=precutdownw;
*/

    }
  }
  // if internally the option findall was set, then return
  // only the first solution
  if (defined(hadproblems)!=0)
  {
    liftrings=liftrings[1];
  }
  ///////////////////////////////////////////////////////////
  if (printlevel-voice+2>=0)
  {

      "The procedure has created a list of lists. The jth entry of this list
contains a ring, an integer and an intvec.
In this ring lives an ideal representing the wanted lifting,
if the integer is N then in the parametrisation t has to be replaced by t^1/N,
and if the ith component of the intvec is w[i] then the ith component in LIFT
should be multiplied by t^-w[i]/N in order to get the parametrisation.

Suppose your list has the name L, then you can access the 1st ring via:
";
    if (findall==1)
    {
      "def LIFTRing=L[1][1]; setring LIFTRing; LIFT;
";
    }
    else
    {
      "def LIFTRing=L[1]; setring LIFTRing; LIFT;
";
    }
  }
  if (findall==1) // if all solutions have been computed, return a list of lists
  {
    return(liftrings);
  }
  else //if only 1 solution was to be computed, return the 1st list in liftrings
  {
    liftrings=liftrings[1];
    return(liftrings);
  }
}
example
{
   "EXAMPLE:";
   int oldprintlevel=printlevel;
   printlevel=1;
   echo=2;
   ////////////////////////////////////////////////////////
   // 1st EXAMPLE:
   ////////////////////////////////////////////////////////
   ring r=0,(t,x),dp;
   ideal i=(1+t2)*x2+t5x+t2;
   intvec w=1,-1;
   list LIST=tropicalLifting(i,w,4);
   def LIFTRing=LIST[1];
   setring LIFTRing;
   // LIFT contains the first 4 terms of a point in the variety of i
   // over the Puiseux series field C{{t}} whose order is -w[1]/w[0]=1
   LIFT;
   // Since the computations were done over Q a field extension was necessary,
   // and the parameter "a" satisfies the equation given by minpoly
   minpoly;
   ////////////////////////////////////////////////////////
   // 2nd EXAMPLE
   ////////////////////////////////////////////////////////
   setring r;
   LIST=tropicalLifting(x12-t11,intvec(12,-11),2,"isPrime","isInTrop");
   def LIFTRing2=LIST[1];
   setring LIFTRing2;
   // This time, LIFT contains the lifting of the point -w[1]/w[0]=11/12
   // only after we replace in LIFT the variable t by t^1/N with N=LIST[3]
   LIFT;
   LIST[3];
   ///////////////////////////////////////////////////////
   // 3rd EXAMPLE
   ////////////////////////////////////////////////////////
   ring R=0,(t,x,y,z),dp;
   ideal i=-y2t4+x2,yt3+xz+y;
   w=1,-2,0,2;
   LIST=tropicalLifting(i,w,3);
   // This time, LIFT contains the lifting of the point v=(-2,0,2)
   // only after we multiply LIFT[3] by t^k with k=-LIST[4][3];
   // NOTE: since the last component of v is positive, the lifting
   //       must start with a negative power of t, which in Singular
   //       is not allowed for a variable.
   def LIFTRing3=LIST[1];
   setring LIFTRing3;
   LIFT;
   LIST[4];
   // An easier way to display this is via displayTropicalLifting.
   setring R;
   displayTropicalLifting(LIST,"subst");
   printlevel=oldprintlevel;
}

///////////////////////////////////////////////////////////////////////////////

proc displayTropicalLifting (list troplift,list #)
"USAGE:    displaytropcallifting(troplift[,#]); troplift list, # list
ASSUME:    troplift is the output of tropicalLifting; the optional parameter
           # can be the string 'subst'
RETURN:    none
NOTE:      - the procedure displays the output of the procedure tropicalLifting
@*         - if the optional parameter 'subst' is given, then the lifting is
             substituted into the ideal and the result is displayed
EXAMPLE:   example displayTropicalLifting;   shows an example"
{
  int j;
  // if the procedure has to display more than one lifting
  if (typeof(troplift[1])=="list")
  {
    for (j=1;j<=size(troplift);j++)
    {
      "=============================";
      string(j)+". Lifting:";
      "";
      displayTropicalLifting(troplift[j],#);
      "";
    }
  }
  // if the procedure has to display only one lifting
  else
  {
    list variablen;
    for (j=2;j<=nvars(basering);j++)
    {
      variablen[j-1]=string(var(j));
    }
    def LIFTRing=troplift[1];
    int N=troplift[2];
    intvec wdiff=troplift[3];
    string LIFTpar=parstr(LIFTRing);
    if (char(LIFTRing)==0)
    {
      string Kstring="Q";
    }
    else
    {
      string Kstring="Z/"+string(char(LIFTRing))+"Z";
    }
    // this means that tropicalLifting was called with
    // absolute primary decomposition
    if (size(troplift)==4)
    {
      setring LIFTRing;
      "The lifting of the point in the tropical variety lives in the ring";
      if ((size(LIFTpar)==0) and (N==1))
      {
        Kstring+"[[t]]";
      }
      if ((size(LIFTpar)==0) and (N!=1))
      {
        Kstring+"[[t^(1/"+string(N)+")]]";
      }
      if ((size(LIFTpar)!=0) and (N!=1))
      {
        Kstring+"["+LIFTpar+"]/"+string(minpoly)+"[[t^(1/"+string(N)+")]]";
      }
      if ((size(LIFTpar)!=0) and (N==1))
      {
        Kstring+"["+LIFTpar+"]/"+string(minpoly)+"[[t]]";
      }
    }
    else // tropicalLifting was called with the option noAbs
    {
      string m=troplift[5];
      setring LIFTRing;
      "The lifting of the point in the tropical variety lives in the ring";
      if ((size(LIFTpar)==0) and (N==1))
      {
        Kstring+"[[t]]";
      }
      if ((size(LIFTpar)==0) and (N!=1))
      {
        Kstring+"[[t^(1/"+string(N)+")]]";
      }
      if ((size(LIFTpar)!=0) and (N!=1))
      {
        Kstring+"["+LIFTpar+"]/M[[t^(1/"+string(N)+")]]";
        "where M is the maximal ideal";
        "M=<"+m+">";
      }
      if ((size(LIFTpar)!=0) and (N==1))
      {
        Kstring+"["+LIFTpar+"]/M[[t]]";
        "where M is the maximal ideal";
        "M=<"+m+">";
      }
    }
    "";
    "The lifting has the form:";
    for (j=1;j<=size(LIFT);j++)
    {
      if (ncols(LIFT)==size(variablen))
      {
        variablen[j]+"="+displaypoly(LIFT[j],N,wdiff[j+1],wdiff[1]);
      }
      else
      {
        "var("+string(j)+")="+displaypoly(LIFT[j],N,wdiff[j+1],wdiff[1]);
      }
    }
    if (size(#)>0)
    {
      if (#[1]=="subst")
      {
        "";
        "Substituting the solution into the ideal gives:";
        for(j=1;j<=size(troplift[4]);j++)
        {
          "i["+string(j)+"]="+troplift[4][j];
        }
      }
    }
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(t,x,y,z),dp;
   ideal i=-y2t4+x2,yt3+xz+y;
   intvec w=2,-4,0,4;
   displayTropicalLifting(tropicalLifting(i,w,3),"subst");
}

proc puiseuxExpansion (poly f,int n,list #)
"USAGE:  puiseuxExpansion(f,n,#); f poly, n int, # list
ASSUME:  f is a non-constant polynomial in two variables which is not
         divisible by the first variable and which is squarefree
         as a power series over the complex numbers;
         the base field is either the field of rational numbers or a finite extension thereof;
         monomial ordering is assumed to be local;
         the optional parameter # can be the string 'subst'
RETURN:  list, where each entry of the list l describes the Newton-Puiseux
@*             parametrisations of one branch of the plane curve singularity
@*             at the origin defined by f; only the terms up to order n of each
@*             parametetrisation are computed
@*             l[i][1] = is a ring
@*             l[i][2] = int
@*             l[i][3] = string
@*
@*       WE NOW DESCRIBE THE LIST ENTRIES l[i] IN MORE DETAIL:
@*       - the ring l[i][1] contains an ideal LIFT and the Newton-Puiseux
           parametrisation of the branch is given by x=t^N and y=LIFT[1],
           where N=l[i][2]
@*       - if the base field had a parameter and a minimal polynomial, then
           the new base field will have a parameter and a new minimal polynomial,
           and LIFT[2] describes how the old parameter can be computed from the new one
@*       - if a field extension with minimal polynomial of degree k was necessary,
           then to the one extension produced acutally k extensions correspond by replacing
           the parameter a successively by all zeros of the minimal polynomial
@*       - if the option subst was set l[i][3] contains the polynomial where
           y has been substituted by y(t^{1/N}) as a string
REMARK:  - it is best to use the procedure displayPuiseuxExpansion to
           display the result
@*       - the procedure requires the @sc{Singular} procedure absPrimdecGTZ to be
           present in the package primdec.lib
@*       - if f is not squarefree it will be replaced by its squarefree part
EXAMPLE:   example puiseuxExpansion;   shows an example"
{
  if (deg(f)<=0)
  {
    ERROR("The input polynomial is not allowed to be constant!");
  }
  if (char(basering)!=0)
  {
    ERROR("In positive characteristic a Puiseux expansion will not in general exist!");
  }
  if ((npars(basering)>1) or ((npars(basering)==1) and (minpoly==0)))
  {
    ERROR("The procedure is not implemented for this base field!");
  }
  if (nvars(basering)!=2)
  {
    ERROR("The base ring should depend on exactly two variables.");
  }
  if (f==(f / var(1))*var(1))
  {
    ERROR("The input polynomial is not allowed to be divisible by the first variable.");
  }
  // if the ordering is not local, change to a local ordering
  if ((1<var(1)) or (1<var(2)))
  {
    def GLOBALRING=basering;
    def LOCALRING=changeordTo(GLOBALRING,"ds");
    setring LOCALRING;
    poly f=imap(GLOBALRING,f);
  }
  // check if a substitution is necessary
  int noResubst;
  if (size(#)>1)
  {
    if (#[1]=="subst")
    {
      noResubst=0;
    }
  }
  // replace f by its squarefree part
  f=squarefree(f);
  // check if var(1) or var(2) divide f
  int coordinatebranchtwo;
  if (f==(f / var(2))*var(2))
  {
    coordinatebranchtwo=1;
    f=f/var(2);
  }
  int jj;
  // if f is now constant then we should skip the next part
  if (deg(f)!=0)
  {
    // compute the Newton polygon
    int zw;
    intvec w;
    int ggteiler;
    list NewtP=newtonpoly(f);
    list tls;
    list pexp;
    // if the base field has a minimal polynomial change the base ring and the ideal
    if (minpoly!=0)
    {
      poly mp=minpoly;
      def OLDRING=basering;
      execute("ring NEWRING=0,("+varstr(basering)+","+parstr(basering)+"),ds;");
      ideal I=imap(OLDRING,mp),imap(OLDRING,f);
    }
    else
    {
      ideal I=f;
    }
    // for each facet of the Newton polygon compute the corresponding parametrisations
    // using tropicalLifting with the option "puiseux" which avoids gfan
    for (jj=1;jj<=size(NewtP)-1;jj++)
    {
      w=NewtP[jj]-NewtP[jj+1];
      ggteiler=gcd(w[1],w[2]);
      zw=w[1] div ggteiler;
      w[1]=w[2] div ggteiler;
      w[2]=zw;
      // if we have introduced a third variable for the parameter, then w needs a third component
      if (nvars(basering)==3)
      {
        w[3]=0;
      }
      if (noResubst==0)
      {
        tls=tropicalLifting(I,w,n,"findAll","puiseux");
      }
      else
      {
        tls=tropicalLifting(I,w,n,"findAll","puiseux","noResubst");
      }
      pexp=pexp+tls;
    }
    // kill rings that are no longer needed
    if (defined(NEWRING))
    {
      setring OLDRING;
      kill NEWRING;
    }
    if (defined(GLOBALRING))
    {
      setring GLOBALRING;
      kill LOCALRING;
    }
    // remove the third entry in the list of parametrisations since we know
    // that none of the exponents in the parametrisation will be negative
    for (jj=1;jj<=size(pexp);jj++)
    {
      pexp[jj]=delete(pexp[jj],3);
      pexp[jj][3]=pexp[jj][3][size(pexp[jj][3])]; // replace the list in pexp[jj][3] by its first entry
    }
  }
  else // if f was reduced to a constant we still have to introduce the list pexp
  {
    list pexp;
  }
  // we have to add the parametrisations for the branches var(1) resp. var(2) if
  // we removed them
  def BASERING=basering;
  if (coordinatebranchtwo==1)
  {
    ring brring=0,t,ds;
    ideal LIFT=0;
    export(LIFT);
    setring BASERING;
    list pexpentry;
    pexpentry[1]=brring;
    pexpentry[2]=1;
    pexpentry[3]="0";
    pexp[size(pexp)+1]=pexpentry;
    kill brring;
  }
  // check if all branches have been found
  int numberofbranchesfound;
  for (jj=1;jj<=size(pexp);jj++)
  {
    def countring=pexp[jj][1];
    setring countring;
    if (minpoly==0)
    {
      numberofbranchesfound=numberofbranchesfound+1;
    }
    else
    {
      poly mp=minpoly;
      ring degreering=0,a,dp;
      poly mp=imap(countring,mp);
      numberofbranchesfound=numberofbranchesfound+deg(mp);
      setring countring;
      kill degreering;
    }
    setring BASERING;
    kill countring;
  }
  // give a warning if not all branches have been found
  if (numberofbranchesfound!=ord(subst(f,x,0))+coordinatebranchtwo)
  {
    "!!!! WARNING: The number of terms computed in the Puiseux expansion were";
    "!!!!          not enough to find all branches of the curve singularity!";
  }
  return(pexp);
}
example
{
   "EXAMPLE:";
   echo=2;
   printlevel=1;
   ring r=0,(x,y),ds;
   poly f=x2-y4+x5y7;
   puiseuxExpansion(f,3,"subst");
   displayPuiseuxExpansion(puiseuxExpansion(f,3));
}

proc displayPuiseuxExpansion (list puiseux,list #)
"USAGE:    displayPuiseuxExpansion(puiseux[,#]); puiseux list, # list
ASSUME:    puiseux is the output of puiseuxExpansion; the optional parameter
           # can be the string 'subst'
RETURN:    none
NOTE:      - the procedure displays the output of the procedure puiseuxExpansion
@*         - if the optional parameter 'subst' is given, then the expansion is
             substituted into the polynomial and the result is displayed
@*         - if the base field had a parameter and a minimal polynomial, then the
             new base field will have a parameter and a minimal polynomial;
             var(2) is the old parameter and it is displayed how the old parameter
             can be computed from the new one
EXAMPLE:   example displayPuiseuxExpansion;   shows an example"
{
  int j;
  // if the procedure has to display more than one expansion
  if (typeof(puiseux[1])=="list")
  {
    for (j=1;j<=size(puiseux);j++)
    {
      "=============================";
      string(j)+". Expansion:";
      "";
      displayPuiseuxExpansion(puiseux[j],#);
      "";
    }
  }
  // if the procedure has to display only one expansion
  else
  {
    list variablen;
    for (j=2;j<=nvars(basering);j++)
    {
      variablen[j-1]=string(var(j));
    }
    def BASERING=basering;
    def LIFTRing=puiseux[1];
    int N=puiseux[2];
    string LIFTpar=parstr(LIFTRing);
    string Kstring="Q";
    setring LIFTRing;
    "The Puiseux expansion lives in the ring";
    if ((size(LIFTpar)==0) and (N==1))
    {
      Kstring+"[[t]]";
    }
    if ((size(LIFTpar)==0) and (N!=1))
    {
      Kstring+"[[t^(1/"+string(N)+")]]";
    }
    if ((size(LIFTpar)!=0) and (N!=1))
    {
      Kstring+"["+LIFTpar+"]/"+string(minpoly)+"[[t^(1/"+string(N)+")]]";
    }
    if ((size(LIFTpar)!=0) and (N==1))
    {
      Kstring+"["+LIFTpar+"]/"+string(minpoly)+"[[t]]";
    }
    "";
    "The expansion has the form:";
    // treat the case LIFT==0 separately
    if (size(LIFT)==0)
    {
      variablen[1]+"=0";
    }
    else
    {
      for (j=1;j<=size(LIFT);j++)
      {
        if (ncols(LIFT)==size(variablen))
        {
          variablen[j]+"="+displaypoly(LIFT[j],N,0,1);
        }
        else
        {
          "var("+string(j)+")="+displaypoly(LIFT[j],N,0,1);
        }
      }
    }
    if (size(#)>0)
    {
      if (#[1]=="subst")
      {
        setring BASERING;
        "";
        "Substituting the expansion into the polynomial gives:";
        "f="+puiseux[3];
      }
    }
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(x,y),ds;
   poly f=x2-y4+x5y7;
   displayPuiseuxExpansion(puiseuxExpansion(f,3));
}

///////////////////////////////////////////////////////////////////////////////
/// Procedures concerned with drawing a tropical curve or a Newton subdivision
///////////////////////////////////////////////////////////////////////////////

proc tropicalCurve (def tp,list #)
"USAGE:      tropicalCurve(tp[,#]); tp list, # optional list
ASSUME:      tp is list of linear polynomials of the form ax+by+c
             with integers a, b and a rational number c representing
             a tropical Laurent polynomial defining a tropical plane curve;
             alternatively tp can be a polynomial in Q(t)[x,y] defining a
             tropical plane curve via the valuation map;
             the basering must have a global monomial ordering,
             two variables and up to one parameter!
RETURN:      list, each entry i=1,...,size(l)-1 corresponds to a vertex
                   in the tropical plane curve defined by tp
                   l[i][1] = x-coordinate of the ith vertex
                   l[i][2] = y-coordinate of the ith vertex
                   l[i][3] = intmat, if j is an entry in the first row
                             of intmat then the ith vertex of
                             the tropical curve is connected to the
                             jth vertex with multiplicity given
                             by the corresponding entry in the second row
                   l[i][4] = list of lists, the first entry of a list is
                             a primitive integer vector defining the direction
                             of an unbounded edge emerging from the ith vertex
                             of the graph, the corresponding second entry in
                             the list is the multiplicity of the unbounded edge
                   l[i][5] = a polynomial whose monomials mark the vertices
                             in the Newton polygon corresponding to the entries
                             in tp which take the common minimum at the ith
                             vertex -- if some coefficient a or b of the
                             linear polynomials in the input was negative,
                             then each monomial has to be shifted by
                             the values in l[size(l)][3]
                   l[size(l)][1] = list, the entries describe the boundary
                                         points of the Newton subdivision
                   l[size(l)][2] = list, the entries are pairs of integer
                                         vectors defining an interior
                                         edge of the Newton subdivision
                   l[size(l)][3] = intvec, the monmials occuring in l[i][5]
                                           have to be shifted by this vector
                                           in order to represent marked
                                           vertices in the Newton polygon
NOTE:        here the tropical polynomial is supposed to be the MINIMUM
             of the linear forms in tp, unless the optional input #[1]
             is the string 'max'
EXAMPLE:     example tropicalCurve;   shows an example"
{
  // introduce necessary variables
  int i,j,k,l,d;
  intvec v,w,u;
  intmat D[2][2];
  // the basering must have a global monomial ordering
  if (1>var(1))
  {
    ERROR("The basering should have a global monomial ordering, e.g. ring r=(0,t),(x,y),dp;");
  }
  // if you insert a single polynomial instead of an ideal
  // representing a tropicalised polynomial,
  // then we compute first the tropicalisation of this polynomial
  // -- this feature is not documented in the above help string
  if (typeof(tp)=="poly")
  {
    // exclude the case that the basering has not precisely
    // one parameter and two indeterminates
    if ((npars(basering)!=1) or (nvars(basering)!=2))
    {
      ERROR("The basering should have precisely one parameter and two indeterminates!");
    }
    poly f=tp;
    kill tp;
    list tp=tropicalise(f,#);  // the tropicalisation of f
  }
  // Exclude the case that the basering has more than 2 indeterminates
  if (nvars(basering) != 2)
  {
    ERROR("The basering should have precisely two indeterminates!");
  }
  // -1) Exclude the pathological case that the defining
  //     tropical polynomial has only one term,
  //     so that the tropical variety is not defined.
  if (size(tp)==1)
  {
    ERROR("A monomial does not define a tropical curve!");
    intmat M[2][1]=0,0;
    return(list(list(0,0,M,list(),detropicalise(tp[1])),list(list(leadexp(detropicalise(tp[1]))),list())));
  }
  // 0) If the input was a list of linear polynomials,
  //    then some coefficient of x or y can be negative,
  //    i.e. the input corresponds to the tropical curve
  //    of a Laurent polynomial. In that case we should
  //    add some ax+by, so that all coefficients are positive.
  //    This does not change the tropical curve.
  //    however, we have to save (a,b), since the Newton
  //    polygone has to be shifted by (-a,-b).
  poly aa,bb; // koeffizienten
  for (i=1;i<=size(tp);i++)
  {
    if (koeffizienten(tp[i],1)<aa)
    {
      aa=koeffizienten(tp[i],1);
    }
    if (koeffizienten(tp[i],2)<bb)
    {
      bb=koeffizienten(tp[i],2);
    }
  }
  if ((aa!=0) or (bb!=0))
  {
    for (i=1;i<=size(tp);i++)
    {
      tp[i]=tp[i]-aa*var(1)-bb*var(2);
    }
  }
  // 1) compute the vertices of the tropical curve
  //    defined by tp and the Newton subdivision
  list vtp=verticesTropicalCurve(tp,#);
  //    if vtp is empty, then the Newton polygone is just
  //    a line segment and constitutes a bunch of lines
  //    which can be computed by bunchOfLines
  if (size(vtp)==0)
  {
    return(bunchOfLines(tp));
  }
  // 2) store all vertices belonging to the ith part of the
  //    Newton subdivision in the list vtp[i] as 4th entry,
  //    and store those, which are not corners of the ith subdivision polygon
  //    in vtp[i][6]
  poly nwt;
  list boundaryNSD;  // stores the boundary of a Newton subdivision
  intmat zwsp[2][1]; // used for intermediate storage
  for (i=1;i<=size(vtp);i++)
  {
    k=1;
    nwt=vtp[i][3]; // the polynomial representing the
    // ith part of the Newton subdivision
    // store the vertices of the ith part of the
    // Newton subdivision in the list newton
    list newton;
    while (nwt!=0)
    {
      newton[k]=leadexp(nwt);
      nwt=nwt-lead(nwt);
      k++;
    }
    boundaryNSD=findOrientedBoundary(newton);// a list of the vertices
                                             // of the Newton subdivision
                                             // as integer vectors (only those
                                             // on the boundary, and oriented
                                             // clockwise)
    vtp[i][4]=boundaryNSD[1];
    vtp[i][5]=boundaryNSD[2];
    vtp[i][6]=zwsp; // the entries of the first row will denote to which
                    // vertex the ith one is connected
                    // and the entries of the second row will denote
                    //with which multiplicity
    kill newton; // we kill the superflous list
  }
  // 3) Next we build for each part of the Newton
  //    subdivision the list of all pairs of vertices on the
  //    boundary, which are involved, including those which are not corners
  list pairs,pair;
  for (i=1;i<=size(vtp);i++)
  {
    list ipairs;
    for (j=1;j<=size(vtp[i][4])-1;j++)
    {
      pair=vtp[i][4][j],vtp[i][4][j+1];
      ipairs[j]=pair;
    }
    pair=vtp[i][4][size(vtp[i][4])],vtp[i][4][1];
    ipairs[size(vtp[i][4])]=pair;
    pairs[i]=ipairs;
    kill ipairs;
  }
  // 4) Check for all pairs of verticies in the Newton diagram if they
  //    occur in two different parts of the Newton subdivision
  int deleted; // if a pair occurs in two NSD, it can be removed
               // from both - deleted is then set to 1
  list inneredges; // contains the list of all pairs contained in two NSD
                   // - these are inner the edges of NSD
  int ggt;
  d=1;  // counts the inner edges
  for (i=1;i<=size(pairs)-1;i++)
  {
    for (j=i+1;j<=size(pairs);j++)
    {
      for (k=size(pairs[i]);k>=1;k--)
      {
        deleted=0;
        for (l=size(pairs[j]);l>=1 and deleted==0;l--)
        {
          if (((pairs[i][k][1]==pairs[j][l][1]) and (pairs[i][k][2]==pairs[j][l][2])) or ((pairs[i][k][1]==pairs[j][l][2]) and (pairs[i][k][2]==pairs[j][l][1])))
          {
            inneredges[d]=pairs[i][k];  // new inner edge is saved in inneredges
            d++;
            ggt=abs(gcd(pairs[i][k][1][1]-pairs[i][k][2][1],pairs[i][k][1][2]-pairs[i][k][2][2]));
            zwsp=j,ggt;   // and it is recorded that the ith and jth
                          // vertex should be connected with mult ggt
            vtp[i][6]=intmatconcat(vtp[i][6],zwsp);
            zwsp=i,ggt;
            vtp[j][6]=intmatconcat(vtp[j][6],zwsp);
            pairs[i]=delete(pairs[i],k);  // finally the pair is deleted
                                          // from both sets of pairs
            pairs[j]=delete(pairs[j],l);
            deleted=1;
          }
        }
      }
    }
  }
  // 5) The entries in vtp[i][6] are ordered, multiple entries are removed,
  //    and the redundant zero is removed as well
  for (i=1;i<=size(vtp);i++)
  {
    vtp[i][6]=clearintmat(vtp[i][6]);
  }
  // 6) Declare the orientation of the boundary of the Newton polytope.
  // 6.1) Collect all potential vertices of the boundary of the Newton polytope.
  list vertices; // all vertices in the set of pairs
  k=1;
  for (i=1;i<=size(pairs);i++)
  {
    for (j=1;j<=size(pairs[i]);j++)
    {
      vertices[k]=pairs[i][j][1];
      k++;
      vertices[k]=pairs[i][j][2];
      k++;
    }
  }
  // 6.2) delete multiple vertices
  for (i=size(vertices)-1;i>=1;i--)
  {
    for (j=size(vertices);j>=i+1;j--)
    {
      if (vertices[i]==vertices[j])
      {
        vertices=delete(vertices,j);
      }
    }
  }
  // 6.3) Order the vertices such that passing from one to the next we
  //      travel along the boundary of the Newton polytope clock wise.
  boundaryNSD=findOrientedBoundary(vertices);
  list orderedvertices=boundaryNSD[1];
  // 7) Find the unbounded edges emerging from a vertex in the tropical curve.
  //    For this we check the remaining pairs for the ith NSD.
  //    Each pair is ordered according
  //    to the order in which the vertices occur in orderedvertices.
  //    The direction of the
  //    unbounded edge is then the outward pointing primitive normal
  //    vector to the vector
  //    pointing from the first vertex in a pair to the second one.
  intvec normalvector;  // stores the outward pointing normal vector
  intvec zwspp; // used for intermediate storage
  int zw,pos1,pos2; // stores the gcd of entries of the
                    // non-normalised normal vector, etc.
  int gestorben; // tests if unbounded edges are multiple
  for (i=1;i<=size(pairs);i++)
  {
    list ubedges; // stores the unbounded edges
    k=1; // counts the unbounded edges
    for (j=1;j<=size(pairs[i]);j++)
    {
      // computes the position of the vertices in the
      pos1=positionInList(orderedvertices,pairs[i][j][1]);
      // pair in the list orderedvertices
      pos2=positionInList(orderedvertices,pairs[i][j][2]);
      if (((pos1>pos2) and !((pos1==size(orderedvertices)) and (pos2==1))) or ((pos2==size(orderedvertices)) and (pos1==1)))  // reorders them if necessary
      {
        zwspp=pairs[i][j][1];
        pairs[i][j][1]=pairs[i][j][2];
        pairs[i][j][2]=zwspp;
      }
      // the vector pointing from vertex 1 in the pair to vertex2
      normalvector=pairs[i][j][2]-pairs[i][j][1];
      ggt=gcd(normalvector[1],normalvector[2]);   // the gcd of the entries
      zw=normalvector[2];    // create the outward pointing normal vector
      normalvector[2]=-normalvector[1] div ggt;
      normalvector[1]=zw div ggt;
      if (size(#)==0) // we are computing w.r.t. minimum
      {
        ubedges[k]=list(normalvector,ggt); // store outward pointing normal vec.
      }
      else // we are computing w.r.t. maximum
      {
        ubedges[k]=list(-normalvector,ggt); //store outward pointing normal vec.
      }
      k++;
    }
    // remove multiple unbounded edges
    for (j=size(ubedges);j>=1;j--)
    {
      gestorben=0;
      for(k=1;(k<=j-1) and (gestorben==0);k++)
      {
        if (ubedges[k][1]==ubedges[j][1])
        {
          ubedges[k][2]=ubedges[k][2]+ubedges[j][2]; // add the multiplicities
          ubedges=delete(ubedges,j);
          gestorben=1;
        }
      }
    }
    vtp[i][7]=ubedges; // store the unbounded edges in vtp[i][7]
    kill ubedges;
  }
  // 8) Store the computed information for the ith part
  //    of the NSD in the list graph[i].
  list graph,gr;
  for (i=1;i<=size(vtp);i++)
  {
    // the first coordinate of the ith vertex of the tropical curve
    gr[1]=vtp[i][1];
    // the second coordinate of the ith vertex of the tropical curve
    gr[2]=vtp[i][2];
    // to which vertices is the ith vertex of the tropical curve connected
    gr[3]=vtp[i][6];
    // the directions unbounded edges emerging from the ith
    // vertex of the trop. curve
    gr[4]=vtp[i][7];
    // the vertices of the boundary of the ith part of the NSD
    gr[5]=vtp[i][3];
    graph[i]=gr;
  }
  // 9) Shift the Newton subdivision by (aa,bb) if necessary
  intvec shiftvector=intvec(int(aa),int(bb));
  if ((aa!=0) or (bb!=0))
  {
    for (i=1;i<=size(boundaryNSD[2]);i++)
    {
      boundaryNSD[2][i]=boundaryNSD[2][i]+shiftvector;
    }
    for (i=1;i<=size(inneredges);i++)
    {
      for (j=1;j<=size(inneredges[i]);j++)
      {
        inneredges[i][j]=inneredges[i][j]+shiftvector;
      }
    }
  }
  // 10) Finally store the boundary vertices and
  //     the inner edges as last entry in the list graph.
  //     This represents the NSD.
  graph[size(vtp)+1]=list(boundaryNSD[2],inneredges,shiftvector);
  return(graph);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t*(x7+y7+1)+1/t*(x4+y4+x2+y2+x3y+xy3)+1/t7*x2y2;
   list graph=tropicalCurve(f);
// the tropical curve has size(graph)-1 vertices
   size(graph)-1;
// the coordinates of the first vertex are graph[1][1],graph[1][2];
   graph[1][1],graph[1][2];
// the first vertex is connected to the vertices
//     graph[1][3][1,1..ncols(graph[1][3])]
   intmat M=graph[1][3];
   M[1,1..ncols(graph[1][3])];
// the weights of the edges to these vertices are
//     graph[1][3][2,1..ncols(graph[1][3])]
   M[2,1..ncols(graph[1][3])];
// from the first vertex emerge size(graph[1][4]) unbounded edges
   size(graph[1][4]);
// the primitive integral direction vector of the first unbounded edge
//     of the first vertex
   graph[1][4][1][1];
// the weight of the first unbounded edge of the first vertex
   graph[1][4][1][2];
// the monomials which are part of the Newton subdivision of the first vertex
   graph[1][5];
// connecting the points in graph[size(graph)][1] we get
//     the boundary of the Newton polytope
   graph[size(graph)][1];
// an entry in graph[size(graph)][2] is a pair of points
//     in the Newton polytope bounding an inner edge
   graph[size(graph)][2][1];
}

/////////////////////////////////////////////////////////////////////////

proc drawTropicalCurve (def f,list #)
"USAGE:      drawTropicalCurve(f[,#]); f poly or list, # optional list
ASSUME:      f is list of linear polynomials of the form ax+by+c with
             integers a, b and a rational number c representing a tropical
             Laurent polynomial defining a tropical plane curve;
             alternatively f can be a polynomial in Q(t)[x,y] defining
             a tropical plane curve via the valuation map;
             the basering must have a global monomial ordering, two
             variables and up to one parameter!
RETURN:      NONE
NOTE:        - the procedure creates the files /tmp/tropicalcurveNUMBER.tex and
               /tmp/tropicalcurveNUMBER.ps, where NUMBER is a random four
               digit integer;
               moreover it displays the tropical curve via kghostview;
               if you wish to remove all these files from /tmp,
               call the procedure cleanTmp
@*           - edges with multiplicity greater than one carry this multiplicity
@*           - if # is empty, then the tropical curve is computed w.r.t. minimum,
               if #[1] is the string 'max', then it is computed w.r.t. maximum
@*           - if the last optional argument is 'onlytexfile' then only the
               latex file is produced; this option should be used if kghostview
               is not installed on your system
@*           - note that lattice points in the Newton subdivision which are
               black correspond to markings of the marked subdivision,
               while lattice points in grey are not marked
EXAMPLE:     example drawTropicalCurve  shows an example"
{
  // check if the option "onlytexfile" is set, then only a tex file is produced
  if (size(#)!=0)
  {
    if (#[size(#)]=="onlytexfile")
    {
      int onlytexfile;
      #=delete(#,size(#));
    }
  }
  // start the actual computations
  string texf;
  int j;
  if (typeof(f)=="poly")
  {
    // exclude the case that the basering has not precisely
    // one parameter and two indeterminates
    if ((npars(basering)!=1) or (nvars(basering)!=2))
    {
      ERROR("The basering should have precisely one parameter and two indeterminates!");
    }
    // if the characteristic of the base field is not 0 then replace the base field
    // by a field of characteristic zero
    if (char(basering)!=0)
    {
      string polynomstring=string(f);
      execute("ring drawring=(0,"+parstr(basering)+"),("+varstr(basering)+"),dp;");
      execute("poly f="+polynomstring+";");
    }
    texf=texPolynomial(f); // write the polynomial over Q(t)
    list graph=tropicalCurve(tropicalise(f,#),#); // graph of tropicalis. of f
  }
  if (typeof(f)=="list")
  {
    if (typeof(f[1])=="list")
    {
      texf="\\mbox{\\tt The defining equation was not handed over!}";
      list graph=f;
    }
    else
    { // write the tropical polynomial defined by f
      if (size(#)==0)
      {
        texf="\\min\\{";
      }
      else
      {
        texf="\\max\\{";
      }
      for (j=1;j<=size(f);j++)
      {
        texf=texf+texPolynomial(f[j]);
        if (j<size(f))
        {
          texf=texf+", ";
        }
        else
        {
          texf=texf+"\\}";
        }
      }
      list graph=tropicalCurve(f,#); // the graph of the tropical polynomial f
    }
  }
  // produce the tex file
  string vertices;
  for (j=1;j<=size(graph)-2;j++)
  {
    vertices=vertices+"("+string(graph[j][1])+","+string(graph[j][2])+"),\\;\\; ";
  }
  vertices=vertices+"("+string(graph[j][1])+","+string(graph[j][2])+")";
  string TEXBILD="\\documentclass[12pt]{amsart}
\\usepackage{texdraw}
\\setlength{\\topmargin}{30mm}
\\addtolength{\\topmargin}{-1in}
\\addtolength{\\topmargin}{-\\headsep}
\\addtolength{\\topmargin}{-\\headheight}
\\addtolength{\\topmargin}{-\\topskip}
\\setlength{\\textheight}{267mm}
\\addtolength{\\textheight}{\\topskip}
\\addtolength{\\textheight}{-\\footskip}
\\addtolength{\\textheight}{-30pt}
\\setlength{\\oddsidemargin}{-1in}
\\addtolength{\\oddsidemargin}{20mm}
\\setlength{\\evensidemargin}{\\oddsidemargin}
\\setlength{\\textwidth}{170mm}

\\begin{document}
   \\parindent0cm
   \\begin{center}
      \\large\\bf The Tropicalisation of

      \\bigskip

      \\begin{math}
          f="+texf+"
      \\end{math}
   \\end{center}
   \\vspace*{0.5cm}
   The vertices of the tropical curve are:
   \\begin{center}
      \\begin{math}
         "+vertices+"
      \\end{math}
   \\end{center}
   \\vspace*{0.5cm}

   \\begin{center}
"+texDrawBasic(texDrawTropical(graph,#))+  // write the tropical curve
   "\\end{center}

   \\vspace*{0.5cm}
   The Newton subdivision of the tropical curve is:
   \\vspace*{0.5cm}

   \\begin{center}
       "+texDrawNewtonSubdivision(graph,#)+"
   \\end{center}
\\end{document}";
  if(defined(onlytexfile)==0)
  {
    int rdnum=random(1000,9999);
    write(":w /tmp/tropicalcurve"+string(rdnum)+".tex",TEXBILD);
    system("sh","cd /tmp; latex /tmp/tropicalcurve"+string(rdnum)+".tex; dvips /tmp/tropicalcurve"+string(rdnum)+".dvi -o; command rm tropicalcurve"+string(rdnum)+".log;  command rm tropicalcurve"+string(rdnum)+".aux;  command rm tropicalcurve"+string(rdnum)+".ps?;  command rm tropicalcurve"+string(rdnum)+".dvi; kghostview tropicalcurve"+string(rdnum)+".ps &");
  }
  else
  {
    return(TEXBILD);
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy;
// the command drawTropicalCurve(f) computes the graph of the tropical curve
// given by f and displays a post script image, provided you have kghostview
   drawTropicalCurve(f);
// we can instead apply the procedure to a tropical polynomial and use "maximum"
   poly g=1/t3*(x7+y7+1)+t3*(x4+y4+x2+y2+x3y+xy3)+t21*x2y2;
   list tropical_g=tropicalise(g);
   tropical_g;
   drawTropicalCurve(tropical_g,"max");
}

/////////////////////////////////////////////////////////////////////////

proc drawNewtonSubdivision (def f,list #)
"USAGE:   drawTropicalCurve(f[,#]); f poly, # optional list
ASSUME:   f is list of linear polynomials of the form ax+by+c with integers
          a, b and a rational number c representing a tropical Laurent
          polynomial defining a tropical plane curve;
          alternatively f can be a polynomial in Q(t)[x,y] defining a tropical
          plane curve via the valuation map;
          the basering must have a global monomial ordering, two variables
          and up to one parameter!
RETURN:   NONE
NOTE:     - the procedure creates the files /tmp/newtonsubdivisionNUMBER.tex,
            and /tmp/newtonsubdivisionNUMBER.ps, where NUMBER is a random
            four digit integer;
            moreover it desplays the tropical curve defined by f via kghostview;
            if you wish to remove all these files from /tmp, call the procedure
            cleanTmp;
@*          if # is empty, then the tropical curve is computed w.r.t. minimum,
            if #[1] is the string 'max', then it is computed w.r.t. maximum
@*        - note that lattice points in the Newton subdivision which are black
            correspond to markings of the marked subdivision, while lattice
            points in grey are not marked
EXAMPLE:     example drawNewtonSubdivision;   shows an example"
{
  string texf;
  int j;
  if (typeof(f)=="poly")
  {
    texf=texPolynomial(f); // write the polynomial over Q(t)
    list graph=tropicalCurve(tropicalise(f,#),#); // graph of tropicalis. of f
  }
  else
  { // write the tropical polynomial defined by f
    if (size(#)==0)
    {
      texf="\\min\\{";
    }
    else
    {
      texf="\\max\\{";
    }
    for (j=1;j<=size(f);j++)
    {
      texf=texf+texPolynomial(f[j]);
      if (j<size(f))
      {
        texf=texf+", ";
      }
      else
      {
        texf=texf+"\\}";
      }
    }
    list graph=tropicalCurve(f,#); // the graph of the tropical polynomial f
  }
  string TEXBILD="\\documentclass[12pt]{amsart}
\\usepackage{texdraw}
\\begin{document}
   \\parindent0cm
   \\begin{center}
      \\large\\bf The Newtonsubdivison of
      \\begin{displaymath}
          f="+texf+"
      \\end{displaymath}
   \\end{center}
   \\vspace*{1cm}

   \\begin{center}
"+texDrawNewtonSubdivision(graph)+
"   \\end{center}

\\end{document}";
  int rdnum=random(1000,9999);
  write(":w /tmp/newtonsubdivision"+string(rdnum)+".tex",TEXBILD);
  system("sh","cd /tmp; latex /tmp/newtonsubdivision"+string(rdnum)+".tex; dvips /tmp/newtonsubdivision"+string(rdnum)+".dvi -o; command rm newtonsubdivision"+string(rdnum)+".log;  command rm newtonsubdivision"+string(rdnum)+".aux;  command rm newtonsubdivision"+string(rdnum)+".ps?;  command rm newtonsubdivision"+string(rdnum)+".dvi; kghostview newtonsubdivision"+string(rdnum)+".ps &");
//  return(TEXBILD);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy;
// the command drawTropicalCurve(f) computes the graph of the tropical curve
// given by f and displays a post script image, provided you have kghostview
   drawNewtonSubdivision(f);
// we can instead apply the procedure to a tropical polynomial
   poly g=x+y+x2y+xy2+1/t*xy;
   list tropical_g=tropicalise(g);
   tropical_g;
   drawNewtonSubdivision(tropical_g);
}

///////////////////////////////////////////////////////////////////////////////
/// Procedures concerned with cubics
///////////////////////////////////////////////////////////////////////////////

proc tropicalJInvariant (def f,list #)
"USAGE:      tropicalJInvariant(f[,#]); f poly or list, # optional list
ASSUME:      f is list of linear polynomials of the form ax+by+c with integers
             a, b and a rational number c representing a tropical Laurent
             polynomial defining a tropical plane curve;
             alternatively f can be a polynomial in Q(t)[x,y] defining a
             tropical plane curve via the valuation map;
@*           the basering must have a global monomial ordering, two variables
             and up to one parameter!
RETURN:      number, if the graph underlying the tropical curve has precisely
                     one loop then its weighted lattice length is returned,
                     otherwise the result will be -1
NOTE:        - if the tropical curve is elliptic and its embedded graph has
               precisely one loop, then the weigthed lattice length of
               the loop is its tropical j-invariant
@*           - the procedure checks if the embedded graph of the tropical
               curve has genus one, but it does NOT check if the loop can
               be resolved, so that the curve is not a proper tropical
               elliptic curve
@*           - if the embedded graph of a tropical elliptic curve has more
               than one loop, then all but one can be resolved, but this is
               not observed by this procedure, so it will not compute
               the j-invariant
@*           - if # is empty, then the tropical curve is computed w.r.t. minimum,
               if #[1] is the string 'max', then it is computed w.r.t. maximum
@*           - the tropicalJInvariant of a plane tropical cubic is the
               'cycle length' of the cubic as introduced in the paper:
               Eric Katz, Hannah Markwig, Thomas Markwig: The j-invariant
               of a cubic tropical plane curve.
EXAMPLE:     example tropicalJInvariant;   shows an example"
{
  // 1) compute first the graph of the tropical curve
  if (typeof(f)=="poly")
  {
    list graph=tropicalCurve(f,#);
  }
  else
  {
    if (typeof(f)=="list")
    {
      if (typeof(f[1])=="list")
      {
        list graph=f;
      }
      else
      {
        if (typeof(f[1])=="poly")
        {
          list graph=tropicalCurve(f,#);
        }
        else
        {
          ERROR("This is no valid input.");
        }
      }
    }
    else
    {
      ERROR("This is no valid input.");
    }
  }
  int i,j,k;
  // 2) compute the genus of the embedded graph of the tropical curve
  int genus;
  for (i=1;i<=size(graph)-1;i++) // we count the number of bounded edges
  {
    genus=genus+ncols(graph[i][3]);
  }
  genus=-genus/2; // we have counted each bounded edge twice
  genus=genus+size(graph); // the genus is 1-#bounded_edges+#vertices
  // 3) if the embedded graph has not genus one,
  //    we cannot compute the j-invariant
  if(genus!=1)
  {
    if (printlevel>=0)
    {
      "The embedded graph of the curve has not genus one.";
    }
    return(-1);
  }
  else
  {
    intmat nullmat[2][1];  // used to set
    // 4) find a vertex which has only one bounded edge,
    //    if none exists zero is returned,
    //    otherwise the number of the vertex in the list graph
    int nonloopvertex=findNonLoopVertex(graph);
    int dv; //checks if vert. has been found to which nonloopvertex is connected
    intmat delvert; // takes for a moment graph[i][3] of the vertex
                    // to which nonloopvertex is connected
    // 5) delete successively vertices in the graph which
    //    have only one bounded edge
    while (nonloopvertex>0)
    {
      // find the only vertex to which the nonloopvertex
      // is connected, when it is found
      // delete the connection in graph[i][3] and set dv=1
      dv=0;
      for (i=1;i<=size(graph)-1 and dv==0;i++)
      {
        if (i!=nonloopvertex)
        {
          for (j=1;j<=ncols(graph[i][3]) and dv==0;j++)
          {
            if(graph[i][3][1,j]==nonloopvertex) // the vertex is found
            {
              delvert=graph[i][3];
              delvert=intmatcoldelete(delvert,j); // delete the connection (note
                                                  // there must have been two!)
              dv=1;
              graph[i][3]=delvert;
            }
          }
        }
      }
      graph[nonloopvertex][3]=nullmat; // the only connection of nonloopvertex
                                       // is killed
      nonloopvertex=findNonLoopVertex(graph); // find the next vertex
                                              // which has only one edge
    }
    // 6) find the loop and the weights of the edges
    intvec loop,weights; // encodes the loop and the edges
    i=1;
    //    start by finding some vertex which belongs to the loop
    while (loop==0)
    {
      // if graph[i][3] of a vertex in the loop has 2 columns, all others have 1
      if (ncols(graph[i][3])==1)
      {
        i++;
      }
      else
      {
        loop[1]=i; // a starting vertex is found
        loop[2]=graph[i][3][1,1]; // it is connected to vertex with this number
        weights[2]=graph[i][3][2,1]; // and the edge has this weight
      }
    }
    j=graph[i][3][1,1]; // the active vertex of the loop
    k=2; // counts the vertices in the loop
    while (j!=i)  // the loop ends with the same vertex with which it starts
    {
      // the first row of graph[j][3] has two entries
      // corresponding to the two vertices
      // to which the active vertex j is connected;
      // one is loop[k-1], i.e. the one which
      // precedes j in the loop; we have to choose the other one
      if (graph[j][3][1,1]==loop[k-1])
      {
        loop[k+1]=graph[j][3][1,2];
        weights[k+1]=graph[j][3][2,2];
      }
      else
      {
        loop[k+1]=graph[j][3][1,1];
        weights[k+1]=graph[j][3][2,1];
      }
      j=loop[k+1]; // set loop[k+1] the new active vertex
      k++;
    }
    // 7) compute for each edge in the loop the lattice length
    poly xcomp,ycomp; // the x- and y-components of the vectors
                      // connecting two vertices of the loop
    number nenner;    // the product of the denominators of
                      // the x- and y-components
    number jinvariant;  // the j-invariant
    int eins,zwei,ggt;
    for (i=1;i<=size(loop)-1;i++) // compute the lattice length for each edge
    {
      xcomp=graph[loop[i]][1]-graph[loop[i+1]][1];
      ycomp=graph[loop[i]][2]-graph[loop[i+1]][2];
      nenner=denominator(leadcoef(xcomp))*denominator(leadcoef(ycomp));
      execute("eins="+string(numerator(leadcoef(nenner*xcomp)))+";");
      execute("zwei="+string(numerator(leadcoef(nenner*ycomp)))+";");
      ggt=gcd(eins,zwei); // the lattice length is the "gcd"
                          // of the x-component and the y-component
      jinvariant=jinvariant+ggt/(nenner*weights[i+1]); // divided by the
                                                       // weight of the edge
    }
    return(jinvariant);
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
// tropcialJInvariant computes the tropical j-invariant of an elliptic curve
   tropicalJInvariant(t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy);
// the Newton polygone need not be the standard simplex
   tropicalJInvariant(x+y+x2y+xy2+1/t*xy);
// the curve can have arbitrary degree
   tropicalJInvariant(t*(x7+y7+1)+1/t*(x4+y4+x2+y2+x3y+xy3)+1/t7*x2y2);
// the procedure does not realise, if the embedded graph of the tropical
//     curve has a loop that can be resolved
   tropicalJInvariant(1+x+y+xy+tx2y+txy2);
// but it does realise, if the curve has no loop at all ...
   tropicalJInvariant(x+y+1);
// or if the embedded graph has more than one loop - even if only one
//     cannot be resolved
   tropicalJInvariant(1+x+y+xy+tx2y+txy2+t3x5+t3y5+tx2y2+t2xy4+t2yx4);
}

/////////////////////////////////////////////////////////////////////////

proc weierstrassForm (poly f,list #)
"USAGE:      weierstrassForm(wf[,#]); wf poly, # list
ASSUME:      wf is a a polynomial whose Newton polygon has precisely one
             interior lattice point, so that it defines an elliptic curve
             on the toric surface corresponding to the Newton polygon
RETURN:      poly, the Weierstrass normal form of the polynomial
NOTE:        - the algorithm for the coefficients of the Weierstrass form is due
               to Fernando Rodriguez Villegas, villegas@math.utexas.edu
@*           - the characteristic of the base field should not be 2 or 3
@*           - if an additional argument # is given, a simplified Weierstrass
               form is computed
EXAMPLE:     example weierstrassForm;   shows an example"
{
  // Check first if the Newton polygon has precisely one interior point
  // - compute the Newton polygon
  list polygon=newtonPolytopeLP(f);
  // - find the vertices of the Newton cycle and order it clockwise
  list pg=findOrientedBoundary(polygon)[2];
  // - check if there is precisely one interior point in the Newton polygon
  if (picksFormula(pg)[3]!=1)
  {
    ERROR("The Newton polygon of the input has NOT precisely one interior point!");
  }
  // Compute the Normal form of the polygon.
  list nf=ellipticNF(polygon);
  // Transform f by the unimodular affine coordinate transformation
  poly tf=coordinatechange(f,nf[2],nf[3]);
  // Check if the Newton polygon is of type 4x2, 2x2 or a cubic
  poly a,b=flatten(coeffs(tf,ideal(var(1)^4,var(1)^2*var(2)^2)));
  // if it is of type 4x2
  if (a!=0)
  {
    return(weierstrassFormOfA4x2Curve(tf));
  }
  // if it is of type 2x2
  if (b!=0)
  {
    return(weierstrassFormOfA2x2Curve(tf));
  }
  // else it is a cubic
  return(weierstrassFormOfACubic(tf,#));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),lp;
// f is already in Weierstrass form
   poly f=y2+yx+3y-x3-2x2-4x-6;
   weierstrassForm(f);
// g is not, but wg is
   poly g=x+y+x2y+xy2+1/t*xy;
   poly wg=weierstrassForm(g);
   wg;
// but it is not yet simple, since it still has an xy-term, unlike swg
   poly swg=weierstrassForm(g,1);
   swg;
// the j-invariants of all three polynomials coincide
   jInvariant(g);
   jInvariant(wg);
   jInvariant(swg);
// the following curve is elliptic as well
   poly h=x22y11+x19y10+x17y9+x16y9+x12y7+x9y6+x7y5+x2y3;
// its Weierstrass form is
   weierstrassForm(h);
}

/////////////////////////////////////////////////////////////////////////

proc jInvariant (poly f,list #)
"USAGE:      jInvariant(f[,#]); f poly, # list
ASSUME:      - f is a a polynomial whose Newton polygon has precisely one
               interior lattice point, so that it defines an elliptic curve
               on the toric surface corresponding to the Newton polygon
@*           - it the optional argument # is present the base field should be
               Q(t) and the optional argument should be one of the following
               strings:
@*             'ord'   : then the return value is of type integer,
                         namely the order of the j-invariant
@*             'split' : then the return value is a list of two polynomials,
                         such that the quotient of these two is the j-invariant
RETURN:      poly, the j-invariant of the elliptic curve defined by poly
NOTE:        the characteristic of the base field should not be 2 or 3,
             unless the input is a plane cubic
EXAMPLE:     example jInvariant;   shows an example"
{
  // compute first the Weierstrass form of the cubic and then the j-invariant
  if (size(#)==0)
  {
    return(jInvariantOfACubic(weierstrassForm(f),#));
  }
  else
  {
    if (#[1]=="split")
    {
      return(jInvariantOfAPuiseuxCubic(weierstrassForm(f)));
    }
    else
    {
      return(jInvariantOfAPuiseuxCubic(weierstrassForm(f),"ord"));
    }
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
// jInvariant computes the j-invariant of a cubic
   jInvariant(x+y+x2y+y3+1/t*xy);
// if the ground field has one parameter t, then we can instead
//    compute the order of the j-invariant
   jInvariant(x+y+x2y+y3+1/t*xy,"ord");
// one can compare the order of the j-invariant to the tropical j-invariant
   tropicalJInvariant(x+y+x2y+y3+1/t*xy);
// the following curve is elliptic as well
   poly h=x22y11+x19y10+x17y9+x16y9+x12y7+x9y6+x7y5+x2y3+x14y8;
// its j-invariant is
   jInvariant(h);
}



///////////////////////////////////////////////////////////////////////////////
/// Procedures concerned with conics
///////////////////////////////////////////////////////////////////////////////

proc conicWithTangents (list points,list #)
"USAGE:      conicWithTangents(points[,#]); points list, # optional list
ASSUME:      points is a list of five points in the plane over K(t)
RETURN:      list, l[1] = the list points of the five given points
@*                 l[2] = the conic f passing through the five points
@*                 l[3] = list of equations of tangents to f in the given points
@*                 l[4] = ideal, tropicalisation of f (i.e. list of linear forms)
@*                 l[5] = a list of the tropicalisation of the tangents
@*                 l[6] = a list containing the vertices of the tropical conic f
@*                 l[7] = a list containing lists with vertices of the tangents
@*                 l[8] = a string which contains the latex-code to draw the
                          tropical conic and its tropicalised tangents
@*                 l[9] = if # is non-empty, this is the same data for the dual
                          conic and the points dual to the computed tangents
NOTE:        the points must be generic, i.e. no three on a line
EXAMPLE:     example conicWithTangents;   shows an example"
{
  int i;
  // Compute the tropical coordinates of the given points - part 1
  list pointdenom,pointnum;
  poly pp1,pp2;
  for (i=1;i<=size(points);i++)
  {
    pp1=denominator(leadcoef(points[i][1]));
    pp2=denominator(leadcoef(points[i][2]));
    pointdenom[i]=list(pp1,pp2);
    pp1=numerator(leadcoef(points[i][1]));
    pp2=numerator(leadcoef(points[i][2]));
    pointnum[i]=list(pp1,pp2);
  }
  // compute the equation of the conic
  def BASERING=basering;
  ring LINRING=(0,t),(x,y,a(1..6)),lp;
  list points=imap(BASERING,points);
  ideal I; // the ideal will contain the linear equations given by the conic
           // and the points
  for (i=1;i<=5;i++)
  {
    I=I,substitute(a(1)*x2+a(2)*xy+a(3)*y2+a(4)*x+a(5)*y+a(6),x,points[i][1],y,points[i][2]);
  }
  I=std(I);
  list COEFFICIENTS;
  ideal DENOMINATORS;
  for (i=1;i<=6;i++)
  {
    COEFFICIENTS[i]=leadcoef(reduce(a(i),I));
    DENOMINATORS[i]=denominator(leadcoef(COEFFICIENTS[i]));
  }
  // compute the common denominator of the coefficients
  ring TRING=0,t,dp;
  ideal DENOMINATORS=imap(LINRING,DENOMINATORS);
  poly p=lcm(DENOMINATORS);
  // compute the tropical coordinates of the points - part 2
  ring tRING=0,t,ls;
  list pointdenom=imap(BASERING,pointdenom);
  list pointnum=imap(BASERING,pointnum);
  intvec pointcoordinates;
  for (i=1;i<=size(pointdenom);i++)
  {
    pointcoordinates[2*i-1]=ord(pointnum[i][1])-ord(pointdenom[i][1]);
    pointcoordinates[2*i]=ord(pointnum[i][2])-ord(pointdenom[i][2]);
  }
  // multiply the coefficients of the conic by the common denominator
  setring LINRING;
  poly p=imap(TRING,p);
  for (i=1;i<=6;i++)
  {
    COEFFICIENTS[i]=COEFFICIENTS[i]*p;
  }
  // Compute the tangents to the conic in the given points
  // and tropicalise the conic and the tangents
  setring BASERING;
  list CO=imap(LINRING,COEFFICIENTS);
  poly f=CO[1]*x2+CO[2]*xy+CO[3]*y2+CO[4]*x+CO[5]*y+CO[6];
  poly fx=diff(f,x);
  poly fy=diff(f,y);
  list tangents;
  list tropicaltangents;
  for (i=1;i<=5;i++)
  {
    tangents[i]=substitute(fx,x,points[i][1],y,points[i][2])*x+substitute(fy,x,points[i][1],y,points[i][2])*y;
    tangents[i]=tangents[i]-substitute(tangents[i],x,points[i][1],y,points[i][2]);
    tropicaltangents[i]=tropicalise(tangents[i]);
  }
  list tropicalf=tropicalise(f);
  // compute the vertices of the tropcial conic and of the tangents
  list graphf=tropicalCurve(tropicalf);
  list eckpunktef;
  for (i=1;i<=size(graphf)-1;i++)
  {
    eckpunktef[i]=list(graphf[i][1],graphf[i][2]);
  }
  list eckpunktetangents;
  for (i=1;i<=size(tropicaltangents);i++)
  {
    eckpunktetangents[i]=verticesTropicalCurve(tropicaltangents[i],0);
  }
  // find the minimal and maximal coordinates of vertices
  poly minx,miny,maxx,maxy=graphf[1][1],graphf[1][2],graphf[1][1],graphf[1][2];
  for (i=2;i<=size(graphf)-1;i++)
  {
    minx=minOfPolys(list(minx,graphf[i][1]));
    miny=minOfPolys(list(miny,graphf[i][2]));
    maxx=-minOfPolys(list(-maxx,-graphf[i][1]));
    maxy=-minOfPolys(list(-maxy,-graphf[i][2]));
  }
  // find the scale factor for the texdraw image
  poly maxdiffx,maxdiffy;
  maxdiffx=maxx-minx;
  maxdiffy=maxy-miny;
  if (maxdiffx==0)
  {
    maxdiffx=1;
  }
  if (maxdiffy==0)
  {
    maxdiffy=1;
  }
  poly scalefactor=minOfPolys(list(12/leadcoef(maxdiffx),16/leadcoef(maxdiffy)))/4;
  // Produce a Latex-Image of the Conic with each of its Tangents
  string zusatzinfo;
  string TEXBILD="\\documentclass[12pt]{amsart}
\\usepackage{texdraw}
\\begin{document}
   \\parindent0cm
   \\begin{center}
      \\large\\bf A Tropical Conic through 5 Points and Tangents
   \\end{center}

   We consider the concic through the following five points:
   \\begin{displaymath}
";
  string texf=texDrawTropical(graphf,list("",scalefactor));
  for (i=1;i<=size(points);i++)
  {
    TEXBILD=TEXBILD+"p_"+string(i)+"=("+texNumber(points[i][1])+","+texNumber(points[i][2])+"),\\;\\;\\;";
  }
  TEXBILD=TEXBILD+"
   \\end{displaymath}";
  for (i=1;i<=size(points);i++)
  {
    zusatzinfo="
    \\move ("+decimal(pointcoordinates[2*i-1])+" "+decimal(pointcoordinates[2*i])+")
    \\fcir f:0.5 r:0.25
    \\rmove (0.4 0.4)
    \\htext{$p_"+string(i)+"$=("+string(pointcoordinates[2*i-1])+","+string(pointcoordinates[2*i])+")}
    ";
    TEXBILD=TEXBILD+"
   Here we draw the conic and the tangent  through point $p_"+string(i)+"$:

   \\vspace*{1cm}

   \\begin{center}
   "+texDrawBasic(list(texf,zusatzinfo,texDrawTropical(tropicalCurve(tropicaltangents[i]),list("",scalefactor,"       \\setgray 0.8 \\linewd 0.1 \\lpatt (0.1 0.4)"))))+
   "\\end{center}";
    if (i<size(points))
    {
      TEXBILD=TEXBILD+"

   \\newpage

   ";
    }
  }
  TEXBILD=TEXBILD+"

\\end{document}";
  setring BASERING;
  // If # non-empty, compute the dual conic and the tangents
  // through the dual points
  // corresponding to the tangents of the given conic.
  if (size(#)>0)
  {
    list dualpoints;
    for (i=1;i<=size(points);i++)
    {
      dualpoints[i]=list(leadcoef(tangents[i])/substitute(tangents[i],x,0,y,0),leadcoef(tangents[i]-lead(tangents[i]))/substitute(tangents[i],x,0,y,0));
    }
    list dualimage=conicWithTangents(dualpoints);
    return(list(points,f,tangents,tropicalf,tropicaltangents,eckpunktef,eckpunktetangents,TEXBILD,dualimage));
  }
  else
  {
    return(list(points,f,tangents,tropicalf,tropicaltangents,eckpunktef,eckpunktetangents,TEXBILD));
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
// the input consists of a list of five points in the plane over Q(t)
   list points=list(1/t2,t),list(1/t,t2),list(1,1),list(t,1/t2),list(t2,1/t);
   list conic=conicWithTangents(points);
// conic[1] is the list of the given five points
   conic[1];
// conic[2] is the equation of the conic f passing through the five points
   conic[2];
// conic[3] is a list containing the equations of the tangents
//          through the five points
   conic[3];
// conic[4] is an ideal representing the tropicalisation of the conic f
   conic[4];
// conic[5] is a list containing the tropicalisation
//          of the five tangents in conic[3]
   conic[5];
// conic[6] is a list containing the vertices of the tropical conic
   conic[6];
// conic[7] is a list containing the vertices of the five tangents
   conic[7];
// conic[8] contains the latex code to draw the tropical conic and
//          its tropicalised tangents; it can written in a file, processed and
//          displayed via kghostview
   write(":w /tmp/conic.tex",conic[8]);
   system("sh","cd /tmp; latex /tmp/conic.tex; dvips /tmp/conic.dvi -o;
            kghostview conic.ps &");
// with an optional argument the same information for the dual conic is computed
//         and saved in conic[9]
   conic=conicWithTangents(points,1);
   conic[9][2]; // the equation of the dual conic
}

///////////////////////////////////////////////////////////////////////////////
/// Procedures concerned with tropicalisation
///////////////////////////////////////////////////////////////////////////////

proc tropicalise (poly f,list #)
"USAGE:      tropicalise(f[,#]); f polynomial, # optional list
ASSUME:      f is a polynomial in Q(t)[x_1,...,x_n]
RETURN:      list, the linear forms of the tropicalisation of f
NOTE:        if # is empty, then the valuation of t will be 1,
@*           if # is the string 'max' it will be -1;
@*           the latter supposes that we consider the maximum of the
             computed linear forms, the former that we consider their minimum
EXAMPLE:     example tropicalise;   shows an example"
{
  int order,j;
  list tropicalf;
  intvec exp;
  int i=0;
  while (f!=0)
  {
    i++;
    exp=leadexp(f);
    if (size(#)==0)
    {
      tropicalf[i]=simplifyToOrder(f)[1];
    }
    else
    {
      tropicalf[i]=-simplifyToOrder(f)[1];
    }
    for (j=1;j<=nvars(basering);j++)
    {
      tropicalf[i]=tropicalf[i]+exp[j]*var(j);
    }
    f=f-lead(f);
  }
  return(tropicalf);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   tropicalise(2t3x2-1/t*xy+2t3y2+(3t3-t)*x+ty+(t6+1));
}


/////////////////////////////////////////////////////////////////////////

proc tropicaliseSet (ideal i)
"USAGE:    tropicaliseSet(i); i ideal
ASSUME:    i is an ideal in Q(t)[x_1,...,x_n]
RETURN:    list, the jth entry is the tropicalisation of the jth generator of i
EXAMPLE:   example tropicaliseSet;   shows an example"
{
  list tropicalid;
  for (int j=1;j<=size(i);j++)
  {
    tropicalid[j]=tropicalise(i[j]);
  }
  return(tropicalid);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   ideal i=txy-y2+1,2t3x2+1/t*y-t6;
   tropicaliseSet(i);
}

/////////////////////////////////////////////////////////////////////////

proc tInitialForm (poly f, intvec w)
"USAGE:      tInitialForm(f,w); f a polynomial, w an integer vector
ASSUME:      f is a polynomial in Q[t,x_1,...,x_n] and w=(w_0,w_1,...,w_n)
RETURN:      poly, the t-initialform of f(t,x) w.r.t. w evaluated at t=1
NOTE:        the t-initialform is the sum of the terms with MAXIMAL
             weighted order w.r.t. w
EXAMPLE:     example tInitialForm;   shows an example"
{
  // take in lead(f) only the term of lowest t-order and set t=1
  poly initialf=lead(f);
  // compute the order of lead(f) w.r.t. (1,w)
  int gewicht=scalarproduct(w,leadexp(f));
  // do the same for the remaining part of f and compare the results
  // keep only the smallest ones
  int vglgewicht;
  f=f-lead(f);
  while (f!=0)
  {
    vglgewicht=scalarproduct(w,leadexp(f));
    if (vglgewicht>gewicht)
    {
      initialf=lead(f);
      gewicht=vglgewicht;
    }
    else
    {
      if (vglgewicht==gewicht)
      {
        initialf=initialf+lead(f);
      }
    }
    f=f-lead(f);
  }
  initialf=substitute(initialf,var(1),1);
  return(initialf);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(t,x,y),dp;
   poly f=t4x2+y2-t2xy+t4x-t9;
   intvec w=-1,-2,-3;
   tInitialForm(f,w);
}

/////////////////////////////////////////////////////////////////////////

proc tInitialIdeal (ideal i,intvec w,list #)
"USAGE:      tInitialIdeal(i,w); i ideal, w intvec
ASSUME:      i is an ideal in Q[t,x_1,...,x_n] and w=(w_0,...,w_n)
RETURN:      ideal ini, the t-initial ideal of i with respect to w"
{
  // THE PROCEDURE WILL BE CALLED FROM OTHER PROCEDURES INSIDE THIS LIBRARY;
  // IN THIS CASE THE VARIABLE t WILL INDEED BE THE LAST VARIABLE INSTEAD OF
  // THE FIRST,
  // AND WE THEREFORE HAVE TO MOVE IT BACK TO THE FRONT!
  // THIS IS NOT DOCUMENTED FOR THE GENERAL USER!!!!
  def BASERING=basering;
  int j;
  if (size(#)>0)
  {
    // we first have to move the variable t to the front again
    ideal variablen=var(nvars(basering));
    for (j=1;j<nvars(basering);j++)
    {
      variablen=variablen+var(j);
    }
  }
  else
  {
    ideal variablen=maxideal(1);
  }
  // we want to homogenise the ideal i ....
  execute("ring HOMOGRING=("+charstr(basering)+"),(@s,"+string(variablen)+"),dp;");
  ideal i=homog(std(imap(BASERING,i)),@s);
  // ... and compute a standard basis with
  // respect to the homogenised ordering defined by w. Since the generators
  // of i will be homogeneous it we can instead take the ordering wp
  // with the weightvector (0,w) replaced by (M,...,M)+(0,w) for some
  // large M, so that all entries are positive
  int M=-minInIntvec(w)[1]+1; // find M such that w[j]+M is
                              // strictly positive for all j
  intvec whomog=M;
  for (j=1;j<=size(w);j++)
  {
    whomog[j+1]=w[j]+M;
  }
  intmat O=weightVectorToOrderMatrix(whomog);
  execute("ring WEIGHTRING=("+charstr(basering)+"),("+varstr(basering)+"),(M("+string(O)+"));");
  // map i to the new ring and compute a GB of i, then dehomogenise i,
  // so that we can be sure, that the
  // initial forms of the generators generate the initial ideal
  ideal i=subst(groebner(imap(HOMOGRING,i)),@s,1);
  // compute the w-initial ideal with the help of the procedure tInitialForm;
  setring BASERING;
  execute("ring COMPINIRING=("+charstr(basering)+"),("+string(variablen)+"),dp;");
  ideal i=imap(WEIGHTRING,i);
  ideal ini;
  for (j=1;j<=size(i);j++)
  {
    ini=ini,tInitialForm(i[j],w);
  }
  // the first elementin in ini is zero, we can delete this one!
  ini=simplify(ini,2);
  // convert it to a string
  setring BASERING;
  return(imap(COMPINIRING,ini));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(t,x,y),dp;
   ideal i=t2x-y+t3,t2x-y-2t3x;
   intvec w=-1,2,0;
   // the t-initial forms of the generators are
   tInitialForm(i[1],w),tInitialForm(i[2],w);
   // and they do not generate the t-initial ideal of i
   tInitialIdeal(i,w);
}

/////////////////////////////////////////////////////////////////////////

proc initialForm (poly f, intvec w)
"USAGE:      initialForm(f,w); f a polynomial, w an integer vector
ASSUME:      f is a polynomial in Q[x_1,...,x_n] and w=(w_1,...,w_n)
RETURN:      poly, the initial form of f(x) w.r.t. w
NOTE:        the initialForm consists of the terms with MAXIMAL weighted order w.r.t. w
EXAMPLE:     example initialForm;   shows an example"
{
  def BASERING=basering;
  intmat O=weightVectorToOrderMatrix(w);
  execute("ring INITIALRING=("+charstr(BASERING)+"),("+varstr(basering)+"),M("+string(O)+");");
  poly f=imap(BASERING,f);
  int GRAD=deg(f);
  poly initialf=lead(f);
  f=f-lead(f);
  while (deg(f)==GRAD)
  {
    initialf=initialf+lead(f);
    f=f-lead(f);
  }
  setring BASERING;
  return(imap(INITIALRING,initialf));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(x,y),dp;
   poly f=x3+y2-xy+x-1;
   intvec w=2,3;
   initialForm(f,w);
}

/////////////////////////////////////////////////////////////////////////

proc weightVectorToOrderMatrix (intvec w)
"USAGE:      weightVectorToOrderMatrix(w); w intvec
ASSUME:      w not zero vector
RETURN:      intmat, an order matrix yielding a weighted degree ordering
NOTE:        returns matrix of full rank with first row equal to m
EXAMPLE:     example weightVectorToOrderMatrix;   shows an example"
{
  intmat O[size(w)][size(w)]; O[1,1..size(w)]=w;
  for (int j=size(w);j>=1;j--)
  {
    if (w[j]<>0)  // find the last non-zero component of w
    {
      int r=2;
      for (int k=1;k<=size(w);k++)
      {           // fill the order matrix O with unit vectors
        if(k<>j)  // except the unit vector of the non-zero component
        {
          intvec u;
          u[size(w)]=0;
          u[k]=1;
          O[r,1..size(w)]=u;
          r=r+1;
          kill u;
        }
      }
      return(O);
    }
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   intvec v=2,3,0,0;
   weightVectorToOrderMatrix(v);
}

/////////////////////////////////////////////////////////////////////////

proc initialIdeal (ideal i, intvec w)
"USAGE:      initialIdeal(i,w); i ideal, w intvec
ASSUME:      i is an ideal in Q[x_1,...,x_n] and w=(w_1,...,w_n)
RETURN:      ideal, the initialIdeal of i w.r.t. w
NOTE:        the initialIdeal consists of the terms with MAXIMAL weighted order w.r.t. w
EXAMPLE:     example initialIdeal;   shows an example"
{
  def BASERING=basering;
  intmat O=weightVectorToOrderMatrix(w);
  execute("ring INITIALRING=("+charstr(BASERING)+"),("+varstr(basering)+"),M("+string(O)+");");
  ideal i=imap(BASERING,i);
  i=std(i);
  ideal ini;
  for (int j=1;j<=size(i);j++)
  {
    ini[j]=initialForm(i[j],w);
  }
  setring BASERING;
  return(imap(INITIALRING,ini));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(x,y),dp;
   poly f=x3+y2-xy+x-1;
   intvec w=2,3;
   initialIdeal(f,w);
}

///////////////////////////////////////////////////////////////////////////////
/// PROCEDURES CONCERNED WITH THE LATEX CONVERSION
///////////////////////////////////////////////////////////////////////////////

proc texNumber (poly p)
"USAGE:   texNumber(f); f poly
RETURN:   string, tex command representing leading coefficient of f using \frac
EXAMPLE:  example texNumber;   shows an example"
{
  number n=leadcoef(p);
  number den=denominator(n);
  number num=numerator(n);
  if (parstr(basering)=="")
  {
    if (den==-1)
    {
      den=-den;
      num=-num;
    }
    if (den==1)
    {
      return(string(num));
    }
    else
    {
      return("\\tfrac{"+string(num)+"}{"+string(den)+"}");
    }
  }
  def BASERING=basering;
  execute("ring PARAMETERRING=("+string(char(basering))+"),("+parstr(basering)+"),ds;");
  poly den=imap(BASERING,den);
  poly num=imap(BASERING,num);
  if (den==1)
  {
    return(texPolynomial(num));
  }
  else
  {
    return("\\tfrac{"+texPolynomial(num)+"}{"+texPolynomial(den)+"}");
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),x,dp;
   texNumber((3t2-1)/t3);
}

/////////////////////////////////////////////////////////////////////////

proc texPolynomial (poly f)
"USAGE:      texPolynomial(f); f poly
RETURN:      string, the tex command representing f
EXAMPLE:     example texPolynomial;   shows an example"
{
  int altshort=short;
  short=0;
  if (f==0)
  {
    return("0");
  }
  string texmf;
  string texco;
  string texf;
  string plus;
  int laenge=size(f);
  while (f!=0)
  {
    if (size(f)<laenge)
    {
      plus="+";
    }
    texmf=texmonomial(f);
    if (texmf=="1")
    {
      texco=texcoefficient(f,1);
      if (texco[1]=="-")
      {
        texf=texf+texco;
      }
      else
      {
        texf=texf+plus+texco;
      }
    }
    else
    {
      texco=texcoefficient(f);
      if (texco[1]=="-")
      {
        texf=texf+texco+texmf;
      }
      else
      {
        texf=texf+plus+texco+texmf;
      }
    }
    f=f-lead(f);
  }
  short=altshort;
  return(texf);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),x,dp;
   texPolynomial(1/t*x2-t2x+1/t);
}

/////////////////////////////////////////////////////////////////////////

proc texMatrix (matrix M)
"USAGE:      texMatrix(M); M matrix
RETURN:      string, the tex command representing M
EXAMPLE:     example texMatrix;   shows an example"
{
  int i,j;
  string texmat="\\left(\\begin{array}{";
  for (i=1;i<=ncols(M);i++)
  {
    texmat=texmat+"c";
  }
  texmat=texmat+"}
   ";
  for (i=1;i<=nrows(M);i++)
  {
    for (j=1;j<=ncols(M);j++)
    {
      texmat=texmat+texPolynomial(M[i,j]);
      if (j<ncols(M))
      {
        texmat=texmat+" & ";
      }
      else
      {
        texmat=texmat+" \\\\
     ";
      }
    }
  }
  texmat=texmat+"\\end{array}\\right)";
  return(texmat);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),x,dp;
   matrix M[2][2]=3/2,1/t*x2-t2x+1/t,5,-2x;
   texMatrix(M);
}


/////////////////////////////////////////////////////////////////////////

proc texDrawBasic (list texdraw)
"USAGE:      texDrawBasic(texdraw); list texdraw
ASSUME:      texdraw is a list of strings representing texdraw commands
             (as produced by texDrawTropical) which should be embedded into
             a texdraw environment
RETURN:      string, a texdraw environment enclosing the input
NOTE:        is called from conicWithTangents
EXAMPLE:     example texDrawBasic;   shows an example"
{
  string texdrawtp="
    \\begin{texdraw}
       \\drawdim cm  \\relunitscale 0.7 \\arrowheadtype t:V
       %\\linewd 0.05 \\lpatt (0.1 0.4)
       %\\move (-4 0) \\avec (9 0) \\move (0 -4) \\avec (0 9)
       \\linewd 0.1  \\lpatt (1 0)
       ";
  for (int i=1;i<=size(texdraw);i++)
  {
    texdrawtp=texdrawtp+texdraw[i];
  }
  texdrawtp=texdrawtp+"
    \\end{texdraw}";
  return(texdrawtp);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=x+y+1;
   string texf=texDrawTropical(tropicalCurve(f),list("",1));
   texDrawBasic(texf);
}

/////////////////////////////////////////////////////////////////////////

proc texDrawTropical (list graph,list #)
"USAGE:  texDrawTropical(graph[,#]); graph list, # optional list
ASSUME:  graph is the output of tropicalCurve
RETURN:  string, the texdraw code of the tropical plane curve encoded by graph
NOTE:    - if the list # is non-empty, the first entry should be a string;
           if this string is 'max', then the tropical curve is considered
           with respect to the maximum
@*       - the procedure computes a scalefactor for the texdraw command which
           should help to display the curve in the right way; this may,
           however, be a bad idea if several texDrawTropical outputs are
           put together to form one image; the scalefactor can be prescribed
           by the further optional entry of type poly
@*       - one can add a string as last opional argument to the list #;
           it can be used to insert further texdraw commands (e.g. to have
           a lighter image as when called from inside conicWithTangents);
@*       - the list # is optional and may as well be empty
EXAMPLE:     example texDrawTropical;   shows an example"
{
  // there is one possible argument, which is not explained to the user;
  // it is used to draw several tropical curves; there we want to suppress
  // the weights sometimes; this is done by handing over the string "noweights"
  int i,j;
  int noweights; // controls if weights should be drawn or not
  for (i=1;i<=size(#);i++)
  {
    if (typeof(#[i])=="string")
    {
      if (#[i]=="noweights")
      {
        noweights=1;
        #=delete(#,i);
      }
    }
  }
  // deal first with the pathological case that
  // the input polynomial was a monomial
  // and does therefore not define a tropical curve,
  // and check if the Newton polytope is
  // a line segment so that the curve defines a bunch of lines
  int bunchoflines;
  // if the boundary of the Newton polytope consists of a single point
  if (size(graph[size(graph)][1])==1)
  {
    return(string());
  }
  else
  {
    matrix M[2][size(graph[size(graph)][1])];
    for (i=1;i<=size(graph[size(graph)][1]);i++)
    {
      M[1,i]=graph[size(graph)][1][i][1];
      M[2,i]=graph[size(graph)][1][i][2];
    }
    // then the Newton polytope is a line segment
    if ((size(graph[size(graph)][1])-size(syz(M)))==1)
    {
      bunchoflines=1;
    }
  }
  // go on with the case that a tropical curve is defined
  string texdrawtp="

       \\setgray 0.6

       ";
  // if texdraw input has been inserted, it should be added
  if (size(#)>=1)
  {
    if (typeof(#[size(#)])=="string")
    {
      if (#[size(#)]!="max")
      {
        texdrawtp=texdrawtp+#[size(#)];
      }
    }
  }
  // find the minimal and maximal coordinates of vertices
  // and find the scale factor for the texdraw image
  list SCFINPUT;
  SCFINPUT[1]=graph;
  list SCF=minScaleFactor(SCFINPUT);
  poly minx,miny,maxx,maxy=SCF[4],SCF[5],SCF[6],SCF[7];
  poly centerx,centery=SCF[8],SCF[9];
  int nachkomma=2; // number of decimals for the scalefactor
  number sf=1; // correction factor for scalefactor
  // if no scale factor was handed over to the procedure, use the
  // one computed by minScaleFactor;
  // check first if a scale factor has been handed over
  i=1;
  int scfpresent;
  while ((i<=size(#)) and (scfpresent==0))
  {
    // if the scalefactor as polynomial was handed over, get it
    if (typeof(#[i])=="poly")
    {
      poly scalefactor=#[2];
      scfpresent=1;
    }
    // if the procedure is called for drawing more than one tropical curve
    // then scalefactor,sf,nachkomma,minx,miny,maxx,maxy,centerx,centery
    // has been handed over to the procedure
    if (typeof(#[i])=="list")
    {
      poly scalefactor=#[i][1];
      sf=#[i][2];
      nachkomma=#[i][3];
      minx=#[i][4];
      miny=#[i][5];
      maxx=#[i][6];
      maxy=#[i][7];
      centerx=#[i][8];
      centery=#[i][9];
      scfpresent=1;
    }
    i++;
  }
  // if no scalefactor was handed over we take the one computed in SCF
  if (scfpresent==0)
  {
    poly scalefactor=SCF[1];
    sf=SCF[2];
    nachkomma=SCF[3];
    texdrawtp=texdrawtp+"
       \\relunitscale "+ decimal(scalefactor,nachkomma);
  }
  // compute the texdrawoutput for the tropical curve given by f
  list relxy;
  for (i=1;i<=size(graph)-1;i++)
  {
    // if the curve is a bunch of lines no vertex has to be drawn
    if (bunchoflines==0)
    {
      texdrawtp=texdrawtp+"
       \\move ("+decimal((graph[i][1]-centerx)/sf)+" "+decimal((graph[i][2]-centery)/sf)+") \\fcir f:0 r:"+decimal(2/(leadcoef(scalefactor)*10),size(string(int(scalefactor)))+1);
    }
    // draw the bounded edges emerging from the ith vertex
    for (j=1;j<=ncols(graph[i][3]);j++)
    {
      // don't draw it twice - and if there is only one vertex
      //                       and graph[i][3][1,1] is thus 0, nothing is done
      if (i<graph[i][3][1,j])
      {
        texdrawtp=texdrawtp+"
       \\move ("+decimal((graph[i][1]-centerx)/sf)+" "+decimal((graph[i][2]-centery)/sf)+") \\lvec ("+decimal((graph[graph[i][3][1,j]][1]-centerx)/sf)+" "+decimal((graph[graph[i][3][1,j]][2]-centery)/sf)+")";
        // if the multiplicity is more than one, denote it in the picture
        if ((graph[i][3][2,j]>1) and (noweights==0))
        {
          texdrawtp=texdrawtp+"
       \\htext ("+decimal((graph[i][1]-centerx+graph[graph[i][3][1,j]][1])/(2*sf))+" "+decimal((graph[i][2]-centery+graph[graph[i][3][1,j]][2])/(2*sf))+"){$"+string(graph[i][3][2,j])+"$}";
        }
      }
    }
    // draw the unbounded edges emerging from the ith vertex
    // they should not be too long
    for (j=1;j<=size(graph[i][4]);j++)
    {
      relxy=shorten(list(decimal((3*graph[i][4][j][1][1]/scalefactor)*sf),decimal((3*graph[i][4][j][1][2]/scalefactor)*sf),string(5*sf/2)));
      texdrawtp=texdrawtp+"
       \\move ("+decimal((graph[i][1]-centerx)/sf)+" "+decimal((graph[i][2]-centery)/sf)+") \\rlvec ("+relxy[1]+" "+relxy[2]+")";
      // if the multiplicity is more than one, denote it in the picture
      if ((graph[i][4][j][2]>1) and (noweights==0))
      {
        texdrawtp=texdrawtp+"
       \\htext ("+decimal(graph[i][1]/sf-centerx/sf+graph[i][4][j][1][1]/scalefactor)+" "+decimal(graph[i][2]/sf-centery/sf+graph[i][4][j][1][2]/scalefactor)+"){$"+string(graph[i][4][j][2])+"$}";
      }
    }
  }
  // add lattice points if the scalefactor is >= 1/2
  // and was not handed over
  if ((scalefactor>1/2) and (scfpresent==0))
  {
    int uh=1;
    if (scalefactor>3)
    {
      uh=0;
    }
    texdrawtp=texdrawtp+"

   %% HERE STARTS THE CODE FOR THE LATTICE";
    for (i=int(minx)-uh;i<=int(maxx)+uh;i++)
    {
      for (j=int(miny)-uh;j<=int(maxy)+uh;j++)
      {
        texdrawtp=texdrawtp+"
        \\move ("+decimal(i-centerx)+" "+decimal(j-centery)+") \\fcir f:0.8 r:"+decimal(1/(10*scalefactor),size(string(int(scalefactor)))+1);
      }
    }
    texdrawtp=texdrawtp+"
   %% HERE ENDS THE CODE FOR THE LATTICE
                          ";
  }
  return(texdrawtp);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=x+y+x2y+xy2+1/t*xy;
   list graph=tropicalCurve(f);
// compute the texdraw code of the tropical curve defined by f
   texDrawTropical(graph);
// compute the texdraw code again, but set the scalefactor to 1
   texDrawTropical(graph,"",1);
}

/////////////////////////////////////////////////////////////////////////

proc texDrawNewtonSubdivision (list graph,list #)
"USAGE:      texDrawNewtonSubdivision(graph[,#]); graph list, # optional list
ASSUME:      graph is the output of tropicalCurve
RETURN:      string, the texdraw code of the Newton subdivision of the
                     tropical plane curve encoded by graph
NOTE:        - the list # may contain optional arguments, of which only
               one will be considered, namely the first entry of type 'poly';
               this entry should be a rational number which specifies the
               scaling factor to be used; if it is missing, the factor will
               be computed; the list # may as well be empty
@*           - note that lattice points in the Newton subdivision which are
               black correspond to markings of the marked subdivision,
               while lattice points in grey are not marked
EXAMPLE:     example texDrawNewtonSubdivision;   shows an example"
{
  int i,j,k,l;
  list boundary=graph[size(graph)][1];
  list inneredges=graph[size(graph)][2];
  intvec shiftvector=graph[size(graph)][3];
  string subdivision;
  // find maximal and minimal x- and y-coordinates and define the scalefactor
  poly maxx,maxy=1,1;
  for (i=1;i<=size(boundary);i++)
  {
    maxx=-minOfPolys(list(-maxx,-boundary[i][1]));
    maxy=-minOfPolys(list(-maxy,-boundary[i][2]));
  }
  // compute the scalefactor
  poly scalefactor=minOfPolys(list(12/leadcoef(maxx),12/leadcoef(maxy)));
  // Check if the scalefactor was handed over, then take that instead
  if (size(#)>0)
  {
    int scfpresent;
    i=1;
    while (i<=size(#) and scfpresent==0)
    {
      if (typeof(#[i])=="poly")
      {
        scalefactor=#[i];
        scfpresent=1;
      }
      i++;
    }
  }
  // check if scaling is necessary
  if (scalefactor<1)
  {
    subdivision=subdivision+"
       \\relunitscale"+ decimal(scalefactor);
  }
  // define the texdraw code for the Newton subdivision
  for (i=1;i<=size(boundary)-1;i++)
  {
    subdivision=subdivision+"
        \\move ("+string(boundary[i][1])+" "+string(boundary[i][2])+")
        \\lvec ("+string(boundary[i+1][1])+" "+string(boundary[i+1][2])+")";
  }
  subdivision=subdivision+"
        \\move ("+string(boundary[size(boundary)][1])+" "+string(boundary[size(boundary)][2])+")
        \\lvec ("+string(boundary[1][1])+" "+string(boundary[1][2])+")

    ";
  for (i=1;i<=size(inneredges);i++)
  {
    subdivision=subdivision+"
        \\move ("+string(inneredges[i][1][1])+" "+string(inneredges[i][1][2])+")
        \\lvec ("+string(inneredges[i][2][1])+" "+string(inneredges[i][2][2])+")";
  }
  // add lattice points if the scalefactor is >= 1/2
  if (scalefactor>1/2)
  {
    for (i=shiftvector[1];i<=int(maxx);i++)
    {
      for (j=shiftvector[2];j<=int(maxy);j++)
      {
        if (scalefactor > 2)
        {
          subdivision=subdivision+"
        \\move ("+string(i)+" "+string(j)+") \\fcir f:0.6 r:"+decimal(2/(10*scalefactor),size(string(int(scalefactor)))+1);
        }
        else
        {
          subdivision=subdivision+"
        \\move ("+string(i)+" "+string(j)+") \\fcir f:0.6 r:"+decimal(2/(20*scalefactor),size(string(int(scalefactor)))+1);
        }
      }
    }
    if ((shiftvector[1]!=0) or (shiftvector[2]!=0))
    {
      subdivision=subdivision+"
        \\htext (-0.3 0.1){{\\tiny $(0,0)$}}";
    }
  }
  // deal with the pathological cases
  if (size(boundary)==1) // then the Newton polytope is a point
  {
    subdivision=subdivision+"
       \\move ("+string(boundary[1][1])+" "+string(boundary[1][2])+")
       \\fcir f:0 r:0.15";
  }
  else
  {
    matrix M[2][size(boundary)];
    for (i=1;i<=size(boundary);i++)
    {
      M[1,i]=boundary[i][1];
      M[2,i]=boundary[i][2];
    }
    if ((size(boundary)-size(syz(M)))==1)
    {
      for (i=1;i<=size(boundary);i++)
      {
        subdivision=subdivision+"
       \\move ("+string(boundary[i][1])+" "+string(boundary[i][2])+")
       \\fcir f:0 r:"+decimal(2/(8*scalefactor),size(string(int(scalefactor)))+1);
      }
    }
  }
  // find the marked points in the subdivision
  poly pg;
  list markings;
  k=1;
  for (i=1;i<size(graph);i++)
  {
    pg=graph[i][5];
    while (pg!=0)
    {
      markings[k]=leadexp(pg)+shiftvector;
      pg=pg-lead(pg);
      k++;
    }
  }
  for (i=size(markings);i>=2;i--)
  {
    j=i-1;
    while (j>=1)
    {
      if (markings[i]==markings[j])
      {
        markings=delete(markings,i);
        j=0;
      }
      j--;
    }
  }
  for (i=1;i<=size(markings);i++)
  {
    if (scalefactor > 2)
    {
      subdivision=subdivision+"
       \\move ("+string(markings[i][1])+" "+string(markings[i][2])+")
       \\fcir f:0 r:"+decimal(2/(8*scalefactor),size(string(int(scalefactor)))+1);
    }
    else
    {
      subdivision=subdivision+"
       \\move ("+string(markings[i][1])+" "+string(markings[i][2])+")
       \\fcir f:0 r:"+decimal(2/(16*scalefactor),size(string(int(scalefactor)))+1);
    }
  }
  // enclose subdivision in the texdraw environment
  string texsubdivision="
    \\begin{texdraw}
       \\drawdim cm  \\relunitscale 1
       \\linewd 0.05"
    +subdivision+"
   \\end{texdraw}
    ";
  return(texsubdivision);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=x+y+x2y+xy2+1/t*xy;
   list graph=tropicalCurve(f);
// compute the texdraw code of the Newton subdivision of the tropical curve
   texDrawNewtonSubdivision(graph);
}

/////////////////////////////////////////////////////////////////////////

proc texDrawTriangulation (list triang,list polygon)
"USAGE:      texDrawTriangulation(triang,polygon);  triang,polygon list
ASSUME:      polygon is a list of integer vectors describing the
             lattice points of a marked polygon;
             triang is a list of integer vectors describing a
             triangulation of the marked polygon
             in the sense that an integer vector of the form (i,j,k) describes
             the triangle formed by polygon[i], polygon[j] and polygon[k]
RETURN:      string, a texdraw code for the triangulation described
                     by triang without the texdraw environment
EXAMPLE:     example texDrawTriangulation;   shows an example"
{
  // the header of the texdraw output
  string latex="
        \\drawdim cm  \\relunitscale 1.2 \\arrowheadtype t:V
   ";
  int i,j; // indices
  list pairs,markings; // stores edges of the triangulation, respecively
  // the marked points for each triangle store the edges and marked
  // points of the triangle
  for (i=1;i<=size(triang);i++)
  {
    pairs[3*i-2]=intvec(triang[i][1],triang[i][2]);
    pairs[3*i-1]=intvec(triang[i][2],triang[i][3]);
    pairs[3*i]=intvec(triang[i][3],triang[i][1]);
    markings[3*i-2]=triang[i][1];
    markings[3*i-1]=triang[i][2];
    markings[3*i]=triang[i][3];
  }
  // delete redundant pairs which occur more than once
  for (i=size(pairs);i>=1;i--)
  {
    for (j=1;j<i;j++)
    {
      if ((pairs[i]==pairs[j]) or ((pairs[i][1]==pairs[j][2]) and (pairs[i][2]==pairs[j][1])))
      {
        pairs=delete(pairs,i);
        j=i;
      }
    }
  }
  // delete redundant marked points which occur more than once
  for (i=size(markings);i>=1;i--)
  {
    for (j=1;j<i;j++)
    {
      if (markings[i]==markings[j])
      {
        markings=delete(markings,i);
        j=i;
      }
    }
  }
  // change the color
  latex=latex+"
        \\setgray 0";
  // draw first all marked points of the triangulation in fat black
  for (i=1;i<=size(markings);i++)
  {
    latex=latex+"
        \\move ("+string(polygon[markings[i]][1])+" "+string(polygon[markings[i]][2])+")
        \\fcir f:0 r:0.08";
  }
  // next draw all edges in black
  for (i=1;i<=size(pairs);i++)
  {
    latex=latex+"
        \\move ("+string(polygon[pairs[i][1]][1])+" "+string(polygon[pairs[i][1]][2])+")
        \\lvec ("+string(polygon[pairs[i][2]][1])+" "+string(polygon[pairs[i][2]][2])+")";
  }
  // finally daw all marked points of the polygon in small gray
  for (i=1;i<=size(polygon);i++)
  {
    latex=latex+"
        \\move ("+string(polygon[i][1])+" "+string(polygon[i][2])+")
        \\fcir f:0.7 r:0.04";
  }
  return(latex);
}
example
{
   "EXAMPLE:";
   echo=2;
   // the lattice polygon spanned by the points (0,0), (3,0) and (0,3)
   // with all integer points as markings
   list polygon=intvec(1,1),intvec(3,0),intvec(2,0),intvec(1,0),intvec(0,0),
                intvec(2,1),intvec(0,1),intvec(1,2),intvec(0,2),intvec(0,3);
   // define a triangulation by connecting the only interior point
   //        with the vertices
   list triang=intvec(1,2,5),intvec(1,5,10),intvec(1,2,10);
   // produce the texdraw output of the triangulation triang
   texDrawTriangulation(triang,polygon);
}

///////////////////////////////////////////////////////////////////////////////
/// Auxilary Procedures
///////////////////////////////////////////////////////////////////////////////

proc radicalMemberShip (poly f,ideal i)
"USAGE:  radicalMemberShip (f,i); f poly, i ideal
RETURN:  int, 1 if f is in the radical of i, 0 else
EXAMPLE:     example radicalMemberShip;   shows an example"
{
  def BASERING=basering;
  execute("ring RADRING=("+charstr(basering)+"),(@T,"+varstr(basering)+"),(dp(1),"+ordstr(basering)+");");
  ideal I=ideal(imap(BASERING,i))+ideal(1-@T*imap(BASERING,f));
  if (reduce(1,std(I))==0)
  {
    return(1);
  }
  else
  {
    return(0);
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(x,y),dp;
   ideal i=(x+1)*y2;
   // y is NOT in the radical of i
   radicalMemberShip(y,i);
   ring rr=0,(x,y),ds;
   ideal i=(x+1)*y2;
   // since this time the ordering is local, y is in the radical of i
   radicalMemberShip(y,i);
}

///////////////////////////////////////////////////////////////////////////////
/// Auxilary Procedures concerned with initialforms
///////////////////////////////////////////////////////////////////////////////

proc tInitialFormPar (poly f, intvec w)
"USAGE:  tInitialFormPar(f,w); f a polynomial, w an integer vector
ASSUME:  f is a polynomial in Q(t)[x_1,...,x_n] and w=(w_1,...,w_2)
RETURN:  poly, the t-initialform of f(t,x) w.r.t. (1,w) evaluated at t=1
NOTE:    the t-initialform are the terms with MINIMAL weighted order w.r.t. (1,w)
EXAMPLE: example tInitialFormPar;   shows an example"
{
  // compute first the t-order of the leading coefficient of f (leitkoef[1]) and
  // the rational constant corresponding to this order in leadkoef(f)
  // (leitkoef[2])
  list leitkoef=simplifyToOrder(f);
  execute("poly koef="+leitkoef[2]+";");
  // take in lead(f) only the term of lowest t-order and set t=1
  poly initialf=koef*leadmonom(f);
  // compute the order of lead(f) w.r.t. (1,w)
  int gewicht=leitkoef[1]+scalarproduct(w,leadexp(f));
  // do the same for the remaining part of f and compare the results
  // keep only the smallest ones
  int vglgewicht;
  f=f-lead(f);
  while (f!=0)
  {
    leitkoef=simplifyToOrder(f);
    vglgewicht=leitkoef[1]+scalarproduct(w,leadexp(f));
    if (vglgewicht<gewicht)
    {
      execute("koef="+leitkoef[2]+";");
      initialf=koef*leadmonom(f);
      gewicht=vglgewicht;
    }
    else
    {
      if (vglgewicht==gewicht)
      {
        execute("koef="+leitkoef[2]+";");
        initialf=initialf+koef*leadmonom(f);
      }
    }
    f=f-lead(f);
  }
  return(initialf);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t4x2+y2-t2xy+t4x-t9;
   intvec w=2,3;
   tInitialFormPar(f,w);
}

/////////////////////////////////////////////////////////////////////////

proc tInitialFormParMax (poly f, intvec w)
"USAGE:  tInitialFormParMax(f,w); f a polynomial, w an integer vector
ASSUME:  f is a polynomial in Q(t)[x_1,...,x_n] and w=(w_1,...,w_2)
RETURN:  poly, the t-initialform of f(t,x) w.r.t. (-1,w) evaluated at t=1
NOTE:    the t-initialform are the terms with MAXIMAL weighted order w.r.t. (1,w)
EXAMPLE: example tInitialFormParMax;   shows an example"
{
  // compute first the t-order of the leading coefficient of f (leitkoef[1]) and
  // the rational constant corresponding to this order in leadkoef(f)
  // (leitkoef[2])
  list leitkoef=simplifyToOrder(f);
  execute("poly koef="+leitkoef[2]+";");
  // take in lead(f) only the term of lowest t-order and set t=1
  poly initialf=koef*leadmonom(f);
  // compute the order of lead(f) w.r.t. (-1,w)
  int gewicht=-leitkoef[1]+scalarproduct(w,leadexp(f));
  // do the same for the remaining part of f and compare the results
  // keep only the largest ones
  int vglgewicht;
  f=f-lead(f);
  while (f!=0)
  {
    leitkoef=simplifyToOrder(f);
    vglgewicht=-leitkoef[1]+scalarproduct(w,leadexp(f));
    if (vglgewicht>gewicht)
    {
      execute("koef="+leitkoef[2]+";");
      initialf=koef*leadmonom(f);
      gewicht=vglgewicht;
    }
    else
    {
      if (vglgewicht==gewicht)
      {
        execute("koef="+leitkoef[2]+";");
        initialf=initialf+koef*leadmonom(f);
      }
    }
    f=f-lead(f);
  }
  return(initialf);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t4x2+y2-t2xy+t4x-1/t6;
   intvec w=2,3;
   tInitialFormParMax(f,w);
}

/////////////////////////////////////////////////////////////////////////

proc solveTInitialFormPar (ideal i)
"USAGE:      solveTInitialFormPar(i); i ideal
ASSUME:      i is a zero-dimensional ideal in Q(t)[x_1,...,x_n] generated
             by the (1,w)-homogeneous elements for some integer vector w
             - i.e. by the (1,w)-initialforms of polynomials
RETURN:      none
NOTE:        the procedure just displays complex approximations
             of the solution set of i
EXAMPLE:     example solveTInitialFormPar;   shows an example"
{
  i=subst(i,t,1);
  string CHARAKTERISTIK=charstr(basering);
  CHARAKTERISTIK=CHARAKTERISTIK[1..size(CHARAKTERISTIK)-2];
  def BASERING=basering;
  execute("ring INITIALRING=("+CHARAKTERISTIK+"),("+varstr(basering)+"),("+ordstr(basering)+");");
  list l=solve(imap(BASERING,i));
  l;
  setring BASERING;
//  return(fetch(SUBSTRING,l));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   ideal i=t2x2+y2,x-t2;
   solveTInitialFormPar(i);
}

/////////////////////////////////////////////////////////////////////////

proc detropicalise (def p)
"USAGE:   detropicalise(f); f poly or f list
ASSUME:   if f is of type poly then t is a linear polynomial with
          an arbitrary constant term and positive integer coefficients
          as further coefficients;
@*        if f is of type list then f is a list of polynomials of
          the type just described in before
RETURN:   poly, the detropicalisation of f ignoring the constant parts
NOTE:     the output will be a monomial and the constant coefficient
          has been ignored
EXAMPLE:  example detropicalise;   shows an example"
{
  poly dtp=1;
  while (p!=0)
  {
    if (leadmonom(p)!=1)
    {
      dtp=dtp*leadmonom(p)^int(leadcoef(p));
    }
    p=p-lead(p);
  }
  return(dtp);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   detropicalise(3x+4y-1);
}

/////////////////////////////////////////////////////////////////////////

proc tDetropicalise (def p)
"USAGE:   tDetropicalise(f); f poly or f list
ASSUME:   if f is of type poly then f is a linear polynomial with an
          integer constant term and positive integer coefficients
          as further coefficients;
@*        if f is of type list then it is a list of polynomials of
          the type just described in before
RETURN:   poly, the detropicalisation of f over the field Q(t)
NOTE:     the output will be a term where the coeffiecient is a Laurent
          monomial in the variable t
EXAMPLE:  example tDetropicalise;   shows an example"
{
  poly dtp;
  if (typeof(p)=="list")
  {
    int i;
    for (i=1;i<=size(p);i++)
    {
      dtp=dtp+tDetropicalise(p[i]);
    }
  }
  else
  {
    dtp=1;
    while (p!=0)
    {
      if (leadmonom(p)!=1)
      {
        dtp=dtp*leadmonom(p)^int(leadcoef(p));
      }
      else
      {
        dtp=t^int(leadcoef(p))*dtp;
      }
      p=p-lead(p);
    }
  }
  return(dtp);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   tDetropicalise(3x+4y-1);
}

///////////////////////////////////////////////////////////////////////////////
/// Auxilary Procedures concerned with conics
///////////////////////////////////////////////////////////////////////////////

proc dualConic (poly f)
"USAGE:      dualConic(f); f poly
ASSUME:      f is an affine conic in two variables x and y
RETURN:      poly, the equation of the dual conic
EXAMPLE:     example dualConic;   shows an example"
{
  if (deg(f)!=2)
  {
    "The polynomial is not a conic";
    return(0);
  }
  matrix A=coeffs(f,ideal(var(1)^2,var(1)*var(2),var(2)^2,var(1),var(2),1));
  matrix C[3][3]=A[1,1],A[2,1]/2,A[4,1]/2,A[2,1]/2,A[3,1],A[5,1]/2,A[4,1]/2,A[5,1]/2,A[6,1];
  matrix M[3][1]=var(1),var(2),1;
  matrix Cdual=-adjoint(C);
  matrix ffd=transpose(M)*Cdual*M;
  poly fdual=ffd[1,1];
  return(fdual);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=0,(x,y),dp;
   poly conic=2x2+1/2y2-1;
   dualConic(conic);
}

///////////////////////////////////////////////////////////////////////////////
/// Auxilary Procedures concerned with substitution
///////////////////////////////////////////////////////////////////////////////

proc parameterSubstitute (poly f,int N)
"USAGE:   parameterSubstitute(f,N); f poly, N int
ASSUME:   f is a polynomial in Q(t)[x_1,...,x_n] describing
          a plane curve over Q(t)
RETURN:   poly f with t replaced by t^N
EXAMPLE:  example parameterSubstitute;   shows an example"
{
  def BASERING=basering;
  number nenner=1;
  for (int i=1;i<=size(f);i++)
  {
    nenner=nenner*denominator(leadcoef(f[i]));
  }
  f=f*nenner;
  f=subst(f,t,t^N)/number(subst(nenner,t,t^N));
  return(f);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t2xy+1/t*y+t3;
   parameterSubstitute(f,3);
   parameterSubstitute(f,-1);
}

/////////////////////////////////////////////////////////////////////////

proc tropicalSubst (poly f,int N,list #)
"USAGE:   parameterSubstitute(f,N,L); f poly, N int, L list
ASSUME:   f is a polynomial in Q(t)[x_1,...,x_k]
          and L is a list of the form var(i_1),poly_1,...,v(i_k),poly_k
RETURN:   list, the list is the tropical polynomial which we get from f
                by replacing the i-th variable be the i-th polynomial
                but in the i-th polynomial the parameter t is replaced by t^1/N
EXAMPLE:  example tropicalSubst;   shows an example"
{
  f=parameterSubstitute(f,N);
  f=substitute(f,#);
  list tp=tropicalise(f);
  poly const;
  for (int i=1;i<=size(tp);i++)
  {
    const=substitute(tp[i],x,0,y,0);
    tp[i]=tp[i]-const+const/N;
  }
  return(tp);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t2x+1/t*y-1;
   tropicalSubst(f,2,x,x+t,y,tx+y+t2);
   // The procedure can be used to study the effect of a transformation of
   // the form x -> x+t^b, with b a rational number, on the tropicalisation and
   // the j-invariant of a cubic over the Puiseux series.
   f=t7*y3+t3*y2+t*(x3+xy2+y+1)+xy;
   // - the j-invariant, and hence its valuation,
   //   does not change under the transformation
   jInvariant(f,"ord");
   // - b=3/2, then the cycle length of the tropical cubic equals -val(j-inv)
   list g32=tropicalSubst(f,2,x,x+t3,y,y);
   tropicalJInvariant(g32);
   // - b=1, then it is still true, but only just ...
   list g1=tropicalSubst(f,1,x,x+t,y,y);
   tropicalJInvariant(g1);
   // - b=2/3, as soon as b<1, the cycle length is strictly less than -val(j-inv)
   list g23=tropicalSubst(f,3,x,x+t2,y,y);
   tropicalJInvariant(g23);
}

/////////////////////////////////////////////////////////////////////////

proc randomPolyInT (int d,int ug, int og, list #)
"USAGE:      randomPolyInT(d,ug,og[,#]);   d, ug, og int, # list
ASSUME:      the basering has a parameter t
RETURN:      poly, a polynomial of degree d where the coefficients are
                   of the form t^j with j a random integer between ug and og
NOTE:        if an optional argument # is given, then the coefficients are
             instead either of the form t^j as above or they are zero,
             and this is chosen randomly
EXAMPLE:     example randomPolyInT;   shows an example"
{
  if (defined(t)!=-1) { ERROR("basering has no paramter t");}
  int i,j,k;
  def BASERING=basering;
  ring RANDOMRING=(0,t),(x,y,z),dp;
  ideal m=maxideal(d);
  int nnn=size(m);
  for (i=1;i<=nnn;i++)
  {
    m[i]=subst(m[i],z,1);
  }
  poly randomPolynomial;
  for (i=1;i<=nnn;i++)
  {
    if (size(#)!=0)
    {
      k=random(0,1);
    }
    if (k==0)
    {
      j=random(ug,og);
      randomPolynomial=randomPolynomial+t^j*m[i];
    }
  }
  setring BASERING;
  poly randomPolynomial=imap(RANDOMRING,randomPolynomial);
  if ((size(randomPolynomial)<3) and (nnn>=3))
  {
    randomPolynomial=randomPolyInT(d,ug,og,#);
  }
  return(randomPolynomial);
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   randomPolyInT(3,-2,5);
   randomPolyInT(3,-2,5,1);
}

/////////////////////////////////////////////////////////////////////////

proc cleanTmp ()
"USAGE:  cleanTmp()
PURPOSE: some procedures create latex and ps-files in the directory /tmp;
         in order to remove them simply call cleanTmp();
RETURN:  none"
{
  system("sh","cd /tmp; command rm -f tropicalcurve*; command rm -f tropicalnewtonsubdivision*");
}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// AUXILARY PROCEDURES, WHICH ARE DECLARED STATIC
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/// Procedures used in tropicalparametriseNoabs respectively in tropicalLifting:
/// - phiOmega
/// - cutdown
/// - tropicalparametriseNoabs
/// - findzeros
/// - basictransformideal
/// - testw
/// - simplifyToOrder
/// - scalarproduct
/// - intvecdelete
/// - invertorder
/// - ordermaximalidealsNoabs
/// - displaypoly
/// - displaycoef
/// - choosegfanvector
/// - tropicalliftingresubstitute
//////////////////////////////////////////////////////////////////////////////

static proc phiOmega (ideal i,int j,int wj)
"USAGE:      phiOmega(i,j,wj); i ideal, j int, wj int
ASSUME:      i an ideal in Q[t,x_1,...,x_n] and 0<j<n+1
RETURN:      ideal, in i var(j) has been substituted by t^-wj*var(j)
NOTE:        is called from tropicalLifting"
{
  int k;
  ideal variablen;
  for (k=2;k<=nvars(basering);k++)
  {
    variablen=variablen+var(k);
  }
  def BASERING=basering;
  execute("ring QUOTRING=("+charstr(basering)+",t),("+string(variablen)+"),dp;");
  ideal i=subst(imap(BASERING,i),var(j-1),t^(-wj)*var(j-1));
  for (k=1;k<=size(i);k++)
  {
    i[k]=i[k]/content(i[k]);
  }
  setring BASERING;
  return(imap(QUOTRING,i));
}



/////////////////////////////////////////////////////////////////////////

static proc cutdown (ideal jideal,intvec wvec,int dimension,list #)
"USAGE:      cutdown(i,w,d); i ideal, w intvec, d int, # list
ASSUME:      i an ideal in Q[t,x_1,...,x_n], (w_1,...,w_n) is in the tropical
             variety of jideal and d=dim(i)>0, in Q(t)[x]; the optional
             parameter # can contain the string 'isPrime' to indicate that
             the input ideal is prime and no minimal associated primes have
             to be computed
RETURN:      list, the first entry is a ring, namely the basering where some
                   variables have been eliminated, and the ring contains
                   the ideal i (with the same variables eliminated),
                   the t-initial ideal ini of i (w.r.t. the weight vector
                   where the entries corresponding to the deleted variables
                   have been eliminated) and a list repl where for each
                   eliminated variable there is one entry, namely a polynomial
                   in the remaining variables and t that explains how
                   resubstitution of a solution for the new i gives a solution
                   for the old i; the second entry is the weight vector
                   wvec with the components corresponding to the eliminated
                   variables removed
NOTE:        needs the libraries random.lib and primdec.lib;
             is called from tropicalLifting"
{
  // IDEA: i is an ideal of dimension d; we want to cut it with d random linear
  //       forms in such a way that the resulting
  //       ideal is 0-dim and still contains w in the tropical variety
  // NOTE: t is the last variable in the basering
  ideal pideal;  //this is the ideal we want to return
  ideal cutideal;
  ideal pini;    //this is the initial ideal
  ideal primini; //the initial of the prime we picl
  int j1,j2,dimp,winprim,j3;
  poly product=1;
  def BASERING=basering;
  ideal variablen;
  intvec setvec;intvec wvecp;
  setvec[nvars(basering)-1]=0;
  poly randomp=0;
  poly randomp1=0;
  poly randomp2=0;
  list erglini;
  list ergl;
  for (j1=1;j1<=nvars(basering)-1;j1++)
  {
    variablen=variablen+var(j1); // read the set of variables
                                 // (needed to make the quotring later)
    product=product*var(j1); // make product of all variables
                             // (needed for the initial-monomial-check later
  }
  execute("ring QUOTRING=("+charstr(basering)+",t),("+string(variablen)+"),dp;");
  setring BASERING;
  // change to quotring where we want to compute the primary decomposition of i
  if (size(#)==0) // we only have to do so if isPrime is not set
  {
    setring QUOTRING;
    ideal jideal=imap(BASERING,jideal);
    list primp=minAssGTZ(jideal); //compute the primary decomposition
    for (j1=1;j1<=size(primp);j1++)
    {
      for(j2=1;j2<=size(primp[j1]);j2++)
      {
        // clear all denominators
        primp[j1][j2]=primp[j1][j2]/content(primp[j1][j2]);
      }
    }
    setring BASERING;
    list primp=imap(QUOTRING,primp);
    // if i is not primary itself
    // go through the list of min. ass. primes and find the first
    // one which has w in its tropical variety
    if (size(primp)>1)
    {
      j1=1;
      while(winprim==0)
      {
        //compute the t-initial of the associated prime
        // - the last entry 1 only means that t is the last variable in the ring
        primini=tInitialIdeal(primp[j1],wvec,1);
        // check if it contains a monomial (resp if the product of var
        // is in the radical)
        if (radicalMemberShip(product,primini)==0)
        {
          // if w is in the tropical variety of the prime, we take that
          jideal=primp[j1];
          setring QUOTRING;
          dimension=dim(groebner(imap(BASERING,jideal)));//compute its dimension
          setring BASERING;
          winprim=1; // and stop the checking
        }
        j1=j1+1;  //else we look at the next associated prime
      }
    }
    else
    {
      jideal=primp[1]; //if i is primary itself we take its prime instead
    }
  }
  // now we start as a first try to intersect with a hyperplane parallel to
  // coordinate axes, because this would make our further computations
  // a lot easier.
  // We choose a subset of our n variables of size d=dim(ideal).
  // For each of these
  // variables, we want to fix a value: x_i= a_i*t^-w_i.
  // This will only work if the
  // projection of the d-dim variety to the other n-d variables
  // is the whole n-d plane.
  // Then a general choice for a_i will intersect the variety
  // in finitely many points.
  // If the projection is not the whole n-d plane,
  // then a general choice will not work.
  // We could determine if we picked a good
  // d-subset of variables using elimination
  // (NOTE, there EXIST d variables such that
  // a random choice of a_i's would work!).
  // But since this involves many computations,
  // we prefer to choose randomly and just
  // try in the end if our intersected ideal
  // satisfies our requirements. If this does not
  // work, we give up this try and use our second intersection idea, which
  // will work for a Zariksi-open subset (i.e. almost always).
  //
  // As random subset of d variables we choose
  // those for which the absolute value of the
  // wvec-coordinate is smallest, because this will
  // give us the smallest powers of t and hence
  // less effort in following computations.
  // Note that the smallest absolute value have those
  // which are biggest, because wvec is negative.
  //print("first try");
  intvec wminust=intvecdelete(wvec,1);
  intmat A[2][size(wminust)];
  // make a matrix with first row -wvec (without t) and second row 1..n
  A[1,1..size(wminust)]=-wminust;
  A[2,1..size(wminust)]=1..size(wminust);
  // sort this matrix in order to get
  // the d biggest entries and their position in wvec
  A=sortintmat(A);
  // we construct a vector which has 1 at entry j if j belongs to the list
  // of the d biggest entries of wvec and a 0 else
  for (j1=1;j1<=nvars(basering)-1;j1++) //go through the variables
  {
    for (j2=1;j2<=dimension;j2++) //go through the list of smallest entries
    {
      if (A[2,j2]==j1)//if the variable belongs to this list
      {
        setvec[j1]=1;//put a 1
      }
    }
  }
  // using this 0/1-vector we produce
  // a random constant (i.e. coeff in Q times something in t)
  // for each of the biggest variables,
  // we add the forms x_i-random constant to the ideal
  // and we save the constant at the i-th place of
  // a list we want to return for later computations
  j3=0;
  while (j3<=1)
  {
    j3++;
    pideal=jideal;
    j2=1;
    for (j1=1;j1<=nvars(basering)-1;j1++)
    {
      if(setvec[j1]==1)//if x_i belongs to the biggest variables
      {
        if ((j3==1) and ((char(basering)==0) or (char(basering)>3)))
        {
          randomp1=random(1,3);
          randomp=t^(A[1,j2])*randomp1;// make a random constant
                                       // --- first we try small numbers
        }
        if ((j3==2) and ((char(basering)==0) or (char(basering)>100)))
        {
          randomp1=random(1,100);
          randomp=t^(A[1,j2])*randomp1;// make a random constant
                                       // --- next we try bigger numbers
        }
        else
        {
          randomp1=random(1,char(basering)-1);
          randomp=t^(A[1,j2])*randomp1;//make a random constant
        }
        ergl[A[2,j2]]=randomp;//and save the constant in a list
        erglini[A[2,j2]]=randomp1;
        j2=j2+1;
      }
      else
      {
        ergl[j1]=0; //if the variable is not among the d biggest ones,
                    //save 0 in the list
        erglini[j1]=0;
      }
    }
      // print(ergl);print(pideal);
      // now we check if we made a good choice of pideal, i.e. if dim=0 and
      // wvec is still in the tropical variety
      // change to quotring where we compute dimension
      cutideal=pideal;
    for(j1=1;j1<=nvars(basering)-1;j1++)
    {
      if(setvec[j1]==1)
      {
        cutideal=cutideal,var(j1)-ergl[j1];//add all forms to the ideal
      }
    }
    setring QUOTRING;
    ideal cutideal=imap(BASERING,cutideal);
    dimp=dim(groebner(cutideal)); //compute the dim of p in the quotring
    //print("dimension");
    //print(dimp);
    kill cutideal;
    setring BASERING;
    if (dimp==0) // if it is 0 as we want
    {
      // compute the t-initial of the associated prime
      // - the last 1 just means that the variable t is
      //   the last variable in the ring
      pini=tInitialIdeal(cutideal,wvec ,1);
      //print("initial");
      //print(pini);
      // and if the initial w.r.t. t contains no monomial
      // as we want (checked with
      // radical-membership of the product of all variables)
      if (radicalMemberShip(product,pini)==0)
      {
        // we made the right choice and now
        // we substitute the variables in the ideal
        // to get an ideal in less variables
        // also we make a projected vector
        // from wvec only the components of the remaining variables
        wvecp=wvec;
        variablen=0;
        j2=0;
        for(j1=1;j1<=nvars(basering)-1;j1++)
        {
          if(setvec[j1]==1)//if j belongs to the biggest variables
          {
            j2=j2+1;
            pideal=subst(pideal,var(j1),ergl[j1]);//substitute this variable
            pini=subst(pini,var(j1),erglini[j1]);
            wvecp=intvecdelete(wvecp,j1+2-j2);
          }
          else
          {
            variablen=variablen+var(j1); // read the set of remaining variables
                                         // (needed to make quotring later)
          }
        }
        // return pideal, the initial and the list ergl which tells us
        // which variables we replaced by which form
        execute("ring BASERINGLESS1=("+charstr(BASERING)+"),("+string(variablen)+",t),(dp("+string(ncols(variablen))+"),lp(1));");
        ideal i=imap(BASERING,pideal);
        ideal ini=imap(BASERING,pini); //ideal ini2=tInitialIdeal(i,wvecp,1);
        list repl=imap(BASERING,ergl);
        export(i);
        export(ini);
        export(repl);
        return(list(BASERINGLESS1,wvecp));
      }
    }
  }
  // this is our second try to cut down, which we only use if the first try
  // didn't work out. We intersect with d general hyperplanes
  // (i.e. we don't choose
  // them to be parallel to coordinate hyperplanes anymore. This works out with
  // probability 1.
  //
  // We choose general hyperplanes, i.e. linear forms which involve all x_i.
  // Each x_i has to be multiplied bz t^(w_i) in order
  // to get the same weight (namely 0)
  // for each term. As we cannot have negative exponents, we multiply
  // the whole form by t^minimumw. Notice that then in the first form,
  // there is one term without t- the term of the variable
  // x_i such that w_i is minimal. That is, we can solve for this variable.
  // In the second form, we can replace that variable,
  // and divide by t as much as possible.
  // Then there is again one term wihtout t -
  // the term of the variable with second least w.
  // So we can solve for this one again and also replace it in the first form.
  // Since all our coefficients are chosen randomly,
  // we can also from the beginning on
  // choose the set of variables which belong to the d smallest entries of wvec
  // (t not counting) and pick random forms g_i(t,x')
  // (where x' is the set of remaining variables)
  // and set x_i=g_i(t,x').
  //
  // make a matrix with first row wvec (without t) and second row 1..n
  //print("second try");
  setring BASERING;
  A[1,1..size(wminust)]=wminust;
  A[2,1..size(wminust)]=1..size(wminust);
  // sort this matrix in otder to get the d smallest entries
  // (without counting the t-entry)
  A=sortintmat(A);
  randomp=0;
  setvec=0;
  setvec[nvars(basering)-1]=0;
  // we construct a vector which has 1 at entry j if j belongs to the list of
  // the d smallest entries of wvec and a 0 else
  for (j1=1;j1<=nvars(basering)-1;j1++) //go through the variables
  {
    for (j2=1;j2<=dimension;j2++) //go through the list of smallest entries
    {
      if (A[2,j2]==j1)//if the variable belongs to this list
      {
        setvec[j1]=1;//put a 1
      }
    }
  }
  variablen=0;
  wvecp=wvec;
  j2=0;
  for(j1=1;j1<=nvars(basering)-1;j1++)
  {
    if(setvec[j1]==1)//if j belongs to the biggest variables
    {
      j2=j2+1;
      wvecp=intvecdelete(wvecp,j1+2-j2);// delete the components
                                        // we substitute from wvec
    }
    else
    {
      variablen=variablen+var(j1); // read the set of remaining variables
                                   // (needed to make the quotring later)
    }
  }
  setring BASERING;
  execute("ring BASERINGLESS2=("+charstr(BASERING)+"),("+string(variablen)+",t),(dp("+string(ncols(variablen))+"),lp(1));");
  // using the 0/1-vector which tells us which variables belong
  // to the set of smallest entries of wvec
  // we construct a set of d random linear
  // polynomials of the form x_i=g_i(t,x'),
  // where the set of all x_i is the set of
  // all variables which are in the list of smallest
  // entries in wvec, and x' are the other variables.
  // We add these d random linear polynomials to
  // the ideal pideal, i.e. we intersect
  // with these and hope to get something
  // 0-dim which still contains wvec in its
  // tropical variety. Also, we produce a list ergl
  // with g_i at the i-th position.
  // This is a list we want to return.
  // we try first with small numbers
  setring BASERING;
  pideal=jideal;
  for(j1=1;j1<=dimension;j1++)//go through the list of variables
  { // corres to the d smallest in wvec
    if ((char(basering)==0) or (char(basering)>3))
    {
      randomp1=random(1,3);
      randomp=randomp1*t^(-A[1,j1]);
    }
    else
    {
      randomp1=random(1,char(basering)-1);
      randomp=randomp1*t^(-A[1,j1]);
    }
    for(j2=1;j2<=nvars(basering)-1;j2++)//go through all variables
    {
      if(setvec[j2]==0)//if x_j belongs to the set x'
      {
        // add a random term with the suitable power
        // of t to the random linear form
        if ((char(basering)==0) or (char(basering)>3))
        {
          randomp2=random(1,3);
          randomp1=randomp1+randomp2*var(j2);
          randomp=randomp+randomp2*t^(wminust[j2]-A[1,j1])*var(j2);
        }

        else
        {
          randomp2=random(char(basering)-1);
          randomp1=randomp1+randomp2*var(j2);
          randomp=randomp+randomp2*t^(wminust[j2]-A[1,j1])*var(j2);
        }
        ergl[j2]=0;//if j belongs to x' we want a 0 in our list
        erglini[j2]=0;
        }
    }
    ergl[A[2,j1]]=randomp;// else we put there the random oly g_i(t,x')
    erglini[A[2,j1]]=randomp1;
    randomp=0;
    randomp1=0;
    }
  //print(ergl);
  // Again, we have to test if we made a good choice
  // to intersect,i.e. we have to check whether
  // pideal is 0-dim and contains wvec in the tropical variety.
  cutideal=pideal;
  for(j1=1;j1<=nvars(basering)-1;j1++)
  {
    if(setvec[j1]==1)
    {
      cutideal=cutideal,var(j1)-ergl[j1];//add all forms to the ideal
    }
  }
  setring QUOTRING;
  ideal cutideal=imap(BASERING,cutideal);
  dimp=dim(groebner(cutideal)); //compute the dim of p in the quotring
  //print("dimension");
  //print(dimp);
  kill cutideal;
  setring BASERING;
  if (dimp==0) // if it is 0 as we want
  {
    // compute the t-initial of the associated prime
    // - the last 1 just means that the variable t
    // is the last variable in the ring
    pini=tInitialIdeal(cutideal,wvec ,1);
    //print("initial");
    //print(pini);
    // and if the initial w.r.t. t contains no monomial as we want (checked with
    // radical-membership of the product of all variables)
    if (radicalMemberShip(product,pini)==0)
    {
      // we want to replace the variables x_i by the forms -g_i in
      // our ideal in order to return an ideal with less variables
      // first we substitute the chosen variables
      for(j1=1;j1<=nvars(basering)-1;j1++)
      {
        if(setvec[j1]==1)//if j belongs to the biggest variables
        {
          pideal=subst(pideal,var(j1),ergl[j1]);//substitute it
          pini=subst(pini,var(j1),erglini[j1]);
        }
      }
      setring BASERINGLESS2;
      ideal i=imap(BASERING,pideal);
      ideal ini=imap(BASERING,pini);//ideal ini2=tInitialIdeal(i,wvecp,1);
      list repl=imap(BASERING,ergl);
      export(i);
      export(ini);
      export(repl);
      return(list(BASERINGLESS2,wvecp));
    }
  }
  // now we try bigger numbers
  while (1) //a never-ending loop which will stop with prob. 1
  { // as we find a suitable ideal with that prob
    setring BASERING;
    pideal=jideal;
    for(j1=1;j1<=dimension;j1++)//go through the list of variables
    { // corres to the d smallest in wvec
      randomp1=random(1,100);
      randomp=randomp1*t^(-A[1,j1]);
      for(j2=1;j2<=nvars(basering)-1;j2++)//go through all variables
      {
        if(setvec[j2]==0)//if x_j belongs to the set x'
        {
          // add a random term with the suitable power
          // of t to the random linear form
          if ((char(basering)==0) or (char(basering)>100))
          {
            randomp2=random(1,100);
            randomp1=randomp1+randomp2*var(j2);
            randomp=randomp+randomp2*t^(wminust[j2]-A[1,j1])*var(j2);
          }
          else
          {
            randomp2=random(1,char(basering)-1);
            randomp1=randomp1+randomp2;
            randomp=randomp+randomp2*t^(wminust[j2]-A[1,j1])*var(j2);
          }
          ergl[j2]=0;//if j belongs to x' we want a 0 in our list
          erglini[j2]=0;
          }
      }
      ergl[A[2,j1]]=randomp;// else we put there the random oly g_i(t,x')
      erglini[A[2,j1]]=randomp1;
      randomp=0;
      randomp1=0;
      }
    //print(ergl);
    // Again, we have to test if we made a good choice to
    // intersect,i.e. we have to check whether
    // pideal is 0-dim and contains wvec in the tropical variety.
    cutideal=pideal;
    for(j1=1;j1<=nvars(basering)-1;j1++)
    {
      if(setvec[j1]==1)
      {
        cutideal=cutideal,var(j1)-ergl[j1];//add all forms to the ideal
      }
    }
    setring QUOTRING;
    ideal cutideal=imap(BASERING,cutideal);
    dimp=dim(groebner(cutideal)); //compute the dim of p in the quotring
    //print("dimension");
    //print(dimp);
    kill cutideal;
    setring BASERING;
    if (dimp==0) // if it is 0 as we want
    {
      // compute the t-initial of the associated prime
      // - the last 1 just means that the variable t
      // is the last variable in the ring
      pini=tInitialIdeal(cutideal,wvec ,1);
      //print("initial");
      //print(pini);
      // and if the initial w.r.t. t contains no monomial
      // as we want (checked with
      // radical-membership of the product of all variables)
      if (radicalMemberShip(product,pini)==0)
      {
        // we want to replace the variables x_i by the forms -g_i in
        // our ideal in order to return an ideal with less variables
        //first we substitute the chosen variables
        for(j1=1;j1<=nvars(basering)-1;j1++)
        {
          if(setvec[j1]==1)//if j belongs to the biggest variables
          {
            pideal=subst(pideal,var(j1),ergl[j1]);//substitute it
            pini=subst(pini,var(j1),erglini[j1]);
          }
        }
        // return pideal and the list ergl which tells us
        // which variables we replaced by which form
        setring BASERINGLESS2;
        ideal i=imap(BASERING,pideal);
        ideal ini=imap(BASERING,pini);//ideal ini2=tInitialIdeal(i,wvecp,1);
        list repl=imap(BASERING,ergl);
        export(i);
        export(ini);
        export(repl);
        return(list(BASERINGLESS2,wvecp));
      }
    }
  }
}


/////////////////////////////////////////////////////////////////////////

static proc tropicalparametriseNoabs (ideal i,intvec ww,int ordnung,int gfanold,int nogfan,int puiseux,list #)
"USAGE:  tropicalparametriseNoabs(i,tw,ord,gf,ng,pu[,#]); i ideal, tw intvec, ord int, gf,ng,pu int, # opt. list
ASSUME:  - i is an ideal in Q[t,x_1,...,x_n,X_1,...,X_k],
           tw=(w_0,w_1,...,w_n,0,...,0) and (w_0,...,w_n,0,...,0) is in
           the tropical variety of i, and ord is the order up to which a point
           in V(i) over C((t)) lying over w shall be computed;
         - moreover, k should be zero if the procedure is not called recursively;
         - the point in the tropical variety is supposed to lie in the NEGATIVE
           orthant;
         - the ideal is zero-dimensional when considered
           in (Q(t)[X_1,...,X_k]/m)[x_1,...,x_n],
           where m=#[2] is a maximal ideal in Q(t)[X_1,...,X_k];
         - gf is 0 if version 2.2 or larger is used and it is 1 else
         - ng is 1 if gfan should not be executed
         - pu is 1 if n=1 and i is generated by one polynomial and newtonpoly is used to find a
           point in the tropical variety instead of gfan
RETURN:  list, l[1] = ring Q(0,X_1,...,X_r)[[t]]
               l[2] = int
               l[3] = string
NOTE:    - the procedure is also called recursively by itself, and
           if it is called in the first recursion, the list # is empty,
           otherwise #[1] is an integer, one more than the number
           of true variables x_1,...,x_n,
           and #[2] will contain the maximal ideal m in the variables X_1,...X_k
           by which the ring Q[t,x_1,...,x_n,X_1,...,X_k] should be divided to
           work correctly in K[t,x_1,...,x_n] where K=Q[X_1,...,X_k]/m is a field
           extension of Q;
         - the ring l[1] contains an ideal PARA, which contains the
           parametrisation of a point in V(i) lying over w up to the
           first ord terms;
         - the string m=l[3] contains the code of the maximal ideal m,
           by which we have to divide Q[X_1,...,X_r] in order to have
           the appropriate field extension over which the parametrisation lives;
         - and if the integer l[2] is N then t has to be replaced by t^1/N in
           the parametrisation, or alternatively replace t by t^N in the
           defining ideal
         - the procedure REQUIRES that the program GFAN is installed on
           your computer"
{
  def ALTRING=basering;
  int recursively; // is set 1 if the procedure is called recursively by itself
  int jj,kk;
  if (size(#)==2) // this means the precedure has been called recursively
  {
    // how many variables are true variables, and how many come
    // from the field extension
    // only true variables have to be transformed
    int anzahlvariablen=#[1];
    ideal gesamt_m=std(#[2]); // stores all maxideals used for field extensions
    // find the zeros of the w-initial ideal and transform the ideal i;
    // findzeros and basictransformideal need to know how
    // many of the variables are true variables
    list m_ring=findzeros(i,ww,anzahlvariablen);
    list btr=basictransformideal(i,ww,m_ring,anzahlvariablen);
  }
  else // the procedure has been called by tropicalLifting
  {
    // how many variables are true variables, and how many come from
    // the field extension only true variables have to be transformed
    int anzahlvariablen=nvars(basering);
    ideal gesamt_m; // stores all maxideals used for field extensions
    // the initial ideal of i has been handed over as #[1]
    ideal ini=#[1];
    // find the zeros of the w-initial ideal and transform the ideal i;
    // we should hand the t-initial ideal ine to findzeros,
    // since we know it already
    list m_ring=findzeros(i,ww,ini);
    list btr=basictransformideal(i,ww,m_ring);
  }
  // check if for the transformation a field extension was necessary, i.e. if the
  // new variables had to be added to the old base ring; if so, change to the new
  // ring in which the transformed i and m and the zero a of V(m) live; otherwise
  // retreive i, a and m from btr
  if (size(btr)==1)
  {
    def PREVIOUSRING=basering;
    def TRRING=btr[1];
    setring TRRING;
    ideal gesamt_m=imap(PREVIOUSRING,gesamt_m)+m; // add the newly found maximal
                                                  // ideal to the previous ones
  }
  else
  {
    i=std(btr[1]);
    list a=btr[2];
    ideal m=btr[3];
    gesamt_m=gesamt_m+m; // add the newly found maximal
                         // ideal to the previous ones
  }
  // check if there is a solution which has the n-th component zero,
  // if so, then eliminate the n-th variable from sat(i+x_n,t),
  // otherwise leave i as it is;
  // then check if the (remaining) ideal has as solution
  // where the n-1st component is zero,
  // and procede as before; do the same for the remaining variables;
  // this way we make sure that the remaining ideal has
  // a solution which has no component zero;
  intvec deletedvariables;    // the jth entry is set 1, if we eliminate x_j
  int numberdeletedvariables; // the number of eliminated variables
  ideal variablen;  // will contain the variables which are not eliminated
  intvec tw=ww;     // in case some variables are deleted,
                    // we have to store the old weight vector
  deletedvariables[anzahlvariablen]=0;
  ideal I,LI;
  i=i+m; // if a field extension was necessary, then i has to be extended by m
  for (jj=anzahlvariablen-1;jj>=1;jj--)  // the variable t is the last one !!!
  {
    I=sat(ideal(var(jj)+i),t)[1];
    LI=subst(I,var(nvars(basering)),0);
    //size(deletedvariables)=anzahlvariablen(before elim.)
    for (kk=1;kk<=size(deletedvariables)-1;kk++)
    {
      LI=subst(LI,var(kk),0);
    }
    if (size(LI)==0) // if no power of t is in lead(I)
    { // (where the X(i) are considered as field elements)
      // get rid of var(jj)
      i=eliminate(I,var(jj));
      deletedvariables[jj]=1;
      anzahlvariablen--; // if a variable is eliminated,
                         // then the number of true variables drops
      numberdeletedvariables++;
    }
    else
    {
      variablen=variablen+var(jj); // non-eliminated true variables are stored
    }
  }
  variablen=invertorder(variablen);
  // store also the additional variables and t,
  // since they for sure have not been eliminated
  for (jj=anzahlvariablen+numberdeletedvariables-1;jj<=nvars(basering);jj++)
  {
    variablen=variablen+var(jj);
  }
  // if some variables have been eliminated,
  // then pass to a new ring which has less variables,
  // but if no variables are left, then we are done
  def BASERING=basering;
  if ((numberdeletedvariables>0) and (anzahlvariablen>1)) // if only t remains,
  { // all true variables are gone
    execute("ring NEURING=("+charstr(basering)+"),("+string(variablen)+"),(dp("+string(size(variablen)-1)+"),lp(1));");
    ideal i=imap(BASERING,i);
    ideal gesamt_m=imap(BASERING,gesamt_m);
  }
  // now we have to compute a point ww on the tropical variety
  // of the transformed ideal i;
  // of course, we only have to do so, if we have not yet
  // reached the order up to which we
  // were supposed to do our computations
  if ((ordnung>1) and (anzahlvariablen>1)) // if only t remains,
  { // all true variables are gone
    // else we have to use gfan
    def PREGFANRING=basering;
    if (nogfan!=1)
    {
      // pass to a ring which has variables which are suitable for gfan
      execute("ring GFANRING=("+charstr(basering)+"),(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z),dp;");
      ideal phiideal=b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z;
      phiideal[nvars(PREGFANRING)]=a; // map t to a
      map phi=PREGFANRING,phiideal;
      ideal i=phi(i);
      // homogenise the ideal i with the first not yet
      // used variable in our ring, since gfan
      // only handles homogenous ideals; in principle
      // for this one has first to compute a
      // standard basis of i and homogenise that,
      // but for the tropical variety (says Anders)
      // it suffices to homogenise an arbitrary system of generators
      // i=groebner(i);
      i=homog(i,maxideal(1)[nvars(PREGFANRING)+1]);
      // if gfan version >= 0.3.0 is used and the characteristic
      // is not zero, then write the basering to the output
      if ((gfanold!=1) and (char(GFANRING)!=0))
      {
        string ringvariablen=varstr(GFANRING);
        ringvariablen=ringvariablen[1..2*nvars(PREGFANRING)+1];
        write(":w /tmp/gfaninput","Z/"+string(char(GFANRING))+"Z["+ringvariablen+"]");
        // write the ideal to a file which gfan takes as input and call gfan
        write(":a /tmp/gfaninput","{"+string(i)+"}");
      }
      else
      {
        // write the ideal to a file which gfan takes as input and call gfan
        write(":w /tmp/gfaninput","{"+string(i)+"}");
      }
      if (gfanold==1)
      {
        if (charstr(basering)!="0")
        {
          system("sh","gfan_tropicalbasis --mod "+charstr(basering)+" < /tmp/gfaninput > /tmp/gfanbasis");
          system("sh","gfan_tropicalintersection < /tmp/gfanbasis > /tmp/gfanoutput");
        }
        else
        {
//          system("sh","gfan_tropicalstartingcone < /tmp/gfaninput > /tmp/gfantropstcone");
//          system("sh","gfan_tropicaltraverse < /tmp/gfantropstcone > /tmp/gfanoutput");
          system("sh","gfan_tropicalbasis < /tmp/gfaninput > /tmp/gfanbasis");
          system("sh","gfan_tropicalintersection < /tmp/gfanbasis > /tmp/gfanoutput");
        }
        string trop=read("/tmp/gfanoutput");
        setring PREGFANRING;
        intvec wneu=-1;    // this integer vector will store
                           // the point on the tropical variety
        wneu[nvars(basering)]=0;
        // for the time being simply stop Singular and set wneu by yourself
        int goon=1;
        trop;
        "CHOOSE A RAY IN THE OUTPUT OF GFAN WHICH HAS ONLY";
        "NON-POSITIVE ENTRIES AND STARTS WITH A NEGATIVE ONE,";
        "E.G. (-3,-4,-1,-5,0,0,0) - the last entry will always be 0 -";
        "THEN TYPE THE FOLLOWING COMMAND IN SINGULAR:   wneu=-3,-4,-1,-5,0,0;";
        "AND HIT THE RETURN BUTTON TWICE (!!!) - NOTE, THE LAST 0 IS OMITTED";
        "IF YOU WANT wneu TO BE TESTED, THEN SET goon=0;";

        // THIS IS NOT NECESSARY !!!! IF WE COMPUTE NOT ONLY THE
        // TROPICAL PREVARIETY
        // test, if wneu really is in the tropical variety
        while (goon==0)
        {
          if (testw(reduce(i,std(gesamt_m)),wneu,anzahlvariablen)==1)
          {
            "CHOOSE A DIFFERENT RAY";

          }
          else
          {
            goon=1;
          }
        }
      }
      else
      {
        system("sh","gfan_tropicallifting -n "+string(anzahlvariablen)+" --noMult -c < /tmp/gfaninput > /tmp/gfanoutput");
        // read the result from gfan and store it to a string,
        // which in a later version
        // should be interpreded by Singular
        intvec wneu=choosegfanvector(read("/tmp/gfanoutput"),0)[1];
        setring PREGFANRING;
      }
    }
    else // if gfan is NOT executed
    {
      // if puiseux is set, then we are in the case of a plane curve and can use the command newtonpoly
      if (puiseux==1)
      {
        list NewtP=newtonpoly(i[1]);
        wneu=NewtP[1]-NewtP[2];
        int ggteiler=gcd(wneu[1],wneu[2]);
        wneu[1]=-wneu[1] div ggteiler;
        wneu[2]=wneu[2] div ggteiler;
        if (wneu[1]>0)
        {
          wneu=-wneu;
        }
        kill NewtP,ggteiler;
      }
      else // set wneu by hand
      {
        "Set intvec wneu!";

      }
    }
  }
  // if we have not yet computed our parametrisation
  // up to the required order and
  // zero is not yet a solution, then we have
  // to go on by calling the procedure recursively;
  // if all variables were deleted, then i=0 and thus anzahlvariablen==0
  if ((ordnung>1) and (anzahlvariablen>1))
  {
    // we call the procedure with the transformed ideal i,
    // the new weight vector, with the
    // required order lowered by one, and with
    // additional parameters, namely the number of
    // true variables and the maximal ideal that
    // was computed so far to describe the field extension
    list PARALIST=tropicalparametriseNoabs(i,wneu,ordnung-1,gfanold,nogfan,puiseux,anzahlvariablen,gesamt_m);
    // the output will be a ring, in which the
    // parametrisation lives, and a string, which contains
    // the maximal ideal that describes the necessary field extension
    def PARARing=PARALIST[1];
    int tweight=-tw[1]*PARALIST[2];
    string PARAm=PARALIST[3];
    setring PARARing;
    // if some variables have been eliminated in before,
    // then we have to insert zeros
    // into the parametrisation for those variables
    if (numberdeletedvariables>0)
    {
      ideal PARAneu=PARA;
      int k;
      for (jj=1;jj<=anzahlvariablen+numberdeletedvariables-1;jj++) // t admits
      { // no parametrisation
        if (deletedvariables[jj]!=1)
        {
          k++;
          PARA[jj]=PARAneu[k];
        }
        else
        {
          PARA[jj]=poly(0);
        }
      }
    }
  }
  // otherwise we are done and we can start to compute
  // the last step of the parametrisation
  else
  {
    // we store the information on m in a string
    string PARAm=string(gesamt_m);
    // we define the weight of t, i.e. in the parametrisation t
    // has to be replaced by t^1/tweight
    int tweight=-tw[1];
    // if additional variables were necessary,
    // we introduce them now as parameters;
    // in any case the parametrisation ring will
    // have only one variable, namely t,
    // and its order will be local, so that it
    // displays the lowest term in t first
    if (anzahlvariablen+numberdeletedvariables<nvars(basering))
    {
      execute("ring PARARing=("+charstr(basering)+",X("+string(1)+".."+string(nvars(basering)-anzahlvariablen-numberdeletedvariables)+")),t,ls;");
    }
    else
    {
      execute("ring PARARing=("+charstr(basering)+"),t,ls;");
    }
    ideal PARA; // will contain the parametrisation
    // we start by initialising the entries to be zero;
    // one entry for each true variable
    // here we also have to consider the variables
    // that we have eliminated in before
    for (jj=1;jj<=anzahlvariablen+numberdeletedvariables-1;jj++)
    {
      PARA[jj]=poly(0);
    }
  }
  // we now have to change the parametrisation by
  // reverting the transformations that we have done
  list a=imap(BASERING,a);
  if (defined(wneu)==0) // when tropicalparametriseNoabs is called for the
  { // last time, it does not enter the part, where wneu is defined and the
    intvec wneu=-1;     // variable t should have weight -1
  }
  for (jj=1;jj<=anzahlvariablen+numberdeletedvariables-1;jj++)
  {
    PARA[jj]=(PARA[jj]+a[jj+1])*t^(tw[jj+1]*tweight div ww[1]);
  }
  // if we have reached the stop-level, i.e. either
  // we had only to compute up to order 1
  // or zero was a solution of the ideal, then we have
  // to export the computed parametrisation
  // otherwise it has already been exported before
  // note, if all variables were deleted, then i==0 and thus testaufnull==0
  if ((ordnung==1) or (anzahlvariablen==1))
  {
    export(PARA);
  }
  // kill the gfan files in /tmp
  system("sh","cd /tmp; /usr/bin/touch gfaninput; /usr/bin/touch gfanoutput; command rm gfaninput; command rm gfanoutput");
  // we return a list which contains the
  // parametrisation ring (with the parametrisation ideal)
  // and the string representing the maximal ideal
  // describing the necessary field extension
  return(list(PARARing,tweight,PARAm));
}

/////////////////////////////////////////////////////////////////////////

static proc findzeros (ideal i,intvec w,list #)
"USAGE:      findzeros(i,w[,#]); i ideal, w intvec, # an optional list
ASSUME:      i is an ideal in Q[t,x_1,...,x_n,X_n+1,...,X_m] and
             w=(w_0,...,w_n,0,...,0) is in the tropical variety of i
RETURN:      list, l[1] = is polynomial ring containing an associated maximal
                          ideal m of the w-initial ideal of i which does not
                          contain any monomial and where the variables
                          which do not lead to a field extension have already
                          been eliminated, and containing a list a such that
                          the non-zero entries of a correspond to the values
                          of the zero of the associated maximal ideal for the
                          eliminated variables
                   l[2] = number of variables which have not been eliminated
                   l[3] = intvec, if the entry is one then the corresponding
                                  variable has not been eliminated
NOTE:        the procedure is called from inside the recursive procedure
             tropicalparametriseNoabs;
             if it is called in the first recursion, the list #[1] contains
             the t-initial ideal of i w.r.t. w, otherwise #[1] is an integer,
             one more than the number of true variables x_1,...,x_n"
{
  def BASERING=basering;
  // set anzahlvariablen to the number of true variables
  if (typeof(#[1])=="int")
  {
    int anzahlvariablen=#[1];
    // compute the initial ideal of i
    // - the last 1 just means that the variable t is the last
    //   variable in the ring
    ideal ini=tInitialIdeal(i,w,1);
  }
  else
  {
    int anzahlvariablen=nvars(basering);
    ideal ini=#[1]; // the t-initial ideal has been computed
                    // in before and was handed over
  }
  // move to a polynomial ring with global monomial ordering
  // - the variable t is superflous
  ideal variablen;
  for (int j=1;j<=nvars(basering)-1;j++)
  {
    variablen=variablen+var(j);
  }
  execute("ring INITIALRING=("+charstr(basering)+"),("+string(variablen)+"),dp;");
  ideal ini=imap(BASERING,ini);
  // compute the associated primes of the initialideal
  // ordering the maximal ideals shall help to avoid
  // unneccessary field extensions
  list maximalideals=ordermaximalidealsNoabs(minAssGTZ(std(ini)),anzahlvariablen);
  ideal m=maximalideals[1][1];              // the first associated maximal ideal
  int neuvar=maximalideals[1][2];           // the number of new variables needed
  intvec neuevariablen=maximalideals[1][3]; // the information which variable
                                            // leads to a new one
  list a=maximalideals[1][4];               // a_k is the kth component of a
                                            // zero of m, if it is not zero
  // eliminate from m the superflous variables, that is those ones,
  // which do not lead to a new variable
  poly elimvars=1;
  for (j=1;j<=anzahlvariablen-1;j++)
  {
    if (neuevariablen[j+1]==0)
    {
      elimvars=elimvars*var(j);
    }
  }
  m=eliminate(m,elimvars);
  export(a);
  export(m);
  list m_ring=INITIALRING,neuvar,neuevariablen;
  setring BASERING;
  return(m_ring);
}


/////////////////////////////////////////////////////////////////////////

static proc basictransformideal (ideal i,intvec w,list m_ring,list #)
"USAGE:  basictransformideal(i,w,m_ring[,#]); i ideal, w intvec, m_ring list, # an optional list
ASSUME:  i is an ideal in Q[t,x_1,...,x_n,X_1,...,X_k],
         w=(w_0,...,w_n,0,...,0) is in the tropical variety of i, and
         m_ring contains a ring containing a maximal ideal m needed
         to describe the field extension over which a corresponding
         associated maximal ideal of the initialideal of i, considered
         in (Q[X_1,...,X_k]/m_alt)(t)[x_1,...,x_n], has a zero, and
         containing a list a describing the zero of m, and m_ring contains
         the information how many new variables are needed for m
RETURN:  list, either l[1] = ideal, i transformed by x_j -> (a_j+x_j)*t^w_j
                      l[2] = list,  a_1,...,a_n a point in V(m)
                      l[3] = ideal, the maximal ideal m
               or l[1] = ring which contains the ideals i and m, and the list a
NOTE:    the procedure is called from inside the recursive procedure
         tropicalparametriseNoabs;
         if it is called in the first recursion, the list # is empty,
         otherwise #[1] is an integer, the number of true variables x_1,...,x_n;
         during the procedure we check if a field extension is necessary
         to express a zero (a_1,...,a_n) of m; if so, we have to introduce
         new variables and a list containing a ring is returned, otherwise
         the list containing i, a and m is returned;
         the ideal m will be changed during the procedure since all variables
         which reduce to a polynomial in X_1,...,X_k modulo m will be eliminated,
         while the others are replaced by new variables X_k+1,...,X_k'"
{
  def BASERING=basering;  // the variable t is acutally the LAST variable !!!
  int j,k;     // counters
  // store the weighted degrees of the elements of i in an integer vector
  intvec wdegs;
  for (j=1;j<=size(i);j++)
  {
    wdegs[j]=deg(i[j],intvec(w[2..size(w)],w[1]));
  }
  // how many variables are true variables,
  // and how many come from the field extension
  // only real variables have to be transformed
  if (size(#)>0)
  {
    int anzahlvariablen=#[1];
  }
  else
  {
    int anzahlvariablen=nvars(basering);
  }
  //
  int zaehler; // testvariable
  // get the information if any new variables are needed from m_ring
  int neuvar=m_ring[2];  // number of variables which have to be added
  intvec neuevariablen=m_ring[3];  // [i]=1, if for the ith comp.
                                   // of a zero of m a new variable is needed
  def MRING=m_ring[1];   // MRING contains a and m
  list a=imap(MRING,a);  // (a_1,...,a_n)=(a[2],...,a[n+1]) will be
                         // a common zero of the ideal m
  ideal m=std(imap(MRING,m)); // m is zero, if neuvar==0,
                              // otherwise we change the ring anyway
  // if a field extension is needed, then extend the polynomial
  // ring by new variables X_k+1,...,X_k';
  if (neuvar>0)
  {
    // change to a ring where for each variable needed
    // in m a new variable has been introduced
    ideal variablen;
    // extract the variables x_1,...,x_n
    for (j=1;j<nvars(basering);j++)
    {
      variablen=variablen+var(j);
    }
    execute("ring TRANSFORMRING=("+charstr(basering)+"),("+string(variablen)+",X("+string(nvars(BASERING)-anzahlvariablen+1)+".."+string(nvars(BASERING)-anzahlvariablen+neuvar)+"),t),(dp("+string(anzahlvariablen-1)+"),dp("+string(nvars(BASERING)+neuvar-anzahlvariablen)+"),lp(1));");
    // map i into the new ring
    ideal i=imap(BASERING,i);
    // define a map phi which maps the true variables, which are not
    // reduced to polynomials in the additional variables modulo m, to
    // the corresponding newly introduced variables, and which maps
    // the old additional variables to themselves
    ideal phiideal;
    k=1;
    for (j=2;j<=size(neuevariablen);j++)  // starting with 2, since the
    { // first entry corresponds to t
      if(neuevariablen[j]==1)
      {
        phiideal[j-1]=var(nvars(BASERING)+k-1);  // -1 since t is the last variable
        k++;
      }
      else
      {
        phiideal[j-1]=0;
      }
    }
    if (anzahlvariablen<nvars(BASERING))
    {
      phiideal=phiideal,X(1..nvars(BASERING)-anzahlvariablen);
    }
    map phi=MRING,phiideal;
    // map m and a to the new ring via phi, so that the true variables
    // in m and a are replaced by
    // the corresponding newly introduced variables
    ideal m=std(phi(m));
    list a=phi(a);
  }
  // replace now the zeros among the a_j by the corresponding
  // newly introduced variables;
  // note that no component of a can be zero
  // since the maximal ideal m contains no variable!
  // moreover, substitute right away in the ideal i
  // the true variable x_j by (a_j+x_j)*t^w_j
  zaehler=nvars(BASERING)-anzahlvariablen+1;
  for (j=1;j<=anzahlvariablen;j++)
  {
    if ((a[j]==0) and (j!=1))  // a[1]=0, since t->t^w_0
    {
      a[j]=X(zaehler);
      zaehler++;
    }
    for (k=1;k<=size(i);k++)
    {
      if (j!=1) // corresponds to  x_(j-1) --  note t is the last variable
      {
        i[k]=substitute(i[k],var(j-1),(a[j]+var(j-1))*t^(-w[j]));
      }
      else // corresponds to t
      {
        i[k]=substitute(i[k],t,t^(-w[j]));
      }
    }
  }
  // we can divide the jth generator of i by t^-wdegs[j]
  for (j=1;j<=ncols(i);j++)
  {
    if (wdegs[j]<0) // if wdegs[j]==0 there is no need to divide, and
    { // we made sure that it is no positive
      i[j]=i[j]/t^(-wdegs[j]);
    }
  }
  // since we want to consider i now in the ring
  // (Q[X_1,...,X_k']/m)[t,x_1,...,x_n]
  // we can  reduce i modulo m, so that "constant terms"
  // which are "zero" since they
  // are in m will disappear; simplify(...,2) then really removes them
  i=simplify(reduce(i,m),2);
  // if new variables have been introduced, we have
  // to return the ring containing i, a and m
  // otherwise we can simply return a list containing i, a and m
  if (neuvar>0)
  {
    export(m);
    export(i);
    export(a);
    list returnlist=TRANSFORMRING;
    return(returnlist);
  }
  else
  {
    return(list(i,a,m));
  }
}

/////////////////////////////////////////////////////////////////////////

static proc testw (ideal i,intvec w,int anzahlvariablen,list #)
"USAGE:      testw(i,w,n); i ideal, w intvec, n number
ASSUME:      i is an ideal in Q[t,x_1,...,x_n,X_1,...,X_k] and
             w=(w_0,...,w_n,0,...,0)
RETURN:      int b, 0 if the t-initial ideal of i considered in
                    Q(X_1,...,X_k)[t,x_1,...,x_n] is monomial free, 1 else
NOTE:        the procedure is called by tinitialform"
{
  // compute the t-initial of i
  // - the last 1 just means that the variable t is the last variable in the ring
  if (size(#)==0)
  {
    ideal tin=tInitialIdeal(i,w);
  }
  else
  {
    ideal tin=tInitialIdeal(i,w,1);
  }

  int j;
  ideal variablen;
  poly monom=1;
  if (size(#)==0)
  {
    for (j=2;j<=anzahlvariablen;j++)
    {
      variablen=variablen+var(j);
      monom=monom*var(j);
    }
    ideal Parameter;
    for (j=anzahlvariablen+1;j<=nvars(basering);j++)
    {
      Parameter=Parameter+var(j);
    }
  }
  else
  {
    for (j=1;j<=anzahlvariablen-1;j++)
    {
      variablen=variablen+var(j);
      monom=monom*var(j);
    }
    ideal Parameter;
    for (j=anzahlvariablen;j<=nvars(basering)-1;j++)
    {
      Parameter=Parameter+var(j);
    }
  }
  def BASERING=basering;
  if (anzahlvariablen<nvars(basering))
  {
    execute("ring TINRING=("+charstr(basering)+","+string(Parameter)+"),("+string(variablen)+"),dp;");
  }
  else
  {
    execute("ring TINRING=("+charstr(basering)+"),("+string(variablen)+"),dp;");
  }
  ideal tin=imap(BASERING,tin);
  poly monom=imap(BASERING,monom);
  return(radicalMemberShip(monom,tin));
}

/////////////////////////////////////////////////////////////////////////

static proc simplifyToOrder (poly f)
"USAGE:      simplifyToOrder(f); f a polynomial
ASSUME:      f is a polynomial in Q(t)[x_1,...,x_n]
RETURN:      list, l[1] = t-order of leading term of f
                   l[2] = the rational coefficient of the term of lowest t-order
                          in lead(f)
NOTE:        the procedure is called by tInitialFormPar"
{
  string denom=string(denominator(leadcoef(f)));
  string num=string(numerator(leadcoef(f)));
  string PMet=string(par(1));
  def BASERING=basering;
  execute("ring r=0,"+PMet+",ls;");
  execute("poly denomi="+denom+";");
  execute("poly numer="+num+";");
  int ordnung=ord(numer)-ord(denomi);
  string koeffizient=string(leadcoef(numer)/leadcoef(denomi));
  setring BASERING;
  return(list(ordnung,koeffizient));
}

/////////////////////////////////////////////////////////////////////////

static proc scalarproduct (intvec w,intvec v)
"USAGE:      scalarproduct(w,v); w,v intvec
ASSUME:      w and v are integer vectors of the same length
RETURN:      int, the scalarproduct of v and w
NOTE:        the procedure is called by tropicalparametriseNoabs"
{
  int sp;
  for (int i=1;i<=size(w);i++)
  {
    sp=sp+v[i]*w[i];
  }
  return(sp);
}

/////////////////////////////////////////////////////////////////////////

static proc intvecdelete (intvec w,int i)
"USAGE:      intvecdelete(w,i); w intvec, i int
RETURN:      intvec, the integer vector w with the ith component deleted
NOTE:        the procedure is called by tropicalparametriseNoabs"
{
  if ((i<1) or (i>size(w)) or (size(w)==1))
  {
    return(w);
  }
  if (i==1)
  {
    return(w[2..size(w)]);
  }
  if (i==size(w))
  {
    return(w[1..size(w)-1]);
  }
  else
  {
    intvec erg=w[1..i-1],w[i+1..size(w)];
    return(erg);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc invertorder (ideal i)
"USAGE:      intvertorder(i); i ideal
RETURN:      ideal, the order of the entries of i has been inverted
NOTE:        the procedure is called by tropicalparametriseNoabs"
{
  ideal ausgabe;
  for (int j=size(i);j>=1;j--)
  {
    ausgabe[size(i)-j+1]=i[j];
  }
  return(ausgabe);
}

/////////////////////////////////////////////////////////////////////////

static proc ordermaximalidealsNoabs (list minassi,int anzahlvariablen)
"USAGE:      ordermaximalidealsNoabs(minassi); minassi list
ASSUME:      minassi is a list of maximal ideals
RETURN:      list, the procedure orders the maximal ideals in minassi according
                   to how many new variables are needed to describe the zeros
                   of the ideal
                   l[j][1] = jth maximal ideal
                   l[j][2] = the number of variables needed
                   l[j][3] = intvec, if for the kth variable a new variable is
                                     needed to define the corresponding zero of
                                     l[j][1], then the k+1st entry is one
                   l[j][4] = list, if for the kth variable no new variable is
                                   needed to define the corresponding zero of
                                   l[j][1], then its value is the k+1st entry
NOTE:        if a maximal ideal contains a variable, it is removed from the list;
             the procedure is called by findzeros"
{
  int j,k,l;
  int neuvar;        // number of new variables needed (for each maximal ideal)
  int pruefer;       // is set one if a maximal ideal contains a variable
  list minassisort;  // will contain the output
  for (j=1;j<=size(minassi);j++){minassisort[j]=0;} // initialise minassisort
                                                    // to fix its initial length
  list zwischen;     // needed for reordering
  list a;// (a_1,...,a_n)=(a[2],...,a[n+1]) will be a common zero of the ideal m
  poly nf;           // normalform of a variable w.r.t. m
  intvec neuevariablen; // ith entry is 1, if for the ith component of a zero
                        // of m a new variable is needed
  intvec testvariablen; // integer vector of length n=number of variables
  // compute for each maximal ideal the number of new variables,
  // which are needed to describe
  // its zeros -- note, a new variable is needed if modulo
  // the maximal ideal it does not reduce
  // to something which only depends on the following variables;
  // if no new variable is needed, then store the value
  // a variable reduces to in the list a;
  for (j=size(minassi);j>=1;j--)
  {
    a[1]=poly(0);         // the first entry in a and in neuevariablen
                          // corresponds to the variable t,
    neuevariablen[1]=0;   // which is not present in the INITIALRING
    neuvar=0;
    minassi[j]=std(minassi[j]);
    for (k=1;(k<=anzahlvariablen-1) and (pruefer==0);k++)
    {
      nf=reduce(var(k),minassi[j]);
      // if a variable reduces to zero, then the maximal ideal
      // contains a variable and we can delete it
      if (nf==0)
      {
        pruefer=1;
      }
      // set the entries of testvariablen corresponding to the first
      // k variables to 1, and the others to 0
      for (l=1;l<=nvars(basering);l++)
      {
        if (l<=k)
        {
          testvariablen[l]=1;
        }
        else
        {
          testvariablen[l]=0;
        }
      }
      // if the variable x_j reduces to a polynomial
      // in x_j+1,...,x_n,X_1,...,X_k modulo m
      // then we can eliminate x_j from the maximal ideal
      // (since we do not need any
      // further field extension to express a_j) and a_j
      // will just be this normalform,
      // otherwise we have to introduce a new variable in order to express a_j;
      if (scalarproduct(leadexp(nf),testvariablen)==0)
      {
        a[k+1]=nf; // a_k is the normal form of the kth variable modulo m
        neuevariablen[k+1]=0;  // no new variable is needed
      }
      else
      {
        a[k+1]=poly(0); // a_k is set to zero until we have
                        // introduced the new variable
        neuevariablen[k+1]=1;
        neuvar++;       // the number of newly needed variables is raised by one
      }
    }
    // if the maximal ideal contains a variable, we simply delete it
    if (pruefer==0)
    {
      minassisort[j]=list(minassi[j],neuvar,neuevariablen,a);
    }
    // otherwise we store the information on a,
    // neuevariablen and neuvar together with the ideal
    else
    {
      minassi=delete(minassi,j);
      minassisort=delete(minassisort,j);
      pruefer=0;
    }
  }
  // sort the maximal ideals ascendingly according to
  // the number of new variables needed to
  // express the zero of the maximal ideal
  for (j=2;j<=size(minassi);j++)
  {
    l=j;
    for (k=j-1;k>=1;k--)
    {
      if (minassisort[l][2]<minassisort[k][2])
      {
        zwischen=minassisort[l];
        minassisort[l]=minassisort[k];
        minassisort[k]=zwischen;
        l=k;
      }
    }
  }
  return(minassisort);
}

/////////////////////////////////////////////////////////////////////////

static proc displaypoly(poly p,int N,int wj,int w1)
"USAGE:  displaypoly(p,N,wj,w1); p poly, N, wj, w1 int
ASSUME:  p is a polynomial in r=(0,X(1..k)),t,ls
RETURN:  string, the string of t^-wj/w1*p(t^1/N)
NOTE:    the procedure is called from displayTropicalLifting"
{
  if (p==0)
  {
    return(string(0));
  }
  ideal tpowers;
  for (int j=ord(p);j<=deg(p);j++)
  {
    tpowers=tpowers,t^j;
  }
  tpowers=simplify(tpowers,2);
  ideal koeffizienten=flatten(coeffs(p,tpowers));;
  string dp;
  for (j=ord(p);j<=deg(p);j++)
  {
    if (koeffizienten[j-ord(p)+1]!=0)
    {
      if ((j-(N*wj) div w1)==0)
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1]);
      }
      if (((j-(N*wj) div w1)==1) and (N!=1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*t^(1/"+string(N)+")";
      }
      if (((j-(N*wj) div w1)==1) and (N==1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*t";
      }
      if (((j-(N*wj) div w1)==-1) and (N==1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*1/t";
      }
      if (((j-(N*wj) div w1)==-1) and (N!=1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*1/t^(1/"+string(N)+")";
      }
      if (((j-(N*wj) div w1)>1) and (N==1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*t^"+string(j-(N*wj) div w1);
      }
      if (((j-(N*wj) div w1)>1) and (N!=1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*t^("+string(j-(N*wj) div w1)+"/"+string(N)+")";
      }
      if (((j-(N*wj) div w1)<-1) and (N==1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*1/t^"+string(wj-j);
      }
      if (((j-(N*wj) div w1)<-1) and (N!=1))
      {
        dp=dp+displaycoef(koeffizienten[j-ord(p)+1])+"*1/t^("+string((N*wj) div w1-j)+"/"+string(N)+")";
      }
      if (j<deg(p))
      {
        dp=dp+" + ";
      }
    }
  }
  return(dp);
}

/////////////////////////////////////////////////////////////////////////

static proc displaycoef (poly p)
"USAGE:      displaycoef(p); p poly
RETURN:      string, the string of p where brackets around
                     have been added if they were missing
NOTE:        the procedure is called from displaypoly"
{
  string pp=string(p);
  if (pp[1]=="(")
  {
    return(pp);
  }
  else
  {
    return("("+pp+")");
  }
}

/////////////////////////////////////////////////////////////////////////

static proc choosegfanvector (string s,int findall)
"USAGE:   choosegfanvector(s); s string
RETURN:   list, the jth entry is the jth integer vector contained in s
NOTE:     the procedure is called from tropicalparametrise"
{
  if (findall==0) // if only one point in the tropical variety should be found
  {
    int i=2;
    string w;
    while (s[i]!=")")
    {
      w=w+s[i];
      i++;
    }
    execute("intvec ww="+w+";");
    ww=ww[1..size(ww)-1];
    return(list(ww));
  }
  else
  {
    int i=1;
    string w;
    list ww;
    intvec www;
    while (size(s)!=0)
    {
      while ((s[1]!="(") and (size(s)!=0))
      {
        s=stringdelete(s,1);
      }
      if (size(s)!=0)
      {
        s=stringdelete(s,1);
      }
      while ((s[1]!=")") and (size(s)!=0))
      {
        w=w+s[1];
        s=stringdelete(s,1);
      }
      if (size(s)!=0)
      {
        execute("www=intvec("+w+");");
        ww[i]=intvec(www[1..size(www)-1]);
        w="";
        i++;
      }
    }
    return(ww);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc tropicalliftingresubstitute (ideal i,list liftring,int N,list #)
"USAGE:   tropicalliftingresubstitute(i,L,N[,#]); i ideal, L list, N int, # string
ASSUME:   i is an ideal and L[1] is a ring which contains the lifting of a
          point in the tropical variety of i computed with tropicalLifting;
          t has to be replaced by t^1/N in the lifting; #[1]=m is the string
          of the maximal ideal defining the necessary field extension as
          computed by tropicalLifting, if #[1] is present
RETURN:   string, the lifting has been substituted into i
NOTE:     the procedure is called from tropicalLifting"
{
  def BASERING=basering;
  def LIFTRing=liftring[1];
  if (size(parstr(LIFTRing))!=0)
  {
    if (size(#)>0) // noAbs was used
    {
      execute("ring NOQRing=("+string(char(LIFTRing))+"),("+varstr(basering)+","+parstr(LIFTRing)+"),dp;");
      execute("qring TESTRing=std("+#[1]+");");
      ideal i=imap(BASERING,i);
    }
    else // absolute primary decomposition was used
    {
      setring LIFTRing;
      poly mp=minpoly;
      execute("ring TESTRing=("+charstr(LIFTRing)+"),("+varstr(BASERING)+"),dp;");
      minpoly=number(imap(LIFTRing,mp));
      ideal i=imap(BASERING,i);
    }
  }
  else
  {
    def TESTRing=BASERING;
    setring TESTRing;
  }
  // map the ideal LIFT to the TESTRing and substitute the solutions in i
  ideal liftideal=imap(LIFTRing,LIFT);
  for (int j=1;j<=ncols(liftideal);j++)
  {
    i=substitute(i,var(j),liftideal[j]);
  }
  // map the resulting i back to LIFTRing;
  // if noAbs, then reduce i modulo the maximal ideal
  // before going back to LIFTRing
  if ((size(parstr(LIFTRing))!=0) and size(#)>0)
  {
    i=reduce(i,std(0));
    setring LIFTRing;
    ideal i=imap(TESTRing,i);
  }
  else
  {
    setring LIFTRing;
    ideal i=imap(TESTRing,i);
  }
  list SUBSTTEST;
  // replace t by t^1/N
  for (j=1;j<=ncols(i);j++)
  {
    SUBSTTEST[j]=displaypoly(i[j],N,0,1);
  }
  return(SUBSTTEST);
}

///////////////////////////////////////////////////////////////////////////////
/// Procedures used in tropicalLifting when using absolute primary decomposition
/// - tropicalparametrise
/// - eliminatecomponents
/// - findzerosAndBasictransform
/// - ordermaximalideals
///////////////////////////////////////////////////////////////////////////////

static proc tropicalparametrise (ideal i,intvec ww,int ordnung,intvec ordnungskontrollvektor,int gfanold,int findall,int nogfan,int puiseux,list #)
"USAGE:  tropicalparametrise(i,tw,ord,gf,fa,ng,pu[,#]); i ideal, tw intvec, ord int, gf,fa,ng,pu int, # opt. list
ASSUME:  - i is an ideal in Q[t,x_1,...,x_n,@a], tw=(w_0,w_1,...,w_n,0)
           and (w_0,...,w_n,0) is in the tropical variety of i,
           and ord is the order up to which a point in V(i)
           over K{{t}} lying over w shall be computed;
         - moreover, @a should be not be there if the procedure is not
           called recursively;
         - the point in the tropical variety is supposed to lie in the
           NEGATIVE orthant;
         - the ideal is zero-dimensional when considered in
           (K(t)[@a]/m)[x_1,...,x_n], where m=#[2] is a maximal ideal in K[@a];
         - gf is 0 if version 2.2 or larger is used and it is 1 else
         - fa is 1 if all solutions should be found
         - ng is 1 if gfan should not be executed
         - pu is 1 if n=1 and i is generated by one polynomial and newtonpoly is used to find a
           point in the tropical variety instead of gfan
RETURN:  list, l[1] = ring K[@a]/m[[t]]
               l[2] = int
NOTE:    - the procedure is also called recursively by itself, and
           if it is called in the first recursion, the list # is empty,
           otherwise #[1] is an integer, one more than the number of
           true variables x_1,...,x_n, and #[2] will contain the maximal
           ideal m in the variable @a by which the ring K[t,x_1,...,x_n,@a]
           should be divided to work correctly in L[t,x_1,...,x_n] where
           L=Q[@a]/m is a field extension of K
         - the ring l[1] contains an ideal PARA, which contains the
           parametrisation of a point in V(i) lying over w up to the first
           ord terms;
         - the string m contains the code of the maximal ideal m, by which we
           have to divide K[@a] in order to have the appropriate field extension
           over which the parametrisation lives;
         - and if the integer l[3] is N then t has to be replaced by t^1/N in the
           parametrisation, or alternatively replace t by t^N in the defining
           ideal
         - the procedure REQUIRES that the program GFAN is installed
           on your computer"
{
  def BASERING=basering;
  int recursively; // is set 1 if the procedure is called recursively by itself
  int ii,jj,kk,ll,jjj,kkk,lll;
  if (typeof(#[1])=="int") // this means the precedure has been
  { // called recursively
    // how many variables are true variables, and how many come
    // from the field extension
    // only true variables have to be transformed
    int anzahlvariablen=#[1];
    // find the zeros of the w-initial ideal and transform the ideal i;
    // findzeros and basictransformideal need to know
    // how many of the variables are true variables
    // and do the basic transformation as well
    list zerolist=#[2];
    list trring=findzerosAndBasictransform(i,ww,zerolist,findall,anzahlvariablen);
  }
  else // the procedure has been called by tropicalLifting
  {
    // how many variables are true variables, and
    // how many come from the field extension
    // only true variables have to be transformed
    int anzahlvariablen=nvars(basering);
    list zerolist; // will carry the zeros which are
    //computed in the recursion steps
    // the initial ideal of i has been handed over as #[1]
    ideal ini=#[1];
    // find the zeros of the w-initial ideal and transform the ideal i;
    // we should hand the t-initial ideal ine to findzeros,
    // since we know it already;
    // and do the basic transformation as well
    list trring=findzerosAndBasictransform(i,ww,zerolist,findall,ini);
  }
  list wneulist; // carries all newly computed weight vector
  intvec wneu;   // carries the newly computed weight vector
  intvec okvneu; // carries the newly computed ordnungskontrollvektor
  int tweight;   // carries the weight of t
  list PARALIST; // carries the result when tropicalparametrise
                 // is recursively called
  list eliminaterings;     // carries the result of eliminatecomponents
  intvec deletedvariables; // contains inform. which variables have been deleted
  deletedvariables[anzahlvariablen-1]=0; // initialise this vector
  int numberdeletedvariables;  // the number of deleted variables
  int oldanzahlvariablen=anzahlvariablen; // anzahlvariablen for later reference
  list liftings,partliftings;  // the computed liftings (all resp. partly)
  // consider each ring which has been returned when computing the zeros of the
  // the t-initial ideal, equivalently, consider
  // each zero which has been returned
  for (jj=1;jj<=size(trring);jj++)
  {
    def TRRING=trring[jj];
    setring TRRING;
    // check if a certain number of components lead to suitable
    // solutions with zero components;
    // compute them all if findall==1
    eliminaterings=eliminatecomponents(i,m,oldanzahlvariablen,findall,oldanzahlvariablen-1,deletedvariables);
    // consider each of the rings returned by eliminaterings ...
    // there is at least one !!!
    for (ii=1;ii<=size(eliminaterings);ii++)
    {
      // #variables which have been eliminated
      numberdeletedvariables=oldanzahlvariablen-eliminaterings[ii][2];
      // #true variables which remain (including t)
      anzahlvariablen=eliminaterings[ii][2];
      // a 1 in this vector says that variable was eliminated
      deletedvariables=eliminaterings[ii][3];
      setring TRRING; // set TRRING - this is important for the loop
      // pass the ring computed by eliminatecomponents
      def PREGFANRING=eliminaterings[ii][1];
      setring PREGFANRING;
      poly m=imap(TRRING,m);        // map the maximal ideal to this ring
      list zero=imap(TRRING,zero);  // map the vector of zeros to this ring
      // now we have to compute a point ww on the tropical
      // variety of the transformed ideal i;
      // of course, we only have to do so, if we have
      // not yet reached the order up to which we
      // were supposed to do our computations
      if ((ordnung>1) and (anzahlvariablen>1)) // if only t remains,
      { // all true variables are gone
        if (nogfan!=1)
        {
          // pass to a ring which has variables which are suitable for gfan
          execute("ring GFANRING=("+string(char(basering))+"),(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z),dp;");
          ideal phiideal=b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z;
          phiideal[nvars(PREGFANRING)]=a; // map t to a
          map phi=PREGFANRING,phiideal;
          ideal II=phi(i);
          // homogenise the ideal II with the first not yet
          // used variable in our ring, since gfan
          // only handles homogenous ideals; in principle for this
          // one has first to compute a
          // standard basis of II and homogenise that,
          // but for the tropical variety (says Anders)
          // it suffices to homogenise an arbitrary system of generators
          // II=groebner(II);
          II=homog(II,maxideal(1)[nvars(PREGFANRING)+1]);
          // if gfan version >= 0.3.0 is used and the characteristic
          // is not zero, then write the basering to the output
          if ((gfanold!=1) and (char(GFANRING)!=0))
          {
            string ringvariablen=varstr(GFANRING);
            ringvariablen=ringvariablen[1..2*nvars(PREGFANRING)+1];
            write(":w /tmp/gfaninput","Z/"+string(char(GFANRING))+"Z["+ringvariablen+"]");
            // write the ideal to a file which gfan takes as input and call gfan
            write(":a /tmp/gfaninput","{"+string(II)+"}");
          }
          else
          {
            // write the ideal to a file which gfan takes as input and call gfan
            write(":w /tmp/gfaninput","{"+string(II)+"}");
          }
          if (gfanold==1)
          {
            if (charstr(basering)!="0")
            {
              system("sh","gfan_tropicalbasis --mod "+charstr(basering)+" < /tmp/gfaninput > /tmp/gfanbasis");
              system("sh","gfan_tropicalintersection < /tmp/gfanbasis > /tmp/gfanoutput");
            }
            else
            {
//      system("sh","gfan_tropicalstartingcone < /tmp/gfaninput > /tmp/gfantropstcone");
//      system("sh","gfan_tropicaltraverse < /tmp/gfantropstcone > /tmp/gfanoutput");
              system("sh","gfan_tropicalbasis < /tmp/gfaninput > /tmp/gfanbasis");
              system("sh","gfan_tropicalintersection < /tmp/gfanbasis > /tmp/gfanoutput");
            }
            string trop=read("/tmp/gfanoutput");
            setring PREGFANRING;
            wneu=-1;    // this integer vector will store the point on the tropical variety
            wneu[nvars(basering)]=0;
            // for the time being simply stop Singular and set wneu by yourself
            int goon=1;
            trop;
            "CHOOSE A RAY IN THE OUTPUT OF GFAN WHICH HAS ONLY";
            "NON-POSITIVE ENTRIES AND STARTS WITH A NEGATIVE ONE,";
            "E.G. (-3,-4,-1,-5,0,0,0) - the last entry will always be 0 -";
            "THEN TYPE THE FOLLOWING COMMAND IN SINGULAR:   wneu=-3,-4,-1,-5,0,0;";
            "AND HIT THE RETURN BUTTON - NOTE, THE LAST 0 IS OMITTED";
            "IF YOU WANT wneu TO BE TESTED, THEN SET goon=0;";

            // THIS IS NOT NECESSARY !!!! IF WE COMPUTE NOT ONLY
            // THE TROPICAL PREVARIETY
            // test, if wneu really is in the tropical variety
            while (goon==0)
            {
              if (testw(reduce(i,std(gesamt_m)),wneu,anzahlvariablen)==1)
              {
                "CHOOSE A DIFFERENT RAY";

              }
              else
              {
                goon=1;
              }
            }
            wneulist[1]=wneu;
          }
          else
          {
            system("sh","gfan_tropicallifting -n "+string(anzahlvariablen)+" --noMult -c < /tmp/gfaninput > /tmp/gfanoutput");
            // read the result from gfan and store it to a string,
            // which in a later version
            // should be interpreded by Singular
            wneulist=choosegfanvector(read("/tmp/gfanoutput"),findall);
            setring PREGFANRING;
          }
          kill GFANRING;
        }
        else // if gfan is NOT executed
        {
          // if puiseux is set, then we are in the case of a plane curve and can use the command newtonpoly
          if (puiseux==1)
          {
            if (nvars(basering)>2) // if the basering has a parameter
            { // we have to pass to a ring with two variables to compute the newtonpoly
              def PRENPRing=basering;
              poly NPpoly=i[1];
              ring NPRING=(0,@a),(x(1),t),ds;
              poly NPpoly=imap(PRENPRing,NPpoly);
              list NewtP=newtonpoly(NPpoly);
              setring PRENPRing;
              kill NPRING;
            }
            else
            {
              list NewtP=newtonpoly(i[1]);
            }
            for (jjj=1;jjj<=size(NewtP)-1;jjj++)
            {
              wneu=NewtP[jjj]-NewtP[jjj+1];
              int ggteiler=gcd(wneu[1],wneu[2]);
              wneu[1]=-wneu[1] div ggteiler;
              wneu[2]=wneu[2] div ggteiler;
              if (wneu[1]>0)
              {
                wneu=-wneu;
              }
              if (nvars(basering)>2)
              {
                wneu[3]=0;
              }
              wneulist[jjj]=wneu;
            }
            kill NewtP,ggteiler;
          }
          else // we have to set the points in the tropical variety by hand
          {
            if (findall==1)
            {
              "Set wneulist!";

            }
            else
            {
              "Set intvec wneu!";

              wneulist[1]=wneu;
            }
          }
        }
      }
      // if we have not yet computed our parametrisation up to
      // the required order and
      // zero is not yet a solution, then we have to go on
      // by calling the procedure recursively;
      // if all variables were deleted, then i=0 and thus anzahlvariablen==0
      lll=0;
      if (((puiseux==0) and (ordnung>1)) or ((puiseux==1) and (ordnungskontrollvektor[2]<ordnungskontrollvektor[1]*ordnung)) and (anzahlvariablen>1))
      {
        partliftings=list(); // initialise partliftings
        // we call the procedure with the transformed
        // ideal i, the new weight vector, with the
        // required order lowered by one, and with
        // additional parameters, namely the number of
        // true variables and the maximal ideal that
        // was computed so far to describe the field extension
        for (kk=1;kk<=size(wneulist);kk++)
        {
          wneu=wneulist[kk];
          okvneu=-ordnungskontrollvektor[1]*wneu[1],-ordnungskontrollvektor[2]*wneu[1]-wneu[2];
          if (puiseux==0)
          {
            PARALIST=tropicalparametrise(i,wneu,ordnung-1,okvneu,gfanold,findall,nogfan,puiseux,anzahlvariablen,zero);
          }
          else
          {
            PARALIST=tropicalparametrise(i,wneu,ordnung,okvneu,gfanold,findall,nogfan,puiseux,anzahlvariablen,zero);
          }
          // the output will be a ring, in which the
          // parametrisation lives, and a string, which contains
          // the maximal ideal that describes the necessary field extension
          for (ll=1;ll<=size(PARALIST);ll++)
          {
            def PARARing=PARALIST[ll][1];
            tweight=-ww[1]*PARALIST[ll][2];
            setring PARARing;
            // if some variables have been eliminated
            // in before, then we have to insert zeros
            // into the parametrisation for those variables
            if (numberdeletedvariables>0)
            {
              ideal PARAneu=PARA;
              kkk=0;
              for (jjj=1;jjj<=anzahlvariablen+numberdeletedvariables-1;jjj++)
              { // t admits no parametrisation
                if (deletedvariables[jjj]!=1)
                {
                  kkk++;
                  PARA[jjj]=PARAneu[kkk];
                }
                else
                {
                  PARA[jjj]=poly(0);
                }
              }
            }
            lll++;
            partliftings[lll]=list(PARARing,tweight,wneu);
            setring PREGFANRING;
            kill PARARing;
          }
        }
      }
      // otherwise we are done and we can start
      // to compute the last step of the parametrisation
      else
      {
        // we define the weight of t, i.e. in the
        // parametrisation t has to be replaced by t^1/tweight
        tweight=-ww[1];
        // if additional variables were necessary,
        // we introduce them now as parameters;
        // in any case the parametrisation ring will
        // have only one variable, namely t,
        // and its order will be local, so that it
        // displays the lowest term in t first
        if (anzahlvariablen<nvars(basering))
        {
          execute("ring PARARing=("+string(char(basering))+",@a),t,ls;");
          minpoly=number(imap(PREGFANRING,m));
        }
        else
        {
          execute("ring PARARing=("+charstr(basering)+"),t,ls;");
        }
        ideal PARA; // will contain the parametrisation
        // we start by initialising the entries to be zero;
        // one entry for each true variable
        // here we also have to consider the variables
        // that we have eliminated in before
        for (jjj=1;jjj<=anzahlvariablen+numberdeletedvariables-1;jjj++)
        {
          PARA[jjj]=poly(0);
        }
        list zeros=imap(PREGFANRING,zero);
        export(PARA);
        export(zeros);
        partliftings=list(list(PARARing,tweight));
        kill PARARing;
      }
      // we now have to change the parametrisation by
      // reverting the transformations that we have done
      for (lll=1;lll<=size(partliftings);lll++)
      {
        if (size(partliftings[lll])==2) // when tropicalparametrise is called
        { // for the last time, it does not enter the part, where wneu is
          wneu=-1;     // defined and the variable t should have weight -1
        }
        else
        {
          wneu=partliftings[lll][3];
          partliftings[lll]=delete(partliftings[lll],3);
        }
        tweight=partliftings[lll][2];
        def PARARing=partliftings[lll][1];
        setring PARARing;
        for (jjj=1;jjj<=anzahlvariablen+numberdeletedvariables-1;jjj++)
        {
          PARA[jjj]=(PARA[jjj]+zeros[size(zeros)][jjj+1])*t^(ww[jjj+1]*tweight div ww[1]);
        }
        // delete the last entry in zero, since that one has
        // been used for the transformation
        zeros=delete(zeros,size(zeros));
        // in order to avoid redefining commands an empty
        // zeros list should be removed
        if (size(zeros)==0)
        {
          kill zeros;
        }
        partliftings[lll]=list(PARARing,tweight);
        setring TRRING;
        kill PARARing;
      }
      kill PREGFANRING;
      liftings=liftings+partliftings;
    }
    kill TRRING;
  }
  if (nogfan!=1)
  {
    // kill the gfan files in /tmp
    system("sh","cd /tmp; /usr/bin/touch gfaninput; /usr/bin/touch gfanoutput; command rm gfaninput; command rm gfanoutput");
  }
  // we return a list which contains lists of the parametrisation
  // rings (with the parametrisation ideal)
  // and an integer N such that t should be replaced by t^1/N
  return(liftings);
}

/////////////////////////////////////////////////////////////////////////

static proc eliminatecomponents (ideal i,ideal m,int anzahlvariablen,int findall,int lastvar,intvec deletedvariables)
"USAGE:  eliminatecomponents(i,m,n,a,v,d); i,m ideal, n,a,v int, d intvec
ASSUME:  i is an ideal in Q[x_1,...,x_n,@a,t] and w=(-w_1/w_0,...,-w_n/w_0)
         is in the tropical variety of i considered in
         Q[@a]/m{{t}}[x_1,...,x_n];
         considered in this ring i is zero-dimensional; @a need not be present
         in which case m is zero; 1<=v<=n
RETURN:  list, L of lists
               L[j][1] = a ring containing an ideal i and an ideal m
               L[j][2] = an integer anzahlvariablen
               L[j][3] = an intvec deletedvariables
NOTE:    - the procedure is called from inside the recursive
           procedure tropicalparametrise
         - the procedure checks for solutions which have certain
           components zero; these are separated from the rest by
           elimination and saturation; the integer deletedvariables
           records which variables have been eliminated;
           the integer anzahlvariablen records how many true variables remain
           after the elimination
         - if the integer a is one then all zeros of the ideal i are
           considered and found, otherwise only one is considered, so that L
           has length one"
{
  def BASERING=basering;
  int j,k; // index variable
  ideal I,LI; // stores the changed ideal i, respectively its leading ideal
  // if all solutions have to be found
  if (findall==1)
  {
    list saturatelist,eliminatelist; // carry the solution of the two tests
    // we test first if there is a solution which has the component
    // lastvar zero and
    // where the order of each component is strictly positive;
    // if so, we add this variable to the ideal and
    // eliminate it - which amounts to
    // to projecting the solutions with this component
    // zero to the hyperplane without this component;
    // for the test we compute the saturation with
    // respect to t and replace each variable
    // x_i and also t by zero -- if the result is zero,
    // then 1 is not in I:t^infty
    // (i.e. there is a solution which has the component lastvar zero) and
    // the result lives in the maximal
    // ideal <t,x_1,...,[no x_lastvar],...,x_n> so that
    // there is a solution which has strictly positive valuation
    // ADDENDUM:
    // if i (without m) has only one polynomial, then we can divide
    // i by t as long as possible to compute the saturation with respect to t
/*
    // DER NACHFOLGENDE TEIL IST MUELL UND WIRD NICHT MEHR GAMACHT
    // for the test we simply compute the leading ideal
    // and set all true variables zero;
    // since the ordering was an elimination ordering
    // with respect to (@a if present and) t
    // there remains something not equal to zero
    // if and only if there is polynomial which only
    // depends on t (and @a if present), but that is
    // a unit in K{{t}}, which would show that there
    // is no solution with the component lastvar zero;
    // however, we also have to ensure that if there
    // exists a solution with the component lastvar
    // equal to zero then this component has a
    // valuation with all strictly positive values!!!!;
    // for this we can either saturate the ideal
    // after elimination with respect to <t,x_1,...,x_n>
    // and see if the saturated ideal is contained in <t,x_1,...x_n>+m,
    // or ALTERNATIVELY we can pass to the
    // ring 0,(t,x_1,...,x_n,@a),(ds(n+1),dp(1)),
    // compute a standard basis of the elimination
    // ideal (plus m) there and check if the dimension 1
    // (since we have not omitted the variable lastvar,
    // this means that we have the ideal
    // generated by t,x_1,...,[no x_lastvar],...,x_n
    // and this defines NO curve after omitting x_lastvar)
    I=std(ideal(var(lastvar)+i));
    // first test,
    LI=lead(reduce(I,std(m)));
    //size(deletedvariables)=anzahlvariablen(before elimination)
    for (j=1;j<=anzahlvariablen-1;j++)
    {
      LI=subst(LI,var(j),0);
    }
    if (size(LI)==0) // if no power of t is in lead(I) (where @a is considered as a field element)
*/
    if (size(i)-size(m)!=1)
    {
      I=reduce(sat(std(ideal(var(lastvar)+i)),t)[1],std(m)); // get rid of the minimal
                                                             // polynomial for the test
    }
    else
    {
      I=subst(i,var(lastvar),0);
      while ((I[1]!=0) and (subst(I[1],t,0)==0))
      {
        I[1]=I[1]/t;
      }
      I=reduce(I,std(m));
    }
    LI=subst(I,var(nvars(basering)),0);
    //size(deletedvariables)=anzahlvariablen(before elimination)
    for (j=1;j<=anzahlvariablen-1;j++)
    {
      LI=subst(LI,var(j),0);
    }
    if (size(LI)==0) // the saturation lives in the maximal
    { // ideal generated by t and the x_i
      // get rid of var(lastvar)
      I=eliminate(I,var(lastvar))+m; // add the minimal polynomial again
      // store the information which variable has been eliminated
      intvec newdeletedvariables=deletedvariables;
      newdeletedvariables[lastvar]=1;
      // pass to a new ring whith one variable less
      if (anzahlvariablen>2)
      {
        string elring="ring ELIMINATERING=("+charstr(basering)+"),("+string(simplify(reduce(maxideal(1),std(var(lastvar))),2))+"),(dp("+string(anzahlvariablen-2)+"),";
      }
      else
      {
        string elring="ring ELIMINATERING=("+charstr(basering)+"),("+string(simplify(reduce(maxideal(1),std(var(lastvar))),2))+"),(";
      }
      if (anzahlvariablen<nvars(basering)) // if @a was present, the
      { // ordersting needs an additional entry
        elring=elring+"dp(1),";
      }
      elring=elring+"lp(1));";
      execute(elring);
      ideal i=imap(BASERING,I); // move the ideal I to the new ring
      // if not yet all variables have been checked,
      // then go on with the next smaller variable,
      // else prepare the elimination ring and the neccessary
      // information for return
      if (lastvar>1)
      {
        eliminatelist=eliminatecomponents(i,imap(BASERING,m),anzahlvariablen-1,findall,lastvar-1,newdeletedvariables);
      }
      else
      {
        export(i);
          eliminatelist=list(list(ELIMINATERING,anzahlvariablen-1,newdeletedvariables));
      }
      setring BASERING;
    }
    // next we have to test if there is also a solution
    // which has the variable lastvar non-zero;
    // to do so, we saturate with respect to this variable;
    // since when considered over K{{t}}
    // the ideal is zero dimensional, this really removes
    // all solutions with that component zero;
    // the checking is then done as above
    // ADDENDUM
    // if the ideal i (without m) is generated by a single polynomial
    // then we saturate by successively dividing by the variable
    if (size(i)-size(m)==1)
    {
      while (subst(i[1],var(lastvar),0)==0)
      {
        i[1]=i[1]/var(lastvar);
      }
    }
    else
    {
      i=std(sat(i,var(lastvar))[1]);
    }
    I=reduce(i,std(m)); // "remove" m from i
    // test first, if i still is in the ideal <t,x_1,...,x_n> -- if not, then
    // we know that i has no longer a point in the tropical
    // variety with all components negative
    LI=subst(I,var(nvars(basering)),0);
    for (j=1;j<=anzahlvariablen-1;j++) // set all variables
    { // t,x_1,...,x_n equal to zero
      LI=subst(LI,var(j),0);
    }
    if (size(LI)==0) // the entries of i have no constant part
    {
      // check now, if the leading ideal of i contains an element
      // which only depends on t
      LI=lead(I);
      //size(deletedvariables)=anzahlvariablen(before elimination)
      for (j=1;j<=anzahlvariablen-1;j++)
      {
        LI=subst(LI,var(j),0);
      }
      if (size(LI)==0) // if no power of t is in lead(i)
      { // (where @a is considered as a field element)
        // if not yet all variables have been tested, go on with the
        // next smaller variable
        // else prepare the neccessary information for return
        if (lastvar>1)
        {
          saturatelist=eliminatecomponents(i,m,anzahlvariablen,findall,lastvar-1,deletedvariables);
        }
        else
        {
          execute("ring SATURATERING=("+charstr(basering)+"),("+varstr(basering)+"),("+ordstr(basering)+");");
          ideal i=imap(BASERING,i);
          export(i);
          setring BASERING;
          saturatelist=list(list(SATURATERING,anzahlvariablen,deletedvariables));
        }
      }
    }
    return(eliminatelist+saturatelist);
  }
  else // only one solution is searched for, we can do a simplified
  { // version of the above
    // check if there is a solution which has the n-th component
    // zero and with positive valuation,
    // if so, then eliminate the n-th variable from
    // sat(i+x_n,t), otherwise leave i as it is;
    // then check if the (remaining) ideal has as
    // solution where the n-1st component is zero ...,
    // and procede as before; do the same for the remaining variables;
    // this way we make sure that the remaining ideal has
    // a solution which has no component zero;
    ideal variablen; // will contain the variables which are not eliminated
    for (j=anzahlvariablen-1;j>=1;j--)  // the variable t is the last one !!!
    {
      I=sat(ideal(std(var(j)+i)),t)[1];
      LI=subst(I,var(nvars(basering)),0);
      //size(deletedvariables)=anzahlvariablen-1(before elimination)
      for (k=1;k<=size(deletedvariables);k++)
      {
        LI=subst(LI,var(k),0);
      }
      if (size(LI)==0) // if no power of t is in lead(I)
      { // (where the X(i) are considered as field elements)
        // get rid of var(j)
        i=eliminate(I,var(j));
        deletedvariables[j]=1;
        anzahlvariablen--; // if a variable is eliminated,
                           // then the number of true variables drops
      }
      else
      {
        variablen=variablen+var(j); // non-eliminated true variables are stored
      }
    }
    variablen=invertorder(variablen);
    // store also the additional variable and t,
    // since they for sure have not been eliminated
    for (j=size(deletedvariables)+1;j<=nvars(basering);j++)
    {
      variablen=variablen+var(j);
    }
    // if there are variables left, then pass to a ring which
    // only realises these variables else we are done
    if (anzahlvariablen>1)
    {
      string elring="ring ELIMINATERING=("+charstr(basering)+"),("+string(variablen)+"),(dp("+string(anzahlvariablen-1)+"),";
    }
    else
    {
      string elring="ring ELIMINATERING=("+charstr(basering)+"),("+string(variablen)+"),(";
    }
    if (size(deletedvariables)+1<nvars(basering)) // if @a was present,
    { // the ordersting needs an additional entry
      elring=elring+"dp(1),";
    }
    elring=elring+"lp(1));";
    execute(elring);
    ideal i=imap(BASERING,i);
    ideal m=imap(BASERING,m);
    export(i);
    export(m);
    return(list(list(ELIMINATERING,anzahlvariablen,deletedvariables)));
  }
}

/////////////////////////////////////////////////////////////////////////

static proc findzerosAndBasictransform (ideal i,intvec w,list zerolist,int findall,list #)
"USAGE:  findzerosAndBasictransform(i,w,z,f[,#]); i ideal, w intvec, z list, f int,# an optional list
ASSUME:  i is an ideal in Q[t,x_1,...,x_n,@a] and w=(w_0,...,w_n,0)
         is in the tropical variety of i; @a need not be present;
         the list 'zero' contains the zeros computed in previous recursion steps;
         if 'f' is one then all zeros should be found and returned,
         otherwise only one
RETURN:  list, each entry is a ring corresponding to one conjugacy class of
               zeros of the t-initial ideal inside the torus; each of the rings
               contains the following objects
               ideal i    = the ideal i, where the variable @a (if present) has
                            possibly been transformed according to the new
                            minimal polynomial, and where itself has been
                            submitted to the basic transform of the algorithm
                            given by the jth zero found for the t-initial ideal;
                            note that the new minimal polynomial has already
                            been added
               poly m     = the new minimal polynomial for @a
                            (it is zero if no @a is present)
               list zero  = zero[k+1] is the kth component of a zero
                            the t-initial ideal of i
NOTE:     -  the procedure is called from inside the recursive procedure
             tropicalparametrise;
             if it is called in the first recursion, the list #[1] contains
             the t-initial ideal of i w.r.t. w, otherwise #[1] is an integer,
             one more than the number of true variables x_1,...,x_n
          -  if #[2] is present, then it is an integer which tells whether
             ALL zeros should be found or not"
{
  def BASERING=basering;
  string tvar=string(var(nvars(basering)));
  int j,k,l; // indices
  // store the weighted degrees of the elements of i in an integer vector
  intvec wdegs;
  for (j=1;j<=size(i);j++)
  {
    wdegs[j]=deg(i[j],intvec(w[2..size(w)],w[1]));
  }
  // set anzahlvariablen to the number of true variables
  if (typeof(#[1])=="int")
  {
    int recursive=1; // checks if the procedure has been called recursively
    int anzahlvariablen=#[1];
    // compute the initial ideal of i
    // - the last 1 just means that the variable t is the last
    //   variable in the ring
    ideal ini=tInitialIdeal(i,w,1);
  }
  else
  {
    int recursive=0;
    int anzahlvariablen=nvars(basering);
    ideal ini=#[1]; // the t-initial ideal has been computed
                    // in before and was handed over
  }
  // collect the true variables x_1,...,x_n plus @a, if it is defined in BASERING
  ideal variablen;
  for (j=1;j<=nvars(basering)-1;j++)
  {
    variablen=variablen+var(j);
  }
  // move to a polynomial ring with global monomial ordering
  // - the variable t is superflous,
  // the variable @a is not if it was already present
  execute("ring INITIALRING=("+charstr(basering)+"),("+string(variablen)+"),dp;");
  ideal ini=imap(BASERING,ini);
  // compute the minimal associated primes of the
  // initialideal over the algebraic closure;
  // ordering the maximal ideals shall help to
  // avoid unneccessary field extensions
  list absminass=absPrimdecGTZ(ini);
  def ABSRING=absminass[1]; // the ring in which the minimal
                            // associated primes live
  setring ABSRING;
  list maximalideals=ordermaximalideals(absolute_primes,anzahlvariablen);
  if (findall==0) // only one maximal ideal shall be considered
  {
    maximalideals=list(maximalideals[1]);
  }
  list extensionringlist; // contains the rings which are to be returned
  for (j=1;j<=size(maximalideals);j++)
  {
    // check if for the jth maximal ideal a field extension is necessary;
    // the latter condition says that @a is not in BASERING;
    // if some of the maximal ideals needs a field extension,
    // then everything will live in this ring
    if ((maximalideals[j][1]!=0) and (nvars(BASERING)==anzahlvariablen))
    {
      // define the extension ring which contains
      // the new variable @a, if it is not yet present
      execute("ring EXTENSIONRING=("+charstr(BASERING)+"),("+string(imap(BASERING,variablen))+",@a,"+tvar+"),(dp("+string(anzahlvariablen-1)+"),dp(1),lp(1));");
      // phi maps x_i to x_i, @a to @a (if present in the ring),
      // and the additional variable
      // for the field extension is mapped to @a as well
      // -- note that we only apply phi
      // to the list a, and in this list no @a is present;
      // therefore, it does not matter where this is mapped to
      map phi=ABSRING,imap(BASERING,variablen),@a;
    }
    else // @a was already present in the BASERING or no
    { // field extension is necessary
      execute("ring EXTENSIONRING=("+charstr(BASERING)+"),("+varstr(BASERING)+"),("+ordstr(BASERING)+");");
      // phi maps x_i to x_i, @a to @a (if present in the ring),
      // and the additional variable
      // for the field extension is mapped to @a as well respectively to 0,
      // if no @a is present;
      // note that we only apply phi to the list a and to
      // the replacement rule for
      // the old variable @a, and in this list resp.
      // replacement rule no @a is present;
      // therefore, it does not matter where this is mapped to;
      if (anzahlvariablen<nvars(EXTENSIONRING)) // @a is in EXTENSIONRING
      {
        // additional variable is mapped to @a
        map phi=ABSRING,imap(BASERING,variablen),@a;
      }
      else
      {
        // additional variable is mapped to 0
        map phi=ABSRING,imap(BASERING,variablen),0;
      }
    }
    // map the list maximalideals to the EXTENSIONRING
    list maximalideals=phi(maximalideals);
    poly m=maximalideals[j][1];    // extract m
    list zeroneu=maximalideals[j][2]; // extract the new zero
    poly repl=maximalideals[j][3]; // extract the replacement rule
    // the list zero may very well exist as an EMPTY global list
    // - in this case we have to remove it
    // in order to avoid a redefining warning
    if (defined(zero)!=0)
    {
      if (size(zero)==0)
      {
        kill zero;
      }
    }
    // map i and alist to the new ring
    if (repl==0) // in BASERING no @a was present
    {
      ideal i=imap(BASERING,i);
      if (defined(zerolist)==0) // if zerolist is empty, it does not
      { // depend on BASERING !
        list zero=imap(BASERING,zerolist);
      }
      else
      {
        list zero=zerolist;
      }
    }
    else // in BASERING was @a present
    {
      ideal variablen=imap(BASERING,variablen);
      // map i and zerolist to EXTENSIONRING replacing @a
      // by the replacement rule repl
      map psi=BASERING,variablen[1..size(variablen)-1],repl,var(nvars(basering));
      ideal i=psi(i);
      list zero=psi(zerolist);
      kill psi;
    }
    // add the last vector of zeros to zero
    zero[size(zero)+1]=zeroneu;
    // do now the basic transformation sending x_l -> t^-w_l*(zero_l+x_l)
    for (l=1;l<=anzahlvariablen;l++)
    {
      for (k=1;k<=size(i);k++)
      {
        if (l!=1) // corresponds to  x_(l-1) --  note t is the last variable
        {
          i[k]=subst(i[k],var(l-1),(zeroneu[l]+var(l-1))*t^(-w[l]));
        }
        else // corresponds to t
        {
          i[k]=subst(i[k],var(nvars(basering)),var(nvars(basering))^(-w[l]));
        }
      }
    }
    // we can divide the lth generator of i by t^-wdegs[l]
    for (l=1;l<=ncols(i);l++)
    {
      if (wdegs[l]<0) // if wdegs[l]==0 there is no need to divide,
      { // and we made sure that it is no positive
        i[l]=i[l]/t^(-wdegs[l]);
      }
    }
    // since we want to consider i now in the ring (Q[@a]/m)[t,x_1,...,x_n]
    // we can  reduce i modulo m, so that "constant terms"
    // which are "zero" since they
    // are in m will disappear; simplify(...,2) then really removes them;
    // finally we add the minimal polynomial
    i=simplify(ideal(reduce(i,std(m))+m),2);
    export(i);
    export(m);
    export(zero);
    extensionringlist[j]=EXTENSIONRING;
    kill EXTENSIONRING;
    setring ABSRING;
  }
  return(extensionringlist);
}

/////////////////////////////////////////////////////////////////////////

static proc ordermaximalideals (list minassi,int anzahlvariablen)
"USAGE:      ordermaximalideals(minassi); minassi list
ASSUME:      minassi is a list of maximal ideals (together with the information
             how many conjugates it has), where the first polynomial is the
             minimal polynomial of the last variable in the ring which is
             considered as a parameter
RETURN:      list, the procedure orders the maximal ideals in minassi according
                   to how many new variables are needed (namely none or one) to
                   describe the zeros of the ideal, and accordingly to the
                   degree of the corresponding minimal polynomial
                   l[j][1] = the minimal polynomial for the jth maximal ideal
                   l[j][2] = list, the k+1st entry is the kth coordinate of the
                                   zero described by the maximal ideal in terms
                                   of the last variable
                   l[j][3] = poly, the replacement for the old variable @a
NOTE:        if a maximal ideal contains a variable, it is removed from the list;
             the procedure is called by findzerosAndBasictransform"
{
  int j,k,l;
  int pruefer;       // is set one if a maximal ideal contains a variable
  list minassisort;  // will contain the output
  for (j=1;j<=size(minassi);j++){minassisort[j]=0;} // initialise minassisort
                                                    // to fix its initial length
  list zwischen;     // needed for reordering
  list zero;         // (a_1,...,a_n)=(zero[2],...,zero[n+1]) will be
                     // a common zero of the ideal m
  poly nf;           // normalform of a variable w.r.t. m
  poly minimalpolynomial;  // minimal polynomial for the field extension
  poly parrep;  // the old variable @a possibly has to be replaced by a new one
  // compute for each maximal ideal the number of new variables, which are
  // needed to describe its zeros -- note, a new variable is needed
  // if the first entry of minassi[j][1] is not the last variable
  // store the value a variable reduces to in the list a;
  for (j=size(minassi);j>=1;j--)
  {
    minimalpolynomial=minassi[j][1][1];
    if (minimalpolynomial==var(nvars(basering)))
    {
      minimalpolynomial=0;
    }
    zero[1]=poly(0);         // the first entry in zero and in
                             // neuevariablen corresponds to the variable t,
    minassi[j][1]=std(minassi[j][1]);
    for (k=1;(k<=anzahlvariablen-1) and (pruefer==0);k++)
    {
      // zero_k+1 is the normal form of the kth variable modulo m
      zero[k+1]=reduce(var(k),minassi[j][1]);
      // if a variable reduces to zero, then the maximal
      // ideal contains a variable and we can delete it
      if (zero[k+1]==0)
      {
        pruefer=1;
      }
    }
    // if anzahlvariablen<nvars(basering), then the old ring
    // had already an additional variable;
    // the old parameter @a then has to be replaced by parrep
    if (anzahlvariablen<nvars(basering))
    {
      parrep=reduce(var(anzahlvariablen),minassi[j][1]);
    }
    // if the maximal ideal contains a variable, we simply delete it
    if (pruefer==0)
    {
      minassisort[j]=list(minimalpolynomial,zero,parrep);
    }
    // otherwise we store the information on a, neuevariablen
    // and neuvar together with the ideal
    else
    {
      minassi=delete(minassi,j);
      minassisort=delete(minassisort,j);
      pruefer=0;
    }
  }
  // sort the maximal ideals ascendingly according to the
  // number of new variables needed to
  // express the zero of the maximal ideal
  for (j=2;j<=size(minassi);j++)
  {
    l=j;
    for (k=j-1;k>=1;k--)
    {
      if (deg(minassisort[l][1])<deg(minassisort[k][1]))
      {
        zwischen=minassisort[l];
        minassisort[l]=minassisort[k];
        minassisort[k]=zwischen;
        l=k;
      }
    }
  }
  return(minassisort);
}

////////////////////////////////////////////////////////////////////////////////////
/// Procedures used in tropicalCurve:
/// - verticesTropicalCurve
/// - bunchOfLines
/// - clearintmat
/// - sortintvec
/// - sortintmat
/// - intmatcoldelete
/// - intmatconcat
/// - minInIntvec
/// - positionInList
/// - sortlist
/// - minInList
/// - vergleiche
/// - koeffizienten
////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////

static proc verticesTropicalCurve (def tp,list #)
"USAGE:      verticesTropicalCurve(tp[,#]); tp list, # optional list
ASSUME:      tp is represents an ideal in Z[x,y] representing a tropical
             polynomial (in the form of the output of the procedure tropicalise)
             defining a tropical plane curve
RETURN:      list, each entry corresponds to a vertex in the tropical plane
                   curve defined by tp
                   l[i][1] = x-coordinate of the ith vertex
                   l[i][2] = y-coordinate of the ith vertex
                   l[i][3] = a polynomial whose monimials mark the vertices in
                             the Newton polygon corresponding to the entries in
                             tp which take the common minimum at the ith vertex
NOTE:      - the information in l[i][3] represents the subdivision of the Newton
             polygon of tp (respectively a polynomial which defines tp);
           - if # is non-empty and #[1] is the string 'max', then in the
             computations minimum and maximum are exchanged;
           - if # is non-empty and the #[1] is not a string, only the vertices
             will be computed and the information on the Newton subdivision will
             be omitted;
           - here the tropical polynomial is supposed to be the MINIMUM of the
             linear forms in tp, unless the optional input #[1] is the
             string 'max'
           - the procedure is called from tropicalCurve and from
             conicWithTangents"
{
  // if you insert a single polynomial instead of an ideal representing
  // a tropicalised polynomial,
  // then we compute first the tropicalisation of this polynomial
  // -- this feature is not documented in the above help string
  if (typeof(tp)=="poly")
  {
    poly f=tp;
    kill tp;
    list tp=tropicalise(f,#);
  }
  int i,j,k,l,z; // indices
  // make sure that no constant entry of tp has type int since that
  // would lead to trouble
  // when using the procedure substitute
  for (i=1;i<=size(tp);i++)
  {
    if (typeof(tp[i])=="int")
    {
      tp[i]=poly(tp[i]);
    }
  }
  // introduce necessary variables
  ideal punkt;
  poly px,py;
  poly wert,vergleich;
  poly newton;
  list eckpunkte;
  int e=1;
  option(redSB);
  // for each triple (i,j,k) of entries in tp check if they have a
  // point in common and if they attain at this point the minimal
  // possible value for all linear forms in tp
  for (i=1;i<=size(tp)-2;i++)
  {
    for(j=i+1;j<=size(tp)-1;j++)
    {
      for (k=j+1;k<=size(tp);k++)
      {
        punkt=std(ideal(tp[i]-tp[k],tp[j]-tp[k]));
        if (size(punkt)==2)
        {
          if (leadmonom(punkt[1])==var(1))
          {
            px=(-punkt[1]+lead(punkt[1]))/leadcoef(punkt[1]);
            py=(-punkt[2]+lead(punkt[2]))/leadcoef(punkt[2]);
          }
          else
          {
            py=(-punkt[1]+lead(punkt[1]))/leadcoef(punkt[1]);
            px=(-punkt[2]+lead(punkt[2]))/leadcoef(punkt[2]);
          }
          l=1;
          wert=substitute(tp[i],var(1),px,var(2),py);
          newton=0;
          vergleich=wert;
          while((l<=size(tp)) and (vergleiche(wert,vergleich,#)))
          {
            vergleich=substitute(tp[l],var(1),px,var(2),py);
            if (vergleich==wert)
            {
              newton=newton+detropicalise(tp[l]);
            }
            l++;
          }
          if ((l==size(tp)+1) and (vergleiche(wert,vergleich,#)))
          {
            if (size(#)==0)
            {
              eckpunkte[e]=list(px,py,newton);
            }
            else
            {
              if (typeof(#[1])=="string")
              {
                eckpunkte[e]=list(px,py,newton);
              }
              else
              {
                eckpunkte[e]=list(px,py);
              }
            }
            e++;
          }
        }
      }
    }
  }
  // if a vertex appears several times, only its first occurence will be kept
  for (i=size(eckpunkte);i>=2;i--)
  {
    for (j=i-1;j>=1;j--)
    {
      if ((eckpunkte[i][1]==eckpunkte[j][1]) and (eckpunkte[i][2]==eckpunkte[j][2]))
      {
        eckpunkte=delete(eckpunkte,i);
        j=0;
      }
    }
  }
  return(eckpunkte);
}

/////////////////////////////////////////////////////////////////////////

static proc bunchOfLines (def tp,list #)
"USAGE:      bunchOfLines(tp[,#]); tp list, # optional list
ASSUME:      tp is represents an ideal in Q[x,y] representing a tropical
             polynomial (in the form of the output of the procedure tropicalise)
             defining a bunch of ordinary lines in the plane,
             i.e. the Newton polygone is a line segment
RETURN:      list, see the procedure tropicalCurve for an explanation of
                   the syntax of this list
NOTE:      - the tropical curve defined by tp will consist of a bunch of
             parallel lines and throughout the procedure a list with the
             name bunchoflines is computed, which represents these lines and
             has the following interpretation:
             list, each entry corresponds to a vertex in the tropical plane
                   curve defined by tp
                   l[i][1] = the equation of the ith line in the tropical curve
                   l[i][2] = a polynomial whose monimials mark the vertices in
                             the Newton polygon corresponding to the entries in
                             tp which take the common minimum at the ith vertex
           - the information in l[i][2] represents the subdivision of the Newton
             polygon of tp (respectively a polynomial which defines tp);
           - if # is non-empty and #[1] is the string 'max', then in the
             computations minimum and maximum are exchanged;
           - if # is non-empty and the #[1] is not a string, only the vertices
             will be computed and the information on the Newton subdivision
             will be omitted;
           - here the tropical polynomial is supposed to be the MINIMUM of the
             linear forms in tp, unless the optional input #[1] is the
             string 'max'
           - the procedure is called from tropicalCurve"
{
  // introduce necessary variables
  list oldtp=tp; // save the old entries of tp
  int i,j,k,l;
  ideal punkt;
  poly px;
  poly wert,vergleich;
  poly newton;
  list bunchoflines;
  int e=1;
  option(redSB);
  // find the direction of the line segment in the Newton polygon
  intvec direction=leadexp(detropicalise(tp[1]))-leadexp(detropicalise(tp[2]));
  direction=direction/gcd(direction[1],direction[2]);
  // change the coordinates in such a way, that the Newton polygon
  // lies on the x-axis
  if (direction[1]==0) // there is no x-term - exchange x and y
  { // and get rid of the new y part
    for (i=1;i<=size(tp);i++)
    {
      tp[i]=substitute(tp[i],var(1),0,var(2),var(1));
    }
  }
  else
  {
    for (i=1;i<=size(tp);i++)
    {
      tp[i]=substitute(tp[i],var(2),0);
    }
  }
  // For all tuples (i,j) of entries in tp check if they attain
  // at their point of intersection
  // the minimal possible value for all linear forms in tp
  for (i=1;i<=size(tp)-1;i++)
  {
    for(j=i+1;j<=size(tp);j++)
    {
      punkt=std(ideal(tp[i]-tp[j]));
      px=-leadcoef(punkt[1]-lead(punkt[1]))/leadcoef(punkt[1]);
      l=1;
      wert=substitute(tp[i],var(1),px);
      newton=0;
      vergleich=wert;
      while((l<=size(tp)) and (vergleiche(wert,vergleich,#)))
      {
        vergleich=substitute(tp[l],var(1),px);
        if (vergleich==wert)
        {
          newton=newton+detropicalise(oldtp[l]);
        }
        l++;
      }
      if ((l==size(tp)+1) and (vergleiche(wert,vergleich,#)))
      {
        bunchoflines[e]=list((oldtp[i]-oldtp[j])/leadcoef(oldtp[i]-oldtp[j]),newton);
        e++;
      }
    }
  }
  // if a vertex appears several times, only its first occurence will be kept
  for (i=size(bunchoflines);i>=2;i--)
  {
    for (j=i-1;j>=1;j--)
    {
      if (bunchoflines[i][1]==bunchoflines[j][1])
      {
        bunchoflines=delete(bunchoflines,i);
        j=0;
      }
    }
  }
  // sort the lines in an descending way according to the leading
  // exponent of the polynomial
  // defining the Newton polygone
  list nbol;
  list maximum;
  while (size(bunchoflines)!=0)
  {
    j=1;
    maximum=bunchoflines[1];
    for (i=2;i<=size(bunchoflines);i++)
    {
      if (deg(bunchoflines[i][2])<deg(maximum[2]))
      {
        maximum=bunchoflines[i];
        j=i;
      }
    }
    nbol=nbol+list(maximum);
    bunchoflines=delete(bunchoflines,j);
  }
  bunchoflines=nbol;
  // define the lines by a point on the line and the direction vector
  list graph,gr;
  intmat M[2][1];
  intvec extrema;
  poly xc,yc,cc;
  list NSD;
  NSD[1]=leadexp(bunchoflines[1][2][size(bunchoflines[1][2])]);
  for (i=1;i<=size(bunchoflines);i++)
  {
    NSD[i+1]=leadexp(bunchoflines[i][2]);
    extrema=leadexp(bunchoflines[i][2])-leadexp(bunchoflines[i][2][size(bunchoflines[i][2])]);
    cc=substitute(bunchoflines[i][1],var(2),0,var(1),0);
    xc=substitute(bunchoflines[i][1]-cc,var(2),0,var(1),1);
    yc=substitute(bunchoflines[i][1]-cc,var(2),1,var(1),0);
    if (xc!=0) // then there is a point on the line with y-coordinate zero
    {
      gr[1]=-cc/leadcoef(xc);
      gr[2]=0;
    }
    else // if there is no point with y-coordinate zero, then
    { // there is point with x-coordinate zero
      gr[1]=0;
      gr[2]=-cc/leadcoef(yc);
    }
    gr[3]=M;
    gr[4]=list(list(intvec(direction[2],-direction[1]),gcd(extrema[1],extrema[2])),list(intvec(-direction[2],direction[1]),1));
    gr[5]=bunchoflines[i][2];
    graph[i]=gr;
  }
  graph=graph+list(list(NSD,list(),intvec(0,0)));
  return(graph);
}

/////////////////////////////////////////////////////////////////////////

static proc clearintmat (intmat vv)
"USAGE:      clearintmat(vv); vv intmat
ASSUME:      all entries of the first column of vv are non-negative,
             not all entries are zero unless vv has only one column
RETURN:      intmat, vv has been ordered in an ascending way by the entries
                     of the first row;
                     if an entry in the first row occurs several times, the
                     entries in the second row have been added and only one
                     row has been kept;
                     colums with a zero in the first row have been removed
                     unless vv has only one column
NOTE:        called by tropicalCurve"
{
  vv=sortintmat(vv);
  for (int i=ncols(vv)-1;i>=1;i--)
  {
    if (vv[1,i]==vv[1,i+1])
    {
      vv[2,i]=vv[2,i]+vv[2,i+1];
      vv=intmatcoldelete(vv,i+1);
    }
    if (vv[1,i]==0)
    {
      vv=intmatcoldelete(vv,i);
    }
  }
  return(vv);
}

/////////////////////////////////////////////////////////////////////////

static proc sortintvec (intvec w)
"USAGE:      sortintvec(v); v intvec
RETURN:      intvec, the entries of v are ordered in an ascending way
NOTE:        not called at all"
{
  int j,k,stop;
  intvec v=w[1];
  for (j=2;j<=size(w);j++)
  {
    k=1;
    stop=0;
    while ((k<=size(v)) and (stop==0))
    {
      if (v[k]<w[j])
      {
        k++;
      }
      else
      {
        stop=1;
      }
    }
    if (k==size(v)+1)
    {
      v=v,w[j];
    }
    else
    {
      if (k==1)
      {
        v=w[j],v;
      }
      else
      {
        v=v[1..k-1],w[j],v[k..size(v)];
      }
    }
  }
  return(v);
}

/////////////////////////////////////////////////////////////////////////

static proc sortintmat (intmat vv)
"USAGE:      sortintmat(vv); vv intmat
RETURN:      intmat, the columns of vv have been ordered in an ascending
                     way by the first entry
NOTE:        called by clearintmat"
{
  if(ncols(vv)==1)
  {
    return(vv);
  }
  intvec v=vv[1,1..ncols(vv)];
  list ww=minInIntvec(v);
  intmat M[2][1]=vv[1..2,ww[2]];
  vv=sortintmat(intmatcoldelete(vv,ww[2]));
  return(intmatconcat(M,vv));
}

/////////////////////////////////////////////////////////////////////////

static proc intmatcoldelete (intmat w,int i)
"USAGE:      intmatcoldelete(w,i); w intmat, i int
RETURN:      intmat, the integer matrix w with the ith comlumn deleted
NOTE:        the procedure is called by intmatsort and normalFan"
{
  if ((i<1) or (i>ncols(w)) or (ncols(w)==1))
  {
    return(w);
  }
  if (i==1)
  {
    intmat M[nrows(w)][ncols(w)-1]=w[1..nrows(w),2..ncols(w)];
    return(M);
  }
  if (i==ncols(w))
  {
    intmat M[nrows(w)][ncols(w)-1]=w[1..nrows(w),1..ncols(w)-1];
    return(M);
  }
  else
  {
    intmat M[nrows(w)][i-1]=w[1..nrows(w),1..i-1];
    intmat N[nrows(w)][ncols(w)-i]=w[1..nrows(w),i+1..ncols(w)];
    return(intmatconcat(M,N));
  }
}

/////////////////////////////////////////////////////////////////////////

static proc intmatconcat (intmat M,intmat N)
"USAGE:      intmatconcat(M,N); M,N intmat
RETURN:      intmat, M and N concatenated
NOTE:        the procedure is called by intmatcoldelete and sortintmat"
{
  if (nrows(M)>=nrows(N))
  {
    int m=nrows(M);

  }
  else
  {
    int m=nrows(N);
  }
  intmat P[m][ncols(M)+ncols(N)];
  P[1..nrows(M),1..ncols(M)]=M[1..nrows(M),1..ncols(M)];
  P[1..nrows(N),ncols(M)+1..ncols(M)+ncols(N)]=N[1..nrows(N),1..ncols(N)];
  return(P);
}

/////////////////////////////////////////////////////////////////////////

static proc minInIntvec (intvec v)
"USAGE:      minInIntvec(v); v intvec
RETURN:      list, first entry is the minimal value in v, second entry
                   is its position in v
NOTE:        called by sortintmat"
{
  int min=v[1];
  int minpos=1;
  for (int i=2;i<=size(v);i++)
  {
    if (v[i]<min)
    {
      min=v[i];
      minpos=i;
    }
  }
  return(list(v[minpos],minpos));
}

/////////////////////////////////////////////////////////////////////////

static proc positionInList (list L,intvec v)
"USAGE:      positionInList(L,v); L list, v intvec
RETURN:      int, the position in L in which v occurs first
NOTE:        called by tropicalCurve"
{
  for (int i=1;i<=size(L);i++)
  {
    if (v==L[i])
    {
      return(i);
    }
  }
}

/////////////////////////////////////////////////////////////////////////

static proc sortlist (list v,int pos)
"USAGE:      sortlist(v,pos); v list, pos int
RETURN:      list, the list L ordered in an ascending way according
                   to the pos-th entries
NOTE:        called by tropicalCurve"
{
  if(size(v)==1)
  {
    return(v);
  }
  list w=minInList(v,pos);
  v=delete(v,w[2]);
  v=sortlist(v,pos);
  v=list(w[1])+v;
  return(v);
}

/////////////////////////////////////////////////////////////////////////

static proc minInList (list v,int pos)
"USAGE:      minInList(v,pos); v list, pos int
RETURN:      list, (v[i],i) such that v[i][pos] is minimal
NOTE:        called by sortlist"
{
  int min=v[1][pos];
  int minpos=1;
  for (int i=2;i<=size(v);i++)
  {
    if (v[i][pos]<min)
    {
      min=v[i][pos];
      minpos=i;
    }
  }
  return(list(v[minpos],minpos));
}

/////////////////////////////////////////////////////////////////////////

static proc vergleiche (poly wert,poly vglwert,list #)
"USAGE:      vergleiche(wert,vglwert,liste), wert, vglwert poly, liste list
RETURN:      int, if list contains a string as first entry then 1
                  is returned if wert is at most vglwert and 0 if wert is
                  larger than vglwert, if liste is anything else 1 is returned if
                  wert is at least vglwert and 0 if wert s less than vglwert"
{
  def BASERING=basering;
  ring testring=0,x,lp;
  poly wert=imap(BASERING,wert);
  poly vglwert=imap(BASERING,vglwert);
  int ergebnis;
  if (size(#)==0)
  {
    ergebnis=1-(wert>vglwert);
  }
  if (size(#)>0)
  {
    if (typeof(#[1])=="string")
    {
      ergebnis=1-(wert<vglwert);
    }
    else
    {
      ergebnis=1-(wert>vglwert);
    }
  }
  setring BASERING;
  return(ergebnis);
}

/////////////////////////////////////////////////////////////////////////

static proc koeffizienten (poly f,int k)
"USAGE:      koeffizienten(f,k)  f poly, k int
ASSUME:      f=a*x+b*y+c is a linear polynomial in two variables,
             k is either 0, 1 or 2
RETURN:      poly, one of the coefficients of f, depending on the value of k:
                   k=0 : c is returned
                   k=1 : a is returned
                   k=2 : b is returned
NOTE:        the procedure is called from tropicalCurve"
{
  poly c=substitute(f,var(1),0,var(2),0);
  if (k==0)
  {
    return(c);
  }
  f=f-c;
  if (k==1)
  {
    return(substitute(f,var(1),1,var(2),0));
  }
  else
  {
    return(substitute(f,var(1),0,var(2),1));
  }
}

////////////////////////////////////////////////////////////////////////////
/// Procedures used in tex-procedures and conicWithTangents:
/// - minOfPolys
/// - shorten
/// - minOfStringDecimal
/// - decimal
/// - stringdelete
/// - stringinsert
/// - texmonomial
/// - texcoefficient
/// - abs
/////////////////////////////////////////////////////////////////////////////

static proc minOfPolys (list v)
"USAGE:      minOfPolys(v); v list
RETURN:      poly, the minimum of the numbers in v
NOTE:        called by texDrawTropical"
{
  poly min=v[1];
  for (int i=2;i<=size(v);i++)
  {
    if (v[i]<min)
    {
      min=v[i];
    }
  }
  return(min);
}

/////////////////////////////////////////////////////////////////////////

proc shorten (list AA)
"USAGE:      shorten(AA); AA list
ASSUME:      AA has three entries representing decimal numbers a, b and c
RETURN:      list, containing strings representing the numbers a and b scaled
                   down so that the absolute maximum of the two is no
                   larger than c
NOTE:        the procedure is called by texDrawTropical"
{
  ring REALRING=(real,50,100),x,lp;
  execute("number aa,bb,cc="+AA[1]+","+AA[2]+","+AA[3]+";");
  number ascale,bscale=1,1;
  if ((aa>cc) or (aa<-cc))
  {
    ascale=abs(cc/aa);
  }
  if ((bb>cc) or (bb<-cc))
  {
    bscale=abs(cc/bb);
  }
  if (ascale<bscale)
  {
    aa=aa*ascale;
    bb=bb*ascale;
  }
  else
  {
    aa=aa*bscale;
    bb=bb*bscale;
  }
  return(list(string(aa),string(bb)));
}


/////////////////////////////////////////////////////////////////////////

static proc minOfStringDecimal (string a, string b)
"USAGE:      minOfStringDecimal(a,b); a,b string
ASSUME:      a and b are strings representing decimal numbers
RETURN:      string, the string representing the larger of the two numbers a or b
NOTE:        the procedure is called by texDrawTropical"
{
  ring REALRING=(real,50,100),x,lp;
  execute("poly aa,bb="+a+","+b+";");
  if (aa<bb)
  {
    return(a);
  }
  else
  {
    return(b);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc decimal (poly n,list #)
"USAGE:      decimal(f[,#]); f poly, # list
ASSUME:      f is a polynomial in Q[x_1,...,x_n], and # is either empty
             or #[1] is a positive integer
RETURN:      string, a decimal expansion of the leading coefficient of f up
                     to order two respectively #[1]
NOTE:        the procedure is called by texDrawTropical and conicWithTangents
             and f will actually be a number"
{
  def BASERING=basering;
  execute("ring INTERRING=0,("+varstr(basering)+"),("+ordstr(basering)+");");
  poly n=imap(BASERING,n);
  execute("ring REALRING=(real,50,100),("+varstr(basering)+"),("+ordstr(basering)+");");
  map phi=INTERRING,maxideal(1);
  string s=string(phi(n));
  int check=0;
  int i=1;
  int j;
  string news;
  int nachkomma=2;
  if (size(#)>0)
  {
    nachkomma=#[1];
  }
  while ((check==0) and i<=size(s))
  {
    if (s[i]==".")
    {
      if (i+nachkomma>size(s))
      {
        nachkomma=size(s)-i;
      }
      for (j=i;j<=i+nachkomma;j++)
      {
        news=news+s[j];
      }
      check=1;
    }
    else
    {
      news=news+s[i];
    }
    i++;
  }
  setring BASERING;
  return(news);
}

/////////////////////////////////////////////////////////////////////////

static proc stringcontainment (string a, string b)
"USAGE:      stringcontainment(a,b); a,b string
ASSUME:      a is a string containing a single letter
RETURN:      int, one if a is one of the letters in b and zero else
NOTE:        the procedure is called from extremeraysC"
{
  int i;
  for (i=1;i<=size(b);i++)
  {
    if (a==b[i])
    {
      return(1);
    }
  }
  return(0);
}

/////////////////////////////////////////////////////////////////////////

static proc stringdelete (string w,int i)
"USAGE:      stringdelete(w,i); w string, i int
RETURN:      string, the string w with the ith component deleted
NOTE:        the procedure is called by texNumber and choosegfanvector"
{
  if ((i>size(w)) or (i<=0))
  {
    return(w);
  }
  if ((size(w)==1) and (i==1))
  {
    return("");

  }
  if (i==1)
  {
    return(w[2..size(w)]);
  }
  if (i==size(w))
  {
    return(w[1..size(w)-1]);
  }
  else
  {
    string erg=w[1..i-1],w[i+1..size(w)];
    return(erg);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc stringinsert (string w,string v,int i)
"USAGE:      stringinsert(w,v,i); w string, v string, i int
RETURN:      string, the string w where at the ith component v has been inserted
NOTE:        the procedure is called by texmonomial"
{
  if (i==1)
  {
    return(v[1]+w);
  }
  if (i==size(w)+1)
  {
    return(w+v[1]);
  }
  else
  {
    string anfang=w[1..i-1];
    string ende=w[i..size(w)];
    string erg=anfang+v+ende;
    return(erg);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc texmonomial (poly f)
"USAGE:      texmonomial(f); f poly
RETURN:      string, the tex-command for the leading monomial of f
NOTE:        the procedure is called by texPolynomial and texNumber"
{
  int altshort=short;
  short=0;
  string F=string(leadmonom(f));
  int k;
  for (int j=1;j<=size(F);j++)
  {
    if (F[j]=="^")
    {
      F=stringinsert(F,"{",j+1);
      k=j+2;
      while (k<=size(F) and ((F[k]=="0") or (F[k]=="1") or (F[k]=="2") or (F[k]=="3") or
                                (F[k]=="4") or (F[k]=="5") or (F[k]=="6") or (F[k]=="7") or (F[k]=="8")
                             or (F[k]=="9")))
      {
        k++;
      }
      F=stringinsert(F,"}",k);
      j=k+1;
    }
    if (F[j]=="(")
    {
      F=stringdelete(F,j);
      F=stringinsert(F,"_{",j);
      k=j+2;
      while (k<=size(F) and ((F[k]=="0") or (F[k]=="1") or (F[k]=="2") or (F[k]=="3") or
                                (F[k]=="4") or (F[k]=="5") or (F[k]=="6") or (F[k]=="7") or (F[k]=="8")
                             or (F[k]=="9")))
      {
        k++;
      }
      F=stringdelete(F,k);
      F=stringinsert(F,"}",k);
      j=k;
    }
    if (F[j]=="*")
    {
      F=stringdelete(F,j);
      j--;
    }
  }
  short=altshort;
  return(F);
}

/////////////////////////////////////////////////////////////////////////

static proc texcoefficient (poly f,list #)
"USAGE:      texcoefficient(f[,#]); f poly, # optional list
RETURN:      string, the tex command representing the leading coefficient
                     of f using \frac as coefficient
NOTE:        if # is non-empty, then the cdot at the end is omitted;
             this is needed for the constant term"
{
  string cdot;
  if (size(#)==0)
  {
    cdot="\\cdot ";
  }
  string koeffizient=texNumber(f);
  if (koeffizient=="1")
  {
    if (size(#)==0)
    {
      return("");
    }
    else
    {
      return(koeffizient);
    }
  }
  if (koeffizient=="-1")
  {
    if (size(#)==0)
    {
      return("-");
    }
    else
    {
      return(koeffizient);
    }
  }
  if (size(koeffizient)>5)
  {
    string tfractest=koeffizient[2..6];
    if (tfractest=="tfrac")
    {
      return(koeffizient+cdot);
    }
  }
  int anzahlplus,anzahlminus;
  for(int j=1;j<=size(koeffizient);j++)
  {
    if (koeffizient[j]=="+")
    {
      anzahlplus++;
    }
    if (koeffizient[j]=="-")
    {
      anzahlminus++;
    }
  }
  if ((anzahlplus==0) and (anzahlminus==1) and (koeffizient[1]=="-"))
  {
    return(koeffizient+cdot);
  }
  else
  {
    if (anzahlplus+anzahlminus>=1)
    {
      return("("+koeffizient+")"+cdot);
    }
    else
    {
      return(koeffizient+cdot);
    }
  }
}

/////////////////////////////////////////////////////////////////////////

static proc abs (def n)
"USAGE:      abs(n); n poly or int
RETURN:      poly or int, the absolute value of n"
{
  if (n>=0)
  {
    return(n);
  }
  else
  {
    return(-n);
  }
}

///////////////////////////////////////////////////////////////////////////////
/// Procedures only used to compute j-invariants
/// - findNonLoopVertex
/// - coordinatechange
/// - weierstrassFormOfACubic
/// - weierstrassFormOfA4x2Curve
/// - weierstrassFormOfA2x2Curve
/// - jInvariantOfACubic
/// - jInvariantOfA4x2Curve
/// - jInvariantOfA2x2Curve
/// - jInvariantOfAPuiseuxCubic
///////////////////////////////////////////////////////////////////////////////

static proc findNonLoopVertex (list graph)
"USAGE:      findNonLoopVertex(graph); graph list
ASSUME:      graph is a list as in the output of tropicalCurve
RETURN:      int, the number of a vertex which has only one edge
NOTE:        the procedure is called by tropicalJInvariant"
{
  int i,j;
  for (i=1;i<=size(graph)-1;i++)
  {
    if ((ncols(graph[i][3])==1) and (graph[i][3][1,1]!=0))
    {
      return(i);
    }
  }
  return(-1);
}


/////////////////////////////////////////////////////////////////////////

static proc coordinatechange (poly f,intmat A,intvec v)
"USAGE:   coordinatechange(f,A,v);  f poly, A intmat, v intvec
ASSUME:   f is a polynomial in two variables, A is a 2x2
          integer matrix, and v is an integer vector with 2 entries
RETURN:   poly, the polynomial transformed by (x,y)->A*(x,y)+v
NOTE:     the procedure is called by weierstrassForm"
{
  poly g;
  int i;
  intmat exp[2][1];
  for (i=1;i<=size(f);i++)
  {
    exp=leadexp(f[i]);
    exp=A*exp;
    g=g+leadcoef(f[i])*var(1)^(exp[1,1]+v[1])*var(2)^(exp[2,1]+v[2]);
  }
  return(g);
}

/////////////////////////////////////////////////////////////////////////

static proc weierstrassFormOfACubic (poly f,list #)
"USAGE:      weierstrassFormOfACubic(wf[,#]); wf poly, # list
ASSUME:      poly is a cubic polynomial
RETURN:      poly, the Weierstrass normal form of the cubic, 0 if poly is
                   not a cubic
NOTE:        - the algorithm for the coefficients of the Weierstrass form is due
               to Fernando Rodriguez Villegas, villegas@math.utexas.edu
             - if an additional argument # is given, the simplified Weierstrass
               form is computed
             - the procedure is called by weierstrassForm
             - the characteristic of the base field should not be 2 or 3
               if # is non-empty"
{
  if (deg(f)!=3)
  {
    ERROR("The curve is not a cubic!");
  }
  // store the coefficients of f in a specific order
  poly t0,s1,s0,r2,r1,r0,q3,q2,q1,q0=flatten(coeffs(f,ideal(var(2)^3,var(2)^2,var(2)^2*var(1),var(2),var(2)*var(1),var(2)*var(1)^2,1,var(1),var(1)^2,var(1)^3)));
  // test, if f is already in Weierstrass form
  if ((t0==0) and (s1==1) and (s0==0) and (r0==0) and (q0==-1) and (size(#)==0))
  {
    return (f);
  }
  // compute the coefficients a1,a2,a3,a4, and a6 of the Weierstrass
  // form y^2+a1xy+a3y=x^3+a2x^2+a4x+a6
  poly a1=r1;
  poly a2=-(s0*q2+s1*q1+r0*r2);
  poly a3=(9*t0*q0-s0*r0)*q3+((-t0*q1-s1*r0)*q2+(-s0*r2*q1-s1*r2*q0));
  poly a4=((-3*t0*r0+s0^2)*q1+(-3*s1*s0*q0+s1*r0^2))*q3
    +(t0*r0*q2^2+(s1*s0*q1+((-3*t0*r2+s1^2)*q0+s0*r0*r2))*q2
      +(t0*r2*q1^2+s1*r0*r2*q1+s0*r2^2*q0));
  poly a6=(-27*t0^2*q0^2+(9*t0*s0*r0-s0^3)*q0-t0*r0^3)*q3^2+
        (((9*t0^2*q0-t0*s0*r0)*q1+((-3*t0*s0*r1+(3*t0*s1*r0+
        2*s1*s0^2))*q0+(t0*r0^2*r1-s1*s0*r0^2)))*q2+(-t0^2*q1^3
        +(t0*s0*r1+(2*t0*s1*r0-s1*s0^2))*q1^2+((3*t0*s0*r2+
        (-3*t0*s1*r1+2*s1^2*s0))*q0+((2*t0*r0^2-s0^2*r0)*r2+
        (-t0*r0*r1^2+s1*s0*r0*r1-s1^2*r0^2)))*q1+((9*t0*s1*r2-
        s1^3)*q0^2+(((-3*t0*r0+s0^2)*r1-s1*s0*r0)*r2+(t0*r1^3
        -s1*s0*r1^2+s1^2*r0*r1))*q0)))*q3+(-t0^2*q0*q2^3+
        (-t0*s1*r0*q1+((2*t0*s0*r2+(t0*s1*r1-s1^2*s0))*q0-
        t0*r0^2*r2))*q2^2+(-t0*s0*r2*q1^2+(-t0*s1*r2*q0+
        (t0*r0*r1-s1*s0*r0)*r2)*q1+((2*t0*r0-s0^2)*r2^2+
        (-t0*r1^2+s1*s0*r1-s1^2*r0)*r2)*q0)*q2+
        (-t0*r0*r2^2*q1^2+(t0*r1-s1*s0)*r2^2*q0*q1-
     t0*r2^3*q0^2));
  poly b2=a1^2+4*a2;
  poly b4=2*a4+a1*a3;
  poly b6=a3^2+4*a6;
  poly b8=a1^2*a6+4*a2*a6-a1*a3*a4+a2*a3^2-a4^2;
  poly c4=b2^2-24*b4;
  poly c6=-b2^3+36*b2*b4-216*b6;
  if (size(#)!=0)
  {
    return(substitute(var(2)^2+a1*var(1)*var(2)+a3*var(2)-var(1)^3-a2*var(1)^2-a4*var(1)-a6,var(2),var(2)-(a1*var(1)+a3)/2));
  }
  else
  {
    return(var(2)^2+a1*var(1)*var(2)+a3*var(2)-var(1)^3-a2*var(1)^2-a4*var(1)-a6);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc weierstrassFormOfA4x2Curve (poly f)
"USAGE:      weierstrassFormOfA4x2Curve(wf); wf poly
ASSUME:      poly is a polynomial of type 4x2
RETURN:      poly, the Weierstrass normal form of the curve
NOTE:        - the procedure is called by weierstrassForm
             - the characteristic of the base field should not be 2 or 3"
{
  poly u11,u40,u30,u20,u10,u00,u21,u01,u02=flatten(coeffs(f,ideal(var(1)*var(2),var(1)^4,var(1)^3,var(1)^2,var(1),1,var(1)^2*var(2),var(2),var(2)^2)));
  poly c4=(u11^4 - 8*u11^2*u20*u02 - 8*u11^2*u01*u21 + 24*u11*u10*u21*u02 + 24*u11*u30*u01*u02 +
           192*u00*u40*u02^2 - 48*u00*u21^2*u02 - 48*u10*u30*u02^2 + 16*u20^2*u02^2 -
           16*u20*u01*u21*u02 - 48*u40*u01^2*u02 + 16*u01^2*u21^2)/lead(u02^4);
  poly c6=(-u11^6 + 12*u11^4*u20*u02 + 12*u11^4*u01*u21 - 36*u11^3*u10*u21*u02 - 36*u11^3*u30*u01*u02 +
           576*u11^2*u00*u40*u02^2 + 72*u11^2*u00*u21^2*u02 + 72*u11^2*u10*u30*u02^2 -
           48*u11^2*u20^2*u02^2 - 24*u11^2*u20*u01*u21*u02 + 72*u11^2*u40*u01^2*u02 -
           48*u11^2*u01^2*u21^2 - 864*u11*u00*u30*u21*u02^2 + 144*u11*u10*u20*u21*u02^2 -
           864*u11*u10*u40*u01*u02^2 + 144*u11*u10*u01*u21^2*u02 + 144*u11*u20*u30*u01*u02^2 +
           144*u11*u30*u01^2*u21*u02 - 2304*u00*u20*u40*u02^3 + 576*u00*u20*u21^2*u02^2 +
           864*u00*u30^2*u02^3 + 1152*u00*u40*u01*u21*u02^2 - 288*u00*u01*u21^3*u02 +
           864*u10^2*u40*u02^3 - 216*u10^2*u21^2*u02^2 - 288*u10*u20*u30*u02^3 +
           144*u10*u30*u01*u21*u02^2 + 64*u20^3*u02^3 - 96*u20^2*u01*u21*u02^2 +
           576*u20*u40*u01^2*u02^2 - 96*u20*u01^2*u21^2*u02 - 216*u30^2*u01^2*u02^2 -
           288*u40*u01^3*u21*u02 + 64*u01^3*u21^3)/lead(u02^6);
  return(var(2)^2-var(1)^3+27*c4*var(1)+54*c6);
}

/////////////////////////////////////////////////////////////////////////

static proc weierstrassFormOfA2x2Curve (poly f)
"USAGE: weierstrassFormOfA2x2Curve(f); f poly
ASSUME: poly, is a polynomial defining an elliptic curve of type (2,2) on P^1xP^1
        i.e. a polynomial of the form a+bx+cx2+dy+exy+fx2y+gy2+hxy2+ix2y2
RETURN: poly, a Weierstrass form of the elliptic curve defined by poly
NOTE:   - the algorithm is based on the paper Sang Yook An, Seog Young Kim,
          David C. Marshall, Susan H. Marshall, William G. McCallum and
          Alexander R. Perlis: Jacobians of Genus One Curves. Journal of Number
          Theory 90,2 (2001), 304-315.
        - the procedure is called by weierstrassForm
        - the characteristic of the base field should not be 2 or 3"
{
  // get the coefficients of the polynomial
  poly A00,A10,A20,A01,A11,A21,A02,A12,A22=flatten(coeffs(f,ideal(1,var(1),var(1)^2,var(2),var(1)*var(2),var(1)^2*var(2),var(2)^2,var(1)*var(2)^2,var(1)^2*var(2)^2)));
  // define P1xP1 as quadric in P3
  matrix A[4][4]=0,0,0,1/2,0,0,1/2,0,0,1/2,0,0,1/2,0,0,0;
  // define the image of the (2,2)-curve under the Segre embedding
  // as quadric which should be
  // intersected with the image of P1xP1
  matrix B[4][4]=A00,A10/2,A01/2,0,A10/2,A20,A11/2,A21/2,A01/2,A11/2,A02,A12/2,0,A21/2,A12/2,A22;
  // compute the coefficients of the Weierstrass form of
  // the input polynomial and its j-invariant
  poly a=det(x*A+B);
  poly a0,a1,a2,a3,a4=flatten(coeffs(a,ideal(x4,x3,x2,x,1)));
  a1,a2,a3=-a1/4,a2/6,-a3/4;
  poly g2=a0*a4-4*a1*a3+3*a2^2;
  poly g3=a0*a2*a4+2*a1*a2*a3-a0*a3^2-a4*a1^2-a2^3;
  return(var(2)^2-var(1)^3+g2/4*var(1)+g3/4);
}

/////////////////////////////////////////////////////////////////////////

static proc jInvariantOfACubic (poly f,list #)
"USAGE:      jInvariantOfACubic(f[,#]); f poly, # list
ASSUME:      poly is a cubic polynomial defining an elliptic curve
RETURN:      poly, the j-invariant of the elliptic curve defined by poly
NOTE:        - if the base field is Q(t) an optional argument # may be given;
               then the algorithm only computes the negative of the order
               of the j-invariant"
{
  if (deg(f)!=3)
  {
    ERROR("The input polynomial is not a cubic!");
  }
  // compute first the Weierstrass form of the cubic
  // - this does not change the j-invariant
  f=weierstrassFormOfACubic(f);
  // compute the coefficients of the Weierstrass form
  poly a1,a2,a3,a4,a6=flatten(coeffs(f,ideal(var(1)*var(2),var(1)^2,var(2),var(1),1)));
  a2,a4,a6=-a2,-a4,-a6;
  // compute the j-invariant
  poly b2=a1^2+4*a2;
  poly b4=2*a4+a1*a3;
  poly b6=a3^2+4*a6;
  poly b8=a1^2*a6+4*a2*a6-a1*a3*a4+a2*a3^2-a4^2;
  poly c4=b2^2-24*b4;
  //  poly c6=-b2^3+36*b2*b4-216*b6;
  poly delta=-b2^2*b8-8*b4^3-27*b6^2+9*b2*b4*b6;
  if (delta==0)
  {
    ERROR("The input is a rational curve and has no j-invariant!");
  }
  if (size(#)>0) // if the optional argument is given, then only the
  { // negative of the order is computed
    int zaehler=3*simplifyToOrder(c4)[1];
    int nenner=simplifyToOrder(delta)[1];
    return(nenner-zaehler);
  }
  else
  {
    poly invariant=(c4^3/delta);
    return(invariant);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc jInvariantOfA2x2Curve (poly f,list #)
"USAGE: jInvariantOfA2x2Curve(f[,#]); f poly, # list
ASSUME: poly, is a polynomial defining an elliptic curve of type (2,2) on P^1xP^1
             i.e. a polynomial of the form a+bx+cx2+dy+exy+fx2y+gy2+hxy2+ix2y2
RETURN: poly, the j-invariant of the elliptic curve defined by poly
NOTE:   - if the base field is Q(t) an optional argument # may be given;
          then the algorithm only computes the negative of the order of the
          j-invariant
        - the characteristic should not be 2 or 3
        - the procedure is not called at all, it is just stored for the purpose
          of comparison"
{
  // get the coefficients of the polynomial
  poly A00,A10,A20,A01,A11,A21,A02,A12,A22=flatten(coeffs(f,ideal(1,var(1),var(1)^2,var(2),var(1)*var(2),var(1)^2*var(2),var(2)^2,var(1)*var(2)^2,var(1)^2*var(2)^2)));
  // define P1xP1 as quadric in P3
  matrix A[4][4]=0,0,0,1/2,0,0,1/2,0,0,1/2,0,0,1/2,0,0,0;
  // define the image of the (2,2)-curve under the Segre embedding as quadric which should be
  // intersected with the image of P1xP1
  matrix B[4][4]=A00,A10/2,A01/2,0,A10/2,A20,A11/2,A21/2,A01/2,A11/2,A02,A12/2,0,A21/2,A12/2,A22;
  // compute the coefficients of the Weierstrass form of
  // the input polynomial and its j-invariant
  poly a=det(var(1)*A+B);
  poly a0,a1,a2,a3,a4=flatten(coeffs(a,ideal(var(1)^4,var(1)^3,var(1)^2,var(1),1)));
  a1,a2,a3=-a1/4,a2/6,-a3/4;
  poly g2=a0*a4-4*a1*a3+3*a2^2;
  poly g3=a0*a2*a4+2*a1*a2*a3-a0*a3^2-a4*a1^2-a2^3;
  poly G2cube=g2^3;
  poly G3square=g3^2;
  poly jinvnum=1728*G2cube;
  poly jinvdenom=-27*G3square+G2cube;
  // check if the curve is rational
  if (jinvdenom==0)
  {
    ERROR("The input is a rational curve and has no j-invariant!");
  }
  if (size(#)>0) // if the optional argument is given,
  { // then only the negative of the order is computed
    int zaehler=simplifyToOrder(jinvnum)[1];
    int nenner=simplifyToOrder(jinvdenom)[1];
    return(nenner-zaehler);
  }
  else
  {
    poly invariant=(jinvnum/jinvdenom);
    return(invariant);
  }
}

/////////////////////////////////////////////////////////////////////////

static proc jInvariantOfA4x2Curve (poly f,list #)
"USAGE:      jInvariantOfA4x2Curve(f[,#]); f poly, # list
ASSUME:      poly, is a polynomial defining an elliptic curve of type (4,2),
             i.e. a polynomial of the form a+bx+cx2+dx3+ex4+fy+gxy+hx2y+iy2
RETURN:      poly, the j-invariant of the elliptic curve defined by poly
NOTE:        - if the base field is Q(t) an optional argument # may be given;
               then the algorithm only computes the negative of the order
               of the j-invariant
             - the characteristic should not be 2 or 3
             - the procedure is not called at all, it is just stored
               for the purpose of comparison"
{
  poly u11,u40,u30,u20,u10,u00,u21,u01,u02=flatten(coeffs(f,ideal(var(1)*var(2),var(1)^4,var(1)^3,var(1)^2,var(1),1,var(1)^2*var(2),var(2),var(2)^2)));
  poly c4=(u11^4 - 8*u11^2*u20*u02 - 8*u11^2*u01*u21 + 24*u11*u10*u21*u02 + 24*u11*u30*u01*u02 +
           192*u00*u40*u02^2 - 48*u00*u21^2*u02 - 48*u10*u30*u02^2 + 16*u20^2*u02^2 -
           16*u20*u01*u21*u02 - 48*u40*u01^2*u02 + 16*u01^2*u21^2);
  poly c6=(-u11^6 + 12*u11^4*u20*u02 + 12*u11^4*u01*u21 - 36*u11^3*u10*u21*u02 - 36*u11^3*u30*u01*u02 +
           576*u11^2*u00*u40*u02^2 + 72*u11^2*u00*u21^2*u02 + 72*u11^2*u10*u30*u02^2 -
           48*u11^2*u20^2*u02^2 - 24*u11^2*u20*u01*u21*u02 + 72*u11^2*u40*u01^2*u02 -
           48*u11^2*u01^2*u21^2 - 864*u11*u00*u30*u21*u02^2 + 144*u11*u10*u20*u21*u02^2 -
           864*u11*u10*u40*u01*u02^2 + 144*u11*u10*u01*u21^2*u02 + 144*u11*u20*u30*u01*u02^2 +
           144*u11*u30*u01^2*u21*u02 - 2304*u00*u20*u40*u02^3 + 576*u00*u20*u21^2*u02^2 +
           864*u00*u30^2*u02^3 + 1152*u00*u40*u01*u21*u02^2 - 288*u00*u01*u21^3*u02 +
           864*u10^2*u40*u02^3 - 216*u10^2*u21^2*u02^2 - 288*u10*u20*u30*u02^3 +
           144*u10*u30*u01*u21*u02^2 + 64*u20^3*u02^3 - 96*u20^2*u01*u21*u02^2 +
           576*u20*u40*u01^2*u02^2 - 96*u20*u01^2*u21^2*u02 - 216*u30^2*u01^2*u02^2 -
           288*u40*u01^3*u21*u02 + 64*u01^3*u21^3);
  poly c4cube=c4^3;
  poly jdenom=c4cube-c6^2;
  if (size(#)>0) // if the optional argument is given,
  { // then only the negative of the order is computed
    int zaehler=3*simplifyToOrder(c4)[1];
    int nenner=simplifyToOrder(jinvdenom)[1];
    return(nenner-zaehler);
  }
  else
  {
    return(1728*(c4cube/(jdenom)));
  }
}

/////////////////////////////////////////////////////////////////////////

static proc jInvariantOfAPuiseuxCubic (poly f,list #)
"USAGE:  jInvariantOfAPuiseuxCubic(f[,#]); f poly, # list
ASSUME:  poly is a cubic polynomial over Q(t) defining an elliptic curve
         and # is empty
RETURN:  list, containing two polynomials whose ratio is the j-invariant
               of the  elliptic curve defined by poly
ASSUME:  poly is a cubic polynomial over Q(t) defining an elliptic curve
         and # is non-empty
RETURN:  int, the order of the j-invariant of the elliptic curve defined by poly
NOTE:    the procedure is called by jInvariant"
{
  if (deg(f)!=3)
  {
    ERROR("The input polynomial is not a cubic!");
  }
  // compute first the Weierstrass form of the cubic
  // - this does not change the j-invariant
  f=weierstrassFormOfACubic(f);
  // compute the coefficients of the Weierstrass form
  poly a1,a2,a3,a4,a6=flatten(coeffs(f,ideal(var(1)*var(2),var(1)^2,var(2),var(1),1)));
  a2,a4,a6=-a2,-a4,-a6;
  number dna1,dna2,dna3,dna4,dna6=denominator(leadcoef(a1)),denominator(leadcoef(a2)),denominator(leadcoef(a3)),denominator(leadcoef(a4)),denominator(leadcoef(a6));
  number na1,na2,na3,na4,na6=numerator(leadcoef(a1)),numerator(leadcoef(a2)),numerator(leadcoef(a3)),numerator(leadcoef(a4)),numerator(leadcoef(a6));
  number hn=dna1*dna2*dna3*dna4*dna6;
  a1=na1*dna2*dna3*dna4*dna6;
  a2=dna1*na2*dna3*dna4*dna6;
  a3=dna1*dna2*na3*dna4*dna6;
  a4=dna1*dna2*dna3*na4*dna6;
  a6=dna1*dna2*dna3*dna4*na6;
  // compute the j-invariant
  poly b2=a1^2+4*a2*hn;
  poly b4=2*a4*hn+a1*a3;
  poly b6=a3^2+4*a6*hn;
  poly b8=a1^2*a6+4*a2*a6*hn-a1*a3*a4+a2*a3^2-a4^2*hn;
  poly c4=b2^2-24*b4*hn^2;
  poly delta=-b2^2*b8-8*b4^3*hn-27*b6^2*hn^3+9*b2*b4*b6*hn;
  if (delta==0)
  {
    ERROR("The input is a rational curve and has no j-invariant!");
  }
  if (size(#)>0) // if the optional argument is given,
  { // then only the negative of the order is computed
    int zaehler=3*simplifyToOrder(c4)[1];
    int nenner=simplifyToOrder(delta)[1];
    int ordhn=simplifyToOrder(hn)[1];
    return(zaehler-nenner-5*ordhn);
  }
  else
  {
    def BASERING=basering;
    execute("ring TRING="+string(char(BASERING))+",t,ds;");
    poly hn=imap(BASERING,hn);
    poly c4=imap(BASERING,c4);
    poly delta=imap(BASERING,delta);
    poly num=c4^3;
    poly denom=delta*hn^5;
    poly ggt=gcd(num,denom);
    num=num div ggt;
    denom=denom div ggt;
    setring BASERING;
    poly num=imap(TRING,num);
    poly denom=imap(TRING,denom);
    number teiler=1;
    if (char(BASERING)==0)
    {
      teiler=gcd(leadcoef(num),leadcoef(denom));
    }
    num=num/teiler;
    denom=denom/teiler;
    list invariant=num,denom;
    return(invariant);
  }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////
/// Further examples for testing the procedures
/////////////////////////////////////////////////////////////////////////////
/*

/// Note, only the following procedures need further examples
/// (the others are too simple):
/// A) tropicalLifting (best tested via displayTropicalLifting)
/// B) tropicalCurve   (best tested via drawTropicalCurve)
/// C) tropicalJInvariant
/// D) weierstrassForm
/// E) jInvariant

////////////////////////////////////////////////////////////////////////////
/// A) Examples tropicalLifting
////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------
// Example 1
// -------------------------------------------------------
ring r0=0,(t,x),dp;
poly f=t7-6t4+3t3x+8t3-12t2x+6tx2-x3+t2;
f;
// The point -2/3 is in the tropical variety.
list L=tropicalLifting(f,intvec(3,-2),4);
L;
displayTropicalLifting(L,"subst");
// --------------------------------------------------------
// Example 2 - a field extension is necessary
// --------------------------------------------------------
poly g=(1+t2)*x2+t5x+t2;
g;
// The poin -1 is in the tropical variety.
displayTropicalLifting(tropicalLifting(g,intvec(1,-1),4),"subst");
// --------------------------------------------------------
// Example 3 - the ideal is not zero dimensional
// --------------------------------------------------------
ring r1=0,(t,x,y),dp;
poly f=(9t27-12t26-5t25+21t24+35t23-51t22-40t21+87t20+56t19-94t18-62t17+92t16+56t15-70t14-42t13+38t12+28t11+18t10-50t9-48t8+40t7+36t6-16t5-12t4+4t2)*x2+(-9t24+12t23-4t22-42t20+28t19+30t18-20t17-54t16+16t15+48t14-16t12+8t11-18t10-26t9+30t8+20t7-24t6+4t5+28t4-8t3-16t2+4)*xy+(6t16-10t15-2t14+16t13+4t12-18t11-10t10+24t9+6t8-20t7+8t6+8t5-20t4-4t3+12t2+4t-4)*y2+(-9t28+3t27+8t26-4t25-45t24-6t23+42t22+30t21-94t20-40t19+68t18+82t17-38t16-60t15+26t14+36t13-22t12-20t11+4t10+4t9+12t8+8t7-8t6-8t5+4t4)*x+(9t27-21t26+16t25+14t24+12t23-61t22+27t21+80t20-19t19-100t18+26t17+96t16-24t15-84t14+44t12-2t11-18t10+2t9+40t8+4t7-32t6-12t5+4t3+12t2-4)*y+(9t27-12t26+4t25+36t23-18t22-28t21-2t20+54t19+14t18-52t17-44t16+24t15+40t14-4t13-12t12+4t11-4t10-4t9+4t8);
f;
displayTropicalLifting(tropicalLifting(f,intvec(1,-1,-4),3),"subst");
// --------------------------------------------------------
// Example 4 - the ideal has even more equations
// --------------------------------------------------------
ring r2=0,(t,x,y,z),dp;
ideal i=t-x3+3yz,t2xy-2x2z;
i;
displayTropicalLifting(tropicalLifting(i,intvec(1,1,3,0),2),"subst");
// --------------------------------------------------------
// Example 5-7 - testing some options
// --------------------------------------------------------
setring r0;
poly f1=(x2-t3)*(x3-t5)*(x5-t7)*(x7-t11)*(x11-t13);
f1;
displayTropicalLifting(tropicalLifting(f1,intvec(7,-11),4,"noAbs"),"subst");
poly f2=(1+t2)*x2+t5x+t2;
f2;
displayTropicalLifting(tropicalLifting(f2,intvec(1,-1),4,"isZeroDimensional","findAll"),"subst");
poly f3=t7-6t4+3t3x+8t3-12t2x+6tx2-x3+t2;
f3;
displayTropicalLifting(tropicalLifting(f3,intvec(3,-2),4,"isInTrop","findAll"),"subst");
// ---------------------------------------------------------
// Even more examples
// ---------------------------------------------------------
ring r1=0,(t,x),dp;
poly f1=(x2-t3)*(x3-t5)*(x5-t7)*(x7-t11)*(x11-t13);
displayTropicalLifting(tropicalLifting(f1,intvec(7,-11),4,"noAbs"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (7,-11)
///////////////////////////////////////////////////////////////////
// one field extension needed
// x=(X(1))*t+(-1/2*X(1))*t^3+(3/8*X(1)-1/2)*t^5+(-5/16*X(1)+1/2)*t^7+(19/128*X(1)-1/2)*t^9+(-15/256*X(1)+1/2)*t^11+(-9/1024*X(1)-1/2)*t^13 where t->t and X(1)^2+1=0
poly f2=(1+t2)*x2+t5x+t2;
displayTropicalLifting(tropicalLifting(f2,intvec(1,-1),4,"isZeroDimensional","findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-1)
///////////////////////////////////////////////////////////////////
// x=t2+2t3+t7   the result is exact
poly f3=t7-6t4+3t3x+8t3-12t2x+6tx2-x3+t2;
displayTropicalLifting(tropicalLifting(f3,intvec(3,-2),4,"isInTrop","findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (3,-2)
///////////////////////////////////////////////////////////////////
//  full parametrisation is given by t->t2+t3 and x=3t7+t9+4t11-t12, this however cannot be computed
// so: t->t2 and x=-3t7-21/2t8-239/8t9-78t10-25589/128t11-506t12-1298967/1024t13-3159t14-256667105/32768t15-19371t16-12540259065/262144t17-118066t18-1222177873545/4194304t19-719423t20-59637294735495/33554432t21
poly f4=t12-83t11-88t10-69t9+3t8x+153t8+298t7x-81t7+165t6x-402t5x+3t4x2+189t4x-131t3x2+213t2x2-86tx2+x3+9x2;
displayTropicalLifting(tropicalLifting(f4,intvec(2,-7),4,"findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (2,-7)
///////////////////////////////////////////////////////////////////
// t->t6 and x=3t3+t7+4t11-t12
poly f5=t12-4120t11+6t10x-1008t10-96t9x+15t8x2+4453t9-2016t8x-144t7x2+20t6x3-18t8-108t7x-1008t6x2-96t5x3+15t4x4-4681t7-36t6x-162t5x2-24t3x4+6t2x5+243t6-18t4x2-108t3x3+x6+1890t5+486t4x-27tx4+243t2x2-729t3;
displayTropicalLifting(tropicalLifting(f5,intvec(2,-1),3,"isInTrop","isZeroDimensional","findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (2,-1)
///////////////////////////////////////////////////////////////////
ring r2=0,(t,x,y),dp;
poly f7=(9t27-12t26-5t25+21t24+35t23-51t22-40t21+87t20+56t19-94t18-62t17+92t16+56t15-70t14-42t13+38t12+28t11+18t10-50t9-48t8+40t7+36t6-16t5-12t4+4t2)*x2+(-9t24+12t23-4t22-42t20+28t19+30t18-20t17-54t16+16t15+48t14-16t12+8t11-18t10-26t9+30t8+20t7-24t6+4t5+28t4-8t3-16t2+4)*xy+(6t16-10t15-2t14+16t13+4t12-18t11-10t10+24t9+6t8-20t7+8t6+8t5-20t4-4t3+12t2+4t-4)*y2+(-9t28+3t27+8t26-4t25-45t24-6t23+42t22+30t21-94t20-40t19+68t18+82t17-38t16-60t15+26t14+36t13-22t12-20t11+4t10+4t9+12t8+8t7-8t6-8t5+4t4)*x+(9t27-21t26+16t25+14t24+12t23-61t22+27t21+80t20-19t19-100t18+26t17+96t16-24t15-84t14+44t12-2t11-18t10+2t9+40t8+4t7-32t6-12t5+4t3+12t2-4)*y+(9t27-12t26+4t25+36t23-18t22-28t21-2t20+54t19+14t18-52t17-44t16+24t15+40t14-4t13-12t12+4t11-4t10-4t9+4t8);
displayTropicalLifting(tropicalLifting(f7,intvec(1,-1,-4),4,"isPrime"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-1,-4)
///////////////////////////////////////////////////////////////////
ring r3=0,(t,x,y,z),dp;
ideal i1=-y2t4+x2,yt3+xz+y;
displayTropicalLifting(tropicalLifting(i1,intvec(1,-2,0,2),4,"findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-2,0,2)
///////////////////////////////////////////////////////////////////
ideal i2=-y2t4+x2,yt3+yt2+xz;
displayTropicalLifting(tropicalLifting(i2,intvec(1,-3,-1,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3,-1,0)
////////////////////////////////////////////////////////////////
ring r4=0,(t,x,y,z,u),dp;
ideal i3=t3x+ty+u,tx+t2u+y;
displayTropicalLifting(tropicalLifting(i3,intvec(1,-1,-2,-1,-3),6),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-1,-2,-1,-3)
/////////////////////////////////////////////////////////////////////
setring r2;
ideal i5=t3-t2y+t2-tx-ty+xy,t3-t2y+t2-2ty+y2,-t4+2t3x-t2x2-t3+3t2x-3tx2+x3+t2+t-x,-t4+2t3x-t2x2-t3+2t2x-tx2+t2y-2txy+x2y+t2+t-y;
displayTropicalLifting(tropicalLifting(i5,intvec(1,-1,-1),3),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-1,-1)
////////////////////////////////////////////////////////////////////
ring r5=0,(t,V,W,X,Y,Z),dp;
ideal i5=VXt5+3VZt4-2VXt3+WXt3+V2t2+3WZt2-2WXt+VW,-4W2X4+V2t2;
displayTropicalLifting(tropicalLifting(i5,intvec(2,-3,-3,-1,-1,-1),3),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (2,-3,-3,-1,-1,-1)
///////////////////////////////////////////////////////////////////
ring r6=0,(t,x,y,z),dp;
ideal i6=t4xy-y3z3+3t2xy3-txy2+t4y;
displayTropicalLifting(tropicalLifting(i6,intvec(3,0,-9,2),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (3,0,-9,2)
////////////////////////////////////////////////////////////
// very easy example stops after one loop with an exact result
ideal i7=t2xy-2x2z;
displayTropicalLifting(tropicalLifting(i7,intvec(1,1,3,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,1,3,0)
/////////////////////////////////////////////////////////////
displayTropicalLifting(tropicalLifting(i7,intvec(1,-3,-1,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3,-1,0)
/////////////////////////////////////////////////////////////////
// requires one field extension
ideal i8=t-x3+3yz;
displayTropicalLifting(tropicalLifting(i8,intvec(1,1,3,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,1,3,0)
/////////////////////////////////////////////////////////////////
displayTropicalLifting(tropicalLifting(i8,intvec(1,-3,-1,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3,-1,0)
/////////////////////////////////////////////////////////////////
// requires one field extension
ideal i9=t-x3+3yz,t2xy-2x2z;
displayTropicalLifting(tropicalLifting(i9,intvec(1,1,3,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,1,3,0)
// takes too much time
//displayTropicalLifting(tropicalLifting(i9,intvec(1,-3,-1,0),4),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3,-1,0)
/////////////////////////////////////////////////////////////////////
// too much for Gfan did not work on my computer
//ideal i10=t2xy+t4-z2,t-2xy+z2+tz,z2-y;
//displayTropicalLifting(tropicalLifting(i10,intvec(2,4,-6,-3),2),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (2,4,-6,-3)
////////////////////////////////////////////////////////////////////
ring r7=0,(t,x,y),dp;
ideal i11=t4xy-y3+3t2xy3-txy2+t4y;
displayTropicalLifting(tropicalLifting(i11,intvec(1,3,1),5),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,3,1)
////////////////////////////////////////////////////////////////
ring r8=0,(t,x),dp;
ideal i12=x32+(16t6)*x30+(8t10)*x29+(120t12)*x28+(112t16)*x27+(32t20+560t18)*x26+(728t22)*x25+(388t26+1820t24)*x24+(80t30+2912t28)*x23+(2160t32+4368t30)*x22+(824t36+8008t34)*x21+(138t40+7304t38+8008t36)*x20+(3840t42+16016t40)*x19+(1180t46+16720t44+11440t42)*x18+(170t50+10680t48+24024t46)*x17+(4480t52+27324t50+12870t48)*x16+(1168t56+19680t54+27456t52)*x15+(152t60+9920t58+32736t56+11440t54)*x14+(3472t62+25200t60+24024t58)*x13+(804t66+14140t64+29040t62+8008t60)*x12+(96t70+5824t68+22848t66+16016t64)*x11+(1776t72+13496t70+19008t68+4368t66)*x10+(364t76+6020t74+14640t72+8008t70)*x9+(42t80+2112t78+8680t76+9020t74+1820t72)*x8+(544t82+3920t80+6480t78+2912t76)*x7+(104t86+1448t84+3680t82+2992t80+560t78)*x6+(12t90+400t88+1568t86+1880t84+728t82)*x5+(94t92+564t90+970t88+648t86+120t84)*x4+(16t96+144t94+352t92+320t90+112t88)*x3+(3t100+36t98+112t96+140t94+80t92+16t90)*x2+(6t102+20t100+34t98+24t96+8t94)*x+(t106+5t104+8t102+8t100+4t98+t96);
displayTropicalLifting(tropicalLifting(i12,intvec(1,-3),2),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3)
////////////////////////////////////////////////////////////////
ring r9=3,(t,x),dp;
ideal i13=imap(r8,i12);
displayTropicalLifting(tropicalLifting(i13,intvec(1,-3),3,"noAbs"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-3)
/////////////////////////////////////////////////////
// without the option findAll we first get only a non-valid solution !!!
ring r10=0,(t,x,y,z,u),dp;
ideal i14=-y2t5-xyt4-2yzt3+yut2+xut+2zu;
displayTropicalLifting(tropicalLifting(i14,intvec(1,-2,-1,-3,-3),3),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (1,-2,-1,-3,-3)
///////////////////////////////////////////////////////
// test for positive characteristic
///////////////////////////////////////////////////////////////////
ring r11=13,(t,x),dp;
poly f1=(x2-t3)*(x3-t5)*(x5-t7)*(x7-t11)*(x11-t13);
displayTropicalLifting(tropicalLifting(f1,intvec(7,-11),4,"findAll"),"subst");
///////////////////////////////////////////////////////////////////
// weight was: (7,-11)
///////////////////////////////////////////////////////////////////
// one field extension needed
// x=(X(1))*t+(-1/2*X(1))*t^3+(3/8*X(1)-1/2)*t^5+(-5/16*X(1)+1/2)*t^7+(19/128*X(1)-1/2)*t^9+(-15/256*X(1)+1/2)*t^11+(-9/1024*X(1)-1/2)*t^13 where t->t and X(1)^2+1=0
poly f2=(1+t2)*x2+t5x+t2;
displayTropicalLifting(tropicalLifting(f2,intvec(1,-1),4,"isZeroDimensional","findAll"),"subst");
///////////////////////////////////////////////////////////////////
ring r12=5,(t,x,y),dp;
ideal i11=t4xy-y3+3t2xy3-txy2+t4y;
displayTropicalLifting(tropicalLifting(i11,intvec(1,3,1),5),"subst");
///////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////
/// B) Examples for tropicalCurve
///////////////////////////////////////////////////////////////////
ring r=(0,t),(x,y),dp;
poly f=t*(x7+y7+1)+1/t*(x4+y4+x2+y2+x3y+xy3)+1/t7*x2y2;
list graph=tropicalCurve(f);
graph;
size(graph)-1;
drawTropicalCurve(graph);
poly g=t3*(x7+y7+1)+1/t3*(x4+y4+x2+y2+x3y+xy3)+1/t21*x2y2;
list tropical_g=tropicalise(g);
tropical_g;
drawTropicalCurve(tropical_g);
/// further examples
poly f1=x+y;
poly f2=xy+xy3+xy6+txy9;
poly f3=xy+x2y3+x3y6+tx4y9;
poly f4=t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy;
poly f5=t8x3+t8y3+t8+t4x2y+t4xy2+t4x2+t4y2+t4x+t4y+t2xy;
poly f6=x3+y3+1;
poly f7=t*x70+t*y70+1/t*x40+1/t7*x20y20+1/t*y40+1/t*x30y+1/t*xy30+1/t*x20+1/t*y20+t;
poly f8=t10*x7+t10*y7+1/t10*x4+1/t70*x2y2+1/t10*y4+1/t10*x3y+1/t10*xy3+1/t10*x2+1/t10*y2+t10;
poly f9=x+y+x2y+xy2+1/t*xy;
poly f10=1+x+y+xy+tx2y+txy2+t3x5+t3y5+tx2y2+t2xy4+t2yx4;
poly f11=1/(t8)*x6y+1/(t16)*x5y2+1/(t9)*x4y3+(t4)*x2y5+1/(t11)*xy6+(t5)*y7+1/(t5)*x6+(t16)*x4y2+(t10)*x3y3+(t19)*xy5+(t14)*x5+1/(t17)*x3y2+(t10)*x2y3+1/(t20)*xy4+(t13)*y5+1/(t17)*x4+(t9)*x3y+(t11)*xy3+1/(t3)*xy2+(t7)*y3+1/(t18)*x2+(t16)*x;
poly f12=-x3+(6t13+3t12+t5+3t4+3t3+1)/(t19)*x2+(2t5+1)/(t12)*xy+y2+(9t28-12t23-12t22+3t21+9t19+3t16-8t15-16t14-24t13-9t12-6t11-8t10-3t9-3t8-4t6-8t5-8t4-3t3-3t-2)/(t35)*x+(9t27+6t20-8t14-4t13-6t12-3t11-4t9-t8-4t5-4t4-2t3-1)/(t27)*y+(27t50+27t43-36t37-9t36-27t35-27t34-t32+12t31-18t30-11t29-54t28-36t27-12t25+13t24+28t23+61t22+27t21+18t20+16t19+3t18+14t17+3t16+16t15+26t14+44t13+34t12+21t11+27t10+12t9+7t8+t6+10t5+11t4+7t3+t2+2t+2)/(t50);
poly f13=x3+(3t9+1)/(t8)*x2y+(3t10+2t+1)/(t8)*xy2+(t10+t7+t+1)/(t7)*y3+1/(t8)*x2+(2t5+1)/(t12)*xy+(t5+t3+1)/(t11)*y2+1/(t8)*x+(t+1)/(t8)*y+1;
poly f14=x3+(3t9+3t6c+1)/(t8)*x2y+(3t12+6t9c+3t6c2+2t3+t2+2c)/(t10)*xy2+(t15+3t12c+t12+3t9c2+t6c3+t6+t5+2t3c+t2c+c2)/(t12)*y3+1/(t8)*x2+(2t5+2t2c+1)/(t12)*xy+(t8+t6+2t5c+t3+t2c2+c)/(t14)*y2+1/(t8)*x+(t3+t2+c)/(t10)*y+1;
poly f15=x3+x2y+xy2+(t5)*y3+x2+1/(t4)*xy+y2+x+y+1;
poly f16=t*(x7+y7+1)+1/t*(x4+y4+x2+y2+x3y+xy3)+1/t7*x2y2;

///////////////////////////////////////////////////////////////////
/// B) Examples for tropicalJInvariant
///////////////////////////////////////////////////////////////////
// tropcial_j_invariant computes the tropical j-invariant of the elliptic curve f
tropicalJInvariant(t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy);
// the Newton polygone need not be the standard simplex
tropicalJInvariant(x+y+x2y+xy2+1/t*xy);
// the curve can have arbitrary degree
tropicalJInvariant(t*(x7+y7+1)+1/t*(x4+y4+x2+y2+x3y+xy3)+1/t7*x2y2);
// the procedure does not realise, if the embedded graph of the tropical curve has
// a loop that can be resolved
tropicalJInvariant(1+x+y+xy+tx2y+txy2);
// but it does realise, if the curve has no loop at all ...
tropicalJInvariant(x+y+1);
// or if the embedded graph has more than one loop - even if only one cannot be resolved
tropicalJInvariant(1+x+y+xy+tx2y+txy2+t3x5+t3y5+tx2y2+t2xy4+t2yx4);
// f is already in Weierstrass form
weierstrassForm(y2+yx+3y-x3-2x2-4x-6);
// g is not, but wg is
g=x+y+x2y+xy2+1/t*xy;
poly wg=weierstrassForm(g);
wg;
// ... but it is not yet a simple, since it still has an xy-term, unlike swg
poly swg=weierstrassForm(g,1);
swg;
// the j-invariants of all three polynomials coincide ...
jInvariant(g);
jInvariant(wg);
jInvariant(swg);
// the following curve is elliptic as well
poly h=x22y11+x19y10+x17y9+x16y9+x12y7+x9y6+x7y5+x2y3;
// its Weierstrass form is
weierstrassForm(h);
jInvariant(x+y+x2y+y3+1/t*xy,"ord");
// see also example f5-f16 in part B)


*/


/////////////////////////////////////////////////////////////////////////

proc drawTwoTropicalCurves (list ff,list #)
"USAGE:      drawTropicalCurve(f[,#]); f poly or list, # optional list
ASSUME:      f is list of linear polynomials of the form ax+by+c with
             integers a, b and a rational number c representing a tropical
             Laurent polynomial defining a tropical plane curve;
             alternatively f can be a polynomial in Q(t)[x,y] defining
             a tropical plane curve via the valuation map;
             the basering must have a global monomial ordering, two
             variables and up to one parameter!
RETURN:      NONE
NOTE:        - the procedure creates the files /tmp/tropicalcurveNUMBER.tex and
               /tmp/tropicalcurveNUMBER.ps, where NUMBER is a random four
               digit integer;
               moreover it displays the tropical curve via kghostview;
               if you wish to remove all these files from /tmp,
               call the procedure cleanTmp
@*           - edges with multiplicity greater than one carry this multiplicity
@*           - if # is empty, then the tropical curve is computed w.r.t. minimum,
               if #[1] is the string 'max', then it is computed w.r.t. maximum
@*           - if the last optional argument is 'onlytexfile' then only the
               latex file is produced; this option should be used if kghostview
               is not installed on your system
@*           - note that lattice points in the Newton subdivision which are
               black correspond to markings of the marked subdivision,
               while lattice points in grey are not marked
EXAMPLE:     example drawTropicalCurve  shows an example"
{
  // check if the option "onlytexfile" is set, then only a tex file is produced
  if (size(#)!=0)
  {
    if (#[size(#)]=="onlytexfile")
    {
      int onlytexfile;
      #=delete(#,size(#));
    }
  }
  // store this list # for use in the Newton subdivision
  list oldsharp=#;
  // start the actual computations
  string texf;
  list graph,graphs,texfs;
  int i,j;
  for (i=1;i<=size(ff);i++)
  {
    def f=ff[i];
    if (typeof(f)=="poly")
    {
      // exclude the case that the basering has not precisely
      // one parameter and two indeterminates
      if ((npars(basering)!=1) or (nvars(basering)!=2))
      {
        ERROR("The basering should have precisely one parameter and two indeterminates!");
      }
      texf=texPolynomial(f); // write the polynomial over Q(t)
      graph=tropicalCurve(tropicalise(f,#),#); // graph of tropicalis. of f
    }
    if (typeof(f)=="list")
    {
      if (size(#)==0)
      {
        texf="\\min\\{";
      }
      else
      {
        texf="\\max\\{";
      }
      for (j=1;j<=size(f);j++)
      {
        texf=texf+texPolynomial(f[j]);
        if (j<size(f))
        {
          texf=texf+", ";
        }
        else
        {
          texf=texf+"\\}";
        }
      }
      graph=tropicalCurve(f,#); // the graph of the tropical polynomial f
      // detropicalise ff[i]
      ff[i]=tDetropicalise(f);
    }
    graphs[i]=graph;
    texfs[i]=texf;
    kill f;
  }
  // add the product of all curves as an additional curve
  poly f=1;
  for (i=1;i<=size(ff);i++)
  {
    f=f*ff[i];
  }
  ff=insert(ff,f);
  graphs=insert(graphs,tropicalCurve(f,#));
  texfs=insert(texfs,texPolynomial(f));
  // produce the tex file
  string vertices;
  list verticess;
  for (i=1;i<=size(ff);i++)
  {
    graph=graphs[i];
    for (j=1;j<=size(graph)-2;j++)
    {
      vertices=vertices+"("+string(graph[j][1])+","+string(graph[j][2])+"),\\;\\;";
    }
    vertices=vertices+"("+string(graph[j][1])+","+string(graph[j][2])+")";
    verticess[i]=vertices;
    vertices="";
  }
  string TEXBILD="\\documentclass[12pt]{amsart}
\\usepackage{texdraw}
\\setlength{\\topmargin}{30mm}
\\addtolength{\\topmargin}{-1in}
\\addtolength{\\topmargin}{-\\headsep}
\\addtolength{\\topmargin}{-\\headheight}
\\addtolength{\\topmargin}{-\\topskip}
\\setlength{\\textheight}{267mm}
\\addtolength{\\textheight}{\\topskip}
\\addtolength{\\textheight}{-\\footskip}
\\addtolength{\\textheight}{-30pt}
\\setlength{\\oddsidemargin}{-1in}
\\addtolength{\\oddsidemargin}{20mm}
\\setlength{\\evensidemargin}{\\oddsidemargin}
\\setlength{\\textwidth}{170mm}

\\begin{document}
   \\parindent0cm
   \\begin{center}
      \\large\\bf The Tropicalisation of several curves:
   \\end{center}

      \\bigskip
";
  string fname;
  for (i=1;i<=size(ff);i++)
  {
    if (i==1)
    {
      fname="f_1\\cdots f_{"+string(size(ff)-1)+"}";
    }
    else
    {
      fname="f_{"+string(i-1)+"}";
    }
    TEXBILD=TEXBILD+"
    The vertices of the tropical curve
    \\begin{center}
      \\begin{math}
          "+fname+"="+texfs[i]+"
      \\end{math}
    \\end{center}
    are
    \\begin{center}
      \\begin{math}
          "+verticess[i]+"
      \\end{math}
    \\end{center}
    \\vspace*{0.5cm}
  ";
  }
  // compute the center and the scale factor
  list SCF=minScaleFactor(graphs);
  #[size(#)+1]=SCF;
  string relunitscale="
       \\relunitscale "+ decimal(SCF[1],SCF[3]);
  #[size(#)+1]=relunitscale;
  // collect the texdraw input for all the curves with different color
  string TDT;
  for (i=1;i<=size(ff);i++)
  {
    #[size(#)+1]="\\setgray "+decimal(1-(number(i)/(size(ff)+1)))+"
";
    if (i>1)
    {
      TDT=TDT+"
"+texDrawTropical(graphs[i],#);
    }
    else
    {
      #=insert(#,"noweights");
      TDT=TDT+"
"+texDrawTropical(graphs[i],#);
      #=delete(#,1);
    }
  }
  // add lattice points if the scalefactor is >= 1/2
  // and was not handed over
  def scalefactor=SCF[1];
  if (scalefactor>1/2)
  {
    def minx=SCF[4];
    def miny=SCF[5];
    def maxx=SCF[6];
    def maxy=SCF[7];
    def centerx=SCF[8];
    def centery=SCF[9];
    int uh=1;
    if (scalefactor>3)
    {
      uh=0;
    }
    TDT=TDT+"

   %% HERE STARTS THE CODE FOR THE LATTICE";
    for (i=int(minx)-uh;i<=int(maxx)+uh;i++)
    {
      for (j=int(miny)-uh;j<=int(maxy)+uh;j++)
      {
        TDT=TDT+"
        \\move ("+decimal(i-centerx)+" "+decimal(j-centery)+") \\fcir f:0.8 r:"+decimal(1/(10*scalefactor),size(string(int(scalefactor)))+1);
      }
    }
    TDT=TDT+"
   %% HERE ENDS THE CODE FOR THE LATTICE
                          ";
  }
  TEXBILD=TEXBILD+"
   \\begin{center}
"+texDrawBasic(TDT)+  // write the tropical curve
   "\\end{center}

   \\vspace*{0.5cm}
";
  // compute the scaling factor for the Newton subdivisions
  oldsharp[size(oldsharp)+1]=nsdScaleFactor(graphs);
  for (i=1;i<=size(ff);i++)
  {
    if (i==1)
    {
      fname="f_1\\cdots f_{"+string(size(ff)-1)+"}";
    }
    else
    {
      fname="f_{"+string(i-1)+"}";
    }
    TEXBILD=TEXBILD+"
   The Newton subdivision of the tropical curve $"+fname+"$ is:
   \\vspace*{0.5cm}

   \\begin{center}
       "+texDrawNewtonSubdivision(graphs[i],oldsharp)+"
   \\end{center}

   \\vspace*{0.5cm}
";
  }
  TEXBILD=TEXBILD+"
\\end{document}";
  if(defined(onlytexfile)==0)
  {
    int rdnum=random(1000,9999);
    write(":w /tmp/tropicalcurve"+string(rdnum)+".tex",TEXBILD);
    system("sh","cd /tmp; latex /tmp/tropicalcurve"+string(rdnum)+".tex; dvips /tmp/tropicalcurve"+string(rdnum)+".dvi -o; command rm tropicalcurve"+string(rdnum)+".log;  command rm tropicalcurve"+string(rdnum)+".aux;  command rm tropicalcurve"+string(rdnum)+".ps?;  command rm tropicalcurve"+string(rdnum)+".dvi; kghostview tropicalcurve"+string(rdnum)+".ps &");
  }
  else
  {
    return(TEXBILD);
  }
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
//   poly f=t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy;
   poly f=x+y+1;
// the command drawTropicalCurve(f) computes the graph of the tropical curve
// given by f and displays a post script image, provided you have kghostview
// we can instead apply the procedure to a tropical polynomial and use "maximum"
   poly g=t3*(x7+y7+1)+1/t3*(x4+y4+x2+y2+x3y+xy3)+1/t21*x2y2;
//   list tropical_g=tropicalise(g);
   drawTwoTropicalCurves(list(f,g),"max");
}


proc minScaleFactor (list graphs)
{
  list graph;
  int j,i,k;
  poly minx,miny,maxx,maxy;
  poly minX,minY,maxX,maxY;
  poly maxdiffx,maxdiffy;
  poly centerx,centery;
  int nachkomma;
  number sf,scf;
  poly scalefactor;
  list SFCS;
  for (k=1;k<=size(graphs);k++)
  {
    graph=graphs[k];
    // find the minimal and maximal coordinates of vertices
    minx,miny,maxx,maxy=graph[1][1],graph[1][2],graph[1][1],graph[1][2];
    for (i=2;i<=size(graph)-1;i++)
    {
      minx=minOfPolys(list(minx,graph[i][1]));
      miny=minOfPolys(list(miny,graph[i][2]));
      maxx=-minOfPolys(list(-maxx,-graph[i][1]));
      maxy=-minOfPolys(list(-maxy,-graph[i][2]));
    }
    if (k==1)
    {
      minX=minx;
      minY=miny;
      maxX=maxx;
      maxY=maxy;
    }
    else
    {
      if (minx<minX)
      {
        minX=minx;
      }
      if (miny<minY)
      {
        minY=miny;
      }
      if (maxx>maxX)
      {
        maxX=maxx;
      }
      if (maxy>maxY)
      {
        maxY=maxy;
      }
    }
  }
  minx,miny,maxx,maxy=minX,minY,maxX,maxY;
  // find the scale factor for the texdraw image
  maxdiffx=maxx-minx;
  maxdiffy=maxy-miny;
  centerx,centery=int(minx+maxdiffx/2),int(miny+maxdiffy/2);
  if (maxdiffx==0)
  {
    maxdiffx=1;
  }
  if (maxdiffy==0)
  {
    maxdiffy=1;
  }
  nachkomma=2; // number of decimals for the scalefactor
  sf=1; // correction factor for scalefactor
  scalefactor=minOfPolys(list(12/leadcoef(maxdiffx),16/leadcoef(maxdiffy)));
  // if the scalefactor is less than 1/100, then we need more than 2 decimals
  if (leadcoef(scalefactor) < 1/100)
  {
    scf=leadcoef(scalefactor);
    while (scf < 1/100)
    {
      scf=scf * 10;
      nachkomma++;
    }
  }
  // if the scalefactor is < 1/100, then we should rather scale the
  // coordinates directly, since otherwise texdraw gets into trouble
  if (nachkomma > 2)
  {
    for (i=3;i<=nachkomma;i++)
    {
      scalefactor=scalefactor * 10;
      sf=sf*10;
    }
  }
  return(list(scalefactor,sf,nachkomma,minx,miny,maxx,maxy,centerx,centery));
}
example
{
   "EXAMPLE:";
   echo=2;
   ring r=(0,t),(x,y),dp;
   poly f=t*(x3+y3+1)+1/t*(x2+y2+x+y+x2y+xy2)+1/t2*xy;
   poly g=1/t3*(x7+y7+1)+t3*(x4+y4+x2+y2+x3y+xy3)+t21*x2y2;
   list graphs;
   graphs[1]=tropicalCurve(f);
   graphs[2]=tropicalCurve(g);
   minScaleFactor(graphs);
}

proc nsdScaleFactor (list graphs)
{
  int i,j;
  list graph,boundary,scalefactors;
  poly maxx,maxy;
  for (j=1;j<=size(graphs);j++)
  {
    graph=graphs[j];
    boundary=graph[size(graph)][1];
    // find maximal and minimal x- and y-coordinates and define the scalefactor
    maxx,maxy=1,1;
    for (i=1;i<=size(boundary);i++)
    {
      maxx=-minOfPolys(list(-maxx,-boundary[i][1]));
      maxy=-minOfPolys(list(-maxy,-boundary[i][2]));
    }
    scalefactors[j]=minOfPolys(list(12/leadcoef(maxx),12/leadcoef(maxy)));
  }
  return(minOfPolys(scalefactors));
}