File: orwp.C

package info (click to toggle)
magnus 20060324-5.1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 19,436 kB
  • ctags: 20,462
  • sloc: cpp: 130,217; ansic: 37,090; tcl: 10,970; perl: 1,109; makefile: 966; sh: 403; yacc: 372; csh: 57; awk: 33; asm: 10
file content (3136 lines) | stat: -rw-r--r-- 73,860 bytes parent folder | download | duplicates (2)
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
// Copyright (C) 1995 The New York Group Theory Cooperative
// See magnus/doc/COPYRIGHT for the full notice.
//
// Contents: A standalone executable which accepts a stream of relators
//           and test words; says whether the test word is trivial
//           modulo the relator.
//
// Principal Author: Dion Gildenhuys
//
// Status: Stable
//
// Usage:
//
// Discussion:
//
// Revision History:
//
// * 07/12/95 Roger commented out most output to cout
//
// Next Implementation Steps:
//


#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <new>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;


// #define INFILE
//#define VERBOSE_MODE
#define MAXSTACK 10000
#define UNIX
#define READ_LENGTHS

#ifdef READ_LENGTHS

static int len1, len2;
static int maxLen1 = 1000, maxLen2 = 3000;

#endif

enum probType { wp, mp, rp }; // word problem, membership problem
	// reduction problem
enum pinchType { none, up, down };
enum tryMoveType { out, left, right };
enum answerType { maybe, no, yes };

#ifndef UNIX

 enum { false, true };
 typedef int bool;

#endif


// ofstream outFile( "out", ios::out );

#ifdef INFILE

 ifstream inFile( "in", ios::in );

#endif


template <class TYPE>
class stack{
private:
    enum { EMPTY = -1 };        
    TYPE* s;
    int max_len;
    int top;
public:
    stack() :max_len(MAXSTACK)
	   { s = new TYPE[MAXSTACK]; if (s == 0) {
			cerr << "\nOut of Memory\n"; exit(1);} top = EMPTY; }
	stack(int size) { s = new TYPE[size]; if ( s == 0 ) {
			cerr << "\nOut of Memory\n"; exit(1);}
			max_len = size; top = EMPTY;}
    ~stack() { delete [] s; }
    void reset() { top = EMPTY;}
	void push(TYPE c) { s[++top] = c; }
	TYPE pop() { return(s[top--]); }
    int empty() const { return(top == EMPTY);}
};

template<class Type>
class ListElt{
public:
   Type   data;
   ListElt<Type>* next;
};

template<class Type>
class list{
protected:
   ListElt<Type>* h;      //head of list
public:
   list() {h=0;}    //0 denotes the empty list
   ~list() { release(); }
   list(const list& l);
   void prepend(const Type &c);        //adds to the front of the list
   void del() {     ListElt<Type>* temp =h;
                    h = h->next;
                    delete temp;}
   ListElt<Type>* first() const { return (h); }
   void release();
   void reverse();
   void print();
   void advance();
   int length() const;
   bool isTrivial() const { return ( h == 0 ); }
   list<Type>& operator=(const list<Type>& );
};

template<class Type> list<Type>& list<Type>::operator=(const list<Type>& w)
{
    if ( this == &w )
        return *this;
    ListElt<Type>* elem = w.h;

    if ( elem == 0 )
        return *this;
    if ( h != 0 )
        delete h;
    h = 0;
    while ( elem ) {
        prepend( elem -> data );        // overloaded assignment
        elem = elem -> next;
        }
    reverse();
    return *this;
    }

template<class Type> int list<Type>::length() const
{
   ListElt<Type>* temp = h;
   int count = 0;

   while (temp != 0) {
      ++count;
      temp = temp -> next;
      }

   return(count);
}



template<class Type> void list<Type>::prepend( const Type &c)
{
   ListElt<Type>* temp = new ListElt<Type>; // creates new element

   if ( temp == 0 ) {
	cerr << "\nOut of memory!\n";
	exit(1);
	}
   temp -> next = h;
   temp -> data = c; // in the case of superWord, this is the overloaded
                     // assignment operator for superGen
   h = temp;
}

template<class Type> void list<Type>::release()
{
   while (h !=0 )
          del();
}

template<class Type> void list<Type>::reverse()
{
   ListElt<Type>* pred, *succ, *elem;

   if (h == 0 ) return;
   if (h && ( ( succ = h -> next ) != NULL ) ) {
        pred = 0;
        elem = h;
        while (succ) {
           elem -> next = pred;
           pred = elem;
           elem = succ;
           succ = succ -> next;
        }
		h = elem;
        h -> next = pred;
   }
}

template<class Type> void list<Type>::advance()
{
   ListElt<Type>* temp;

   temp = h;
   h = temp -> next;
   delete temp;
}

template<class Type> list<Type>::list(const list<Type>& l)
{
   ListElt<Type>* elem = l.h;
   list<Type> temp;
   
   h = 0;
   while (elem) {
        temp.prepend( elem -> data );
        ++elem;
        }
   reverse();
}

class superGen {     // has an exponent and list of subscripts
private:
   int exponent, temp;
   ListElt<int> *subscript;
public:
   superGen() {subscript = 0; exponent = 0;}
   superGen(const superGen& s);
   ~superGen() { release(); }
   void assignExponent(int n) { exponent = n;}
   void adjoinSubscript(const int m);
   void print();
   void del() { ListElt<int>* temp = subscript;
                subscript = subscript -> next;
                delete temp;}
   ListElt<int>* firstSubscript() const { return (subscript); }
   int exp() const { return (exponent);}
   void release();
   void reverseSubscripts();
   void invert() { temp = exponent; exponent = -temp; }
   superGen& operator=(const superGen& );
   bool isTrivial() const { return ( subscript == 0 ); }
};


superGen& superGen::operator=(const superGen& s)
{
   if ( this == &s )
     return *this;
   ListElt<int>* oldElem = s.subscript;

   exponent = s.exponent;
   if ( subscript != 0 )
     delete subscript;
   subscript = 0;

   if (oldElem == 0)
        return(*this);

   while (oldElem) {
        adjoinSubscript(oldElem -> data);
        oldElem = oldElem -> next;
		}

   reverseSubscripts();
   return(*this);
}

int sameSubscripts(const superGen &a, const superGen &b)
{

   ListElt<int>* elt1, *elt2;

   elt1 = a.firstSubscript();
   elt2 = b.firstSubscript();
   if ((elt1 == 0) && (elt2 == 0))
        return(1);
   while ((elt1 != 0) && (elt2 != 0))
        {
        if ((elt1 -> data) != (elt2 -> data))
           return(0);
        elt1 = elt1 -> next;
        elt2 = elt2 -> next;
        }
   if ((elt1 == 0) && (elt2 != 0))
        return(0);
   if ((elt2 == 0) && (elt1 != 0))
        return(0);
   return(1);
}

void superGen::adjoinSubscript( const int m )
{
   ListElt<int>* temp = new ListElt<int>;

	if ( temp == 0 ) {
	cerr << "\nOut of memory!\n";
	exit(1);
	}


   temp -> next = subscript;
   temp -> data = m;
   subscript = temp;
}

void superGen::release()
{
   while (subscript != 0)
        del();
}

void superGen::reverseSubscripts()
{
   ListElt<int>* pred, *succ, *elem;

      if (subscript && ( ( succ = subscript -> next) != NULL ) ) {
        pred = 0;
        elem = subscript;
        while (succ) {
           elem -> next = pred;
           pred = elem;
           elem = succ;
           succ = succ -> next;
        }
        subscript = elem;
        subscript -> next = pred;
   }
}


superGen::superGen(const superGen& s) : exponent(s.exponent)
{ 
   ListElt<int>* oldElem = s.subscript;

   subscript = 0;
   if (oldElem == 0)
        return;

   while (oldElem) {
        adjoinSubscript(oldElem -> data);
        oldElem = oldElem -> next;
        }
   reverseSubscripts();
}


void superGen::print()
{
   ListElt<int>* temp = subscript;
   int k;

   cout << "x_" ;
   while (temp != 0) {
        k = temp -> data;
		cout << k;
        temp = temp -> next;
		if (temp) cout << ',';
   }
   cout << '^' << exponent;
}

template<> void list<char>::print()
{
   ListElt<char>* temp = h;

   while (temp !=0) { //detect end of list
		  cout << temp -> data;
          temp = temp -> next;
   }
   cout << "\n";
}

class PowerOfNamedGen {
private:
   char name;
   int power;
public:
   void assign(char c, int n){ name = c; power = n;}
   void print();
   char nme() { return(name); }
   int pwr() { return(power);}
};

void PowerOfNamedGen::print()
{
   cout << name << "^" << power;
}
 

class ListOfPowersOfNamedGens: public list<PowerOfNamedGen>
{
public:
   void print(); 
   bool userInput();
};


void ListOfPowersOfNamedGens::print()
{
   ListElt<PowerOfNamedGen>* temp = h;

   while (temp != 0) {
         (temp -> data).print();
          temp = temp -> next;
   }
   cout << "\n";
}

bool ListOfPowersOfNamedGens::userInput()
{
   PowerOfNamedGen g;
   int c;
   int n;

//   cout << "Input string:\n";

#ifdef INFILE

   c = inFile.get();

#else

   c = cin.get();

#endif

   while ( c != '\n'){
	  if ( c == EOF )
		return( false );
	  if ( ( c > 'z') || (c < 'A' ) ) {
		 cerr << "Bad input \n ";
		 exit(1);
	  }

#ifdef INFILE

	  inFile >> n;

#else

	  cin >> n;

#endif

	  g.assign( c, n );
	  prepend( g );

#ifdef INFILE

	  c = inFile.get();

#else

	  c = cin.get();

#endif

   }

   reverse();
   return( true );
}

int indexFirstCharMatch(const char c, ListOfPowersOfNamedGens* lpn)
   // return the index to assign to the generator with name c
{
   int count = 0;
   ListElt<PowerOfNamedGen>* le = lpn -> first();
   char d;

   while (le != 0) {
        d = (le -> data).nme();
        ++count;
        if (d == c) 
           break;
        le = le -> next;
        }
   return(count);
}


class superWord: public list<superGen>
{
public:
   void print();
   void invert();
   void freelyReduce();
   void adjoinSubscriptFirstGen( int n )
        { ( h -> data ).adjoinSubscript( n ); }
   void assignExponentFirstGen( int n )
        { ( h -> data ).assignExponent( n ); }
   void invertFirstGen() { ( h -> data ).invert(); }
};


void superWord::freelyReduce()
{

   ListElt<superGen>* genp1, *genp2, *genp3, *genp0;
   int exp1, exp3, len = length();
   stack<ListElt<superGen>*> st(len);

   genp1 = h;   // points to current generator
   genp0 = h;   // will point later to previous generator if there is one

   while (genp1 != 0){
        genp3 = genp1 -> next;  // the testing generator 
        if (genp3 == 0)
            return; // there is only one generator
        exp1 = (genp1 -> data).exp();
        while (sameSubscripts( genp1 -> data, genp3 -> data )) {
           exp3 = ( genp3 -> data ).exp();
           exp1 += exp3;
           genp2 = genp3;   // for selfdestruction
           genp3 = genp3 -> next;
           delete(genp2); //
           if (genp3 == 0)
              break;
           }
        if (exp1 != 0) {  // consolodate generators into one
                // perhaps there was no cancellation
           (genp1 -> data).assignExponent(exp1);
           genp1 -> next = genp3;
           st.push( genp0 ); // push it onto the stack
           genp0 = genp1;  // will point to previous generator
           genp1 = genp3; // advance the current generator
           }
        else {  // a sequence of generators, including genp1, cancel
           if (h == genp1) { // at the beginning of the word
              delete(h);  // cancellation at the start
			  h = genp3;   // new beginning of word
              genp0 = h;
              genp1 = h;
              }
           else { 
              delete( genp1 );   // the current generator cancelled
              genp0 -> next = genp3;   // same previous generator
              if (genp3 == 0)
                 genp1 = 0;
              else {
                 if (0 == sameSubscripts
                    ( genp0 -> data, genp3 -> data ))
                    genp1 = genp3;       // not same subscripts
                 else { 
                    genp1 = genp0;      // backtrack
                    if (h != genp1)   // the stack should be nonempty
                       {
                       genp0 = st.pop();
                       genp0 -> next = genp1;
                       }
                    } 
                 }
                 
              }
           }
        }                       
}   

void superWord::invert()
{
   ListElt<superGen>* elem;

   reverse();
   elem = h;
   while (elem != 0) {
        (elem -> data).invert();
        elem = elem -> next;
        }
}

void superWord::print()
{
   ListElt<superGen>* temp = h;

   if (temp == 0) cout << "1";
   while (temp != 0) {
        (temp -> data).print();
		cout << " ";
        temp = temp -> next;
   }
   cout << "\n";
}

int exponentSum(const superGen &g, const superWord &w)
{
   int k = 0;
   ListElt<superGen>* x;

   x = w.first(); // pointer to first generator
   while (x != 0) {
        if (sameSubscripts( x -> data, g ))
                k += (x -> data).exp();      // add the exponent of x to k
        x = x -> next;
        }
   return (k);
} 

bool appearsIn( const superGen &g, const superWord &w )
{
    bool ans = false;
    ListElt<superGen>* lesg = w.first();

    if ( lesg == 0 )
        return( ans );

    while ( !sameSubscripts( lesg -> data, g )) {
        lesg = lesg -> next;
        if ( lesg == 0 )
            break;
        }

    if ( lesg != 0 )
        ans = true;
    return(ans);
}


void removeGen( superWord &a, const superGen &g )
{
    ListElt<superGen> *olesg, *lesg;


    lesg = a.first();

    if ( lesg == 0 )
	return;

    if ( sameSubscripts( g, lesg -> data ) ) {
	a.del();	// delete the first subscript
	return;
	}

	do {
	olesg = lesg;
	lesg = lesg -> next;
	if ( lesg != 0 ) {
		if ( sameSubscripts( g, lesg -> data ) ) {
		olesg -> next = lesg -> next;
		delete lesg;
		}
		lesg = olesg -> next;
		}
	} while ( lesg != 0 );
}

bool doesNotAppearIn( const superGen &g, const superWord &w )
{
	if ( appearsIn( g, w ))
		return( false );
	else
		return( true );
}


void conditionalChoice( int &x1, int &x2, superGen &st,
	superGen &accomp, const superWord &r, const superWord &target,
	bool (*cond)( const superGen&, const superWord& ))
	// This function defines st and its exponentsum x1, perhaps also
	// accomp and its exponentsum x2. If r contains a generator g, for
	// which cond( g, target ) is satisfied (if the pointer to cond has
	// been set to zero, then the condition cond is not applied),
	// and g has zero exponentsum
	// in r, then st is defined to be the first such g, and accomp and
	// x2 are ignored; otherwise, we choose accomp to be the first
	// generator g in r, different from st, that satisfies
	// cond( r, target ), and we set x2 equal to its exponentsum.
	// The function conditionalChoice is only invoked when the function
	// pointer to cond is set to zero, or when cond( g, target ) is true
	// for at least two generators g in r.

{
	int k = 0, abk, e, abe, m;
	ListElt<superGen> *x, *y, *z;
	bool firstTime = true, foundTwo = false;
	superGen *g;

	x = r.first();

	while ( x != 0 ) {
		if ( cond ) {
			while ( !( cond( x -> data, target ))) {
				x = x -> next;
				if ( x == 0 )	// impossible the first time
					break;
				}
			}
		if ( x == 0 )
			break;
		e = exponentSum( x -> data, r );
		if ( e == 0 ) {
			st = x -> data;	// overloaded assignment
			x1 = 0;
			break;	// the search has been completed
			}
		abe = (e < 0) ? -e : e; // abe is the absolute value of e
		if ( firstTime ) {
			y = x;
			k = e;
			firstTime = false;
			}
		else {
			if ( !sameSubscripts( x -> data, y -> data )) {
				foundTwo = true; // we found y and z = x:
				z = x;
				m = e;
				}
			abk = (k < 0) ? -k : k; // abs val of k
			if ( abe < abk ) { // then switch, so that abk remains minimal
				m = k;
				z = y;
				k = e;
				y = x;
				}
			}
		x = x -> next;
		}
	if ( e == 0 )
		return;
	if ( foundTwo ) {
		st = y -> data;
		x1 = k;
		accomp = z -> data;
		x2 = m;
		}
}

void chooseStableAccomp( const superWord &r, const superWord &outsideGens,
  superGen &stable, superGen &accomp, probType &ptype,
  const superWord &target, int &x1, int &x2, bool &sits )
	// Choose the generators stable and accomp in
	// accordance with the type of problem. Assume r has length >1.
	// In the cases of the word problem or the reduction problem,
	// the choice is made by the function conditionalChoice, with
	// its parameter function pointer cond set to 0. In the case
	// of the membership problem, we first consider the case where
	// the target subgroup is cyclic. If its generator has zero
	// exponent sum in r, we choose it as stable, we put x1=0,
	// sits = true, and we don't define accomp and x2. If the
	// generator for the cyclic target subgroup has nonzero exponent
	// sum in r, we look for another generator in r with nonzero
	// exponent sum in r. If we find it, then it will be accomp,
	// x2 will be its exponent sum, the generator for the target subgroup
	// will be stable (strictly, a root of it),
	// and x1 its exponent sum. In this case sits is
	// set to true. If no generator in r, outside the cyclic target
	// subgroup has nonzero exponent sum, then we define
	// stable outside the target subgroup, appearing in r, sits=false,
	// x1=0, and we don't define accomp, x2.
{
	ListElt<superGen> *x, *y, *fog = outsideGens.first();;
	int e;

	if ( ptype == wp ) { // find the exponentsum with least abs. value
		sits = false;
		if ( fog != 0 ) {
			stable = fog -> data;	// deep copy
			x1 = 0;
			return;
			}
		conditionalChoice( x1, x2, stable, accomp, r, target, 0 );
		}

	else { // first search for gen. outside r, in the target
		x = target.first();
		while ( x ) {
			if ( !appearsIn( x -> data, r )) {
				stable = x -> data; // deep copy
				x1 = 0;
				sits = true;
				ptype = rp;
				return;
				}
			x = x -> next;
			}

		if ( 1 == target.length() ) {
			x = target.first();
			x1 = exponentSum( x -> data, r ); // it may be redefined
			if ( x1 != 0 ) {
				y = r.first();
				while( y ) {
					e = exponentSum( y -> data, r );
					if (( e != 0 ) &&
					  ( !sameSubscripts( x -> data, y -> data )))
						break;
					y = y -> next;
					}
				if ( y == 0 ) { // the one case where sits will be false
					y = r.first();
					if ( sameSubscripts( x -> data, y -> data ))
						y = y -> next;
					stable = y -> data; // deep copy
					x1 = 0;
					sits = false;
					return;
					}
				else {
					stable = x -> data; // deep copy
					accomp = y -> data; // deep copy
					x2 = e;
					sits = true; // stable in, accomp outside target
					ptype = rp;
					return;
					}
				}
			else {
				stable = x -> data;
				sits = true;
				ptype = rp;
				return;
				}
			}

		// At this point, all target gens. (more than one) appear in r
		conditionalChoice( x1, x2, stable, accomp, r, target, appearsIn );
		ptype = rp;
		sits = true;
		 // stable and accomp will be chosen in the target subgroup

		}
}

void adjoinSubscriptsByConjugation
	( const superWord &w, const superGen &conjugator, superWord &psw )
{       // w is assumed to be freely reduced
   ListElt<superGen>* x;
   int sumPowersOfConj = 0;

   x = w.first();

   while ( x != 0 ) {
		if ( sameSubscripts( x -> data, conjugator ))
		   sumPowersOfConj += ( x -> data ).exp();
        else {
		   psw.prepend( x -> data ); // prepend a copy of the superGen
           psw.adjoinSubscriptFirstGen( sumPowersOfConj );
           }
        x = x -> next;
        }               
   if (sumPowersOfConj != 0) {
	  psw.prepend( conjugator ); // prepend a copy of the conjugator
	  psw.assignExponentFirstGen( sumPowersOfConj );
	  }
   psw.reverse();
   psw.freelyReduce(); 
}


void eltTransform( const superWord &w, const superGen &g1,
  const superGen &g2, superWord &ts)
  // If g1 = a^i then it is replaced by (a.g2)^i, yielding ts from w
{
   ListElt<superGen>* x;
   int count, exp;

   x = w.first();

   while (x != 0) {
        while (( x != 0 ) && ( !sameSubscripts( x -> data, g1 ))) {
            ts.prepend( x -> data ); // prepend a copy of the superGen
            x = x -> next; 
            }
        if ( x != 0 ) {  // g1 and x are the same
            exp = (x -> data).exp();
            count = (exp < 0) ? -exp : exp; // count is abs. val. exp
            while (count != 0) {
                if (exp < 0) {
                    ts.prepend( g2 );
                    ts.invertFirstGen();
                    ts.prepend( x -> data );
                    ts.assignExponentFirstGen( -1 );
                    }
                else {
                    ts.prepend( x -> data );
                    ts.assignExponentFirstGen( 1 );
                    ts.prepend( g2 );
                    }
                --count;
                }  // insertions have been made for 1 occurence of g1
            x = x -> next;
            }           // case of x = g1 is done
        }
   ts.reverse();
}

int indexFromListNames( list<char> &listNames, const char c )
      //  check if c is on the list; if so, return its position 
        // from the end, else prepend it to the list and return its
		// new position from the end
{
   int len, i = 0, found = 0;
   ListElt<char>* le;

   le = listNames.first();
   while (le != 0) {
        ++i;    
        if (c == le -> data) {
           found = 1;
           break;
           }
        le = le -> next;
        }
   if (found) {
        len = listNames.length();
        return(len + 1 -i);  // position from the end
        }
   listNames.prepend(c);  // name not found; add it to the list
   return(i + 1);  // length plus one
}


void superWordFromLPNG( ListOfPowersOfNamedGens &lpn,
    list<char> &listNames, superWord& sw )
{
   superGen *s;
   PowerOfNamedGen pn;
   ListElt<PowerOfNamedGen>* le;
   int index;
   int power;
   char name;

   le = lpn.first();
   while (le != 0) {
		s = new superGen;
		if ( s == 0 ) {
		cerr << "\nOut of memory!\n";
		exit(1);
			}
		pn = le -> data;
        power = pn.pwr();
        name = pn.nme();
        index = indexFromListNames(listNames, name);
        s -> adjoinSubscript(index);
        s -> assignExponent(power);
        sw.prepend(*s);
        le = le -> next;
        }

   sw.reverse();
}


void adjoinRootOfGen( superWord &w, const superGen &g, int n)
        // replace g by g^n in the word w
{
   ListElt<superGen>* le = w.first();
   int exp;

   while (le != 0) {
        if (sameSubscripts( g, le -> data )) {
           exp = (le -> data).exp();
           exp *= n;    // multiply the exponent by n
           (le -> data).assignExponent(exp);
		   }
        le = le -> next;
        }
}


class minMaxEntry {
public:
   superGen entry;
   int small;
   int big;
   minMaxEntry& operator=(const minMaxEntry& );
};

minMaxEntry& minMaxEntry::operator=(const minMaxEntry& mm)
{

	if ( this != &mm ) {
	 small = mm.small;
	 big = mm.big;
	 entry = mm.entry;   // overloaded assignment operator
    }
	return *this;

}

void lookUpMinMaxEntries
    ( const superGen &g, const list<minMaxEntry> &lmme,
    int &min, int &max)
    // it sets min and max equal to 0 if no match is found
{
    ListElt<minMaxEntry> *lemme;
    minMaxEntry* mme;
    bool found = false;

    lemme = lmme.first();

    while ( lemme != 0) {
        mme = &( lemme -> data );
        if (sameSubscripts( mme -> entry , g )) {
            min = mme -> small;
            max = mme -> big;
            found = true;
            break;
            }
        lemme = lemme -> next;
        }
    if ( !found ) {
	min = 0;
	max = 0;
	}

}

void adjoinSubscriptsByRestrictedConjugation
  (const superWord &w, const superGen &conjugator,
   const list<minMaxEntry> &lmme, superWord &psw )
{       // w is assumed to be freely reduced
   ListElt<superGen>* x;
   int sumPowersOfConj = 0;
   int lowerBd, upperBd;
   bool done = false;

   x = w.first(); // pointer to first generator

   while ( x != 0 ) {
        if ( sameSubscripts( x -> data, conjugator )) {
           sumPowersOfConj += ( x -> data ).exp();
		   }
        else {
           lookUpMinMaxEntries( x -> data, lmme, lowerBd, upperBd);
           if (lowerBd > sumPowersOfConj) {
                psw.prepend( conjugator ); // not moved through
                psw.assignExponentFirstGen( sumPowersOfConj - lowerBd );
                psw.prepend( x -> data );
                psw.adjoinSubscriptFirstGen( lowerBd );
                sumPowersOfConj = lowerBd; // the power that is moved through
                done = true;
                }
           if (upperBd < sumPowersOfConj) {
                psw.prepend( conjugator ); // not moved through
                psw.assignExponentFirstGen( sumPowersOfConj - upperBd );
                psw.prepend( x -> data );
                psw.adjoinSubscriptFirstGen( upperBd );
                sumPowersOfConj = upperBd; // the power that is moved through
                done = true;
                }

           if (!done) {
              psw.prepend( x -> data );
              psw.adjoinSubscriptFirstGen( sumPowersOfConj );
              }
           done = false;
           }
        x = x -> next;
        }               
   if (sumPowersOfConj != 0) {
      psw.prepend( conjugator );
      psw.assignExponentFirstGen( sumPowersOfConj );
      } 
   psw.reverse();
   psw.freelyReduce();
}

class MagProb {
public:
    int childNumber;
    list<int> exponentsStableLetter;
    int leftExp, rightExp;
    probType problemType;
    pinchType pinchT;
    list<char> listNames;   // names of generators; only used at the root
    superWord relator, rewrittenRelator;
    int relatorLength;
    superWord test, rewrittenTest, outsideGens; // outside means
	// outside the relator and outside the target subgroup
    superWord gensTargetSubgp; // re. membership problem
    superWord inheritedTarget;
    superWord gensAssocSubgp; // re. HNN extension
    superGen stableLetter, accompanyingGen;
    int exps1, exps2;
        // exps1 is the least exponent sum in the relator
        // If exps1 is not zero then it, exps2 and accompanyingGen are used
        // in the rewriting process of the relator and test word;
	// and exps2 is the exponentsum of accompanyingGen in relator
    list<minMaxEntry> lmm;
      // list of minimal and maximal subscripts
    bool stableInTargetSubgp;
    MagProb();
	bool inputRelator(); // only used at the root
	void inputTest();    // only used at the root
    void rewriteRelator(); // It defines exps1, exps2, rewrittenRelator,
			   // stableLetter, accompanyingGen,
			   // stableInTargetSubgp
    void defineOutsideGens();
    void createMinMaxSubscriptTable();
    void rewriteTest(); // it requires that exps1, exps2, stableLetter,
        // accompanyingGen, rewrittenRelator, llm all be already defined
    void printRelator() { relator.print(); }
    void printStableLetter() { stableLetter.print(); }
    void printAccompanyingGen() { if ( !accompanyingGen.isTrivial() )
                                    accompanyingGen.print(); }
    void printTestWord() { test.print();}
    void printRewrittenRelator() { rewrittenRelator.print(); }
    void printRewrittenTestWord() { rewrittenTest.print(); }
    void printMinMaxSubscripts();
    void printPinchType();
    void printInfo();
    bool abTest();
};

MagProb::MagProb()
{
    childNumber = 0;
    leftExp = 0;
    rightExp = 0;
    problemType = wp;
	pinchT = none;
	stableInTargetSubgp = false;
}


bool MagProb::abTest() // the abelianized word problem. Test whether
	// the exponentsum of each generator in test and not in gensTargetSubgp
	// is divisible by the exponentsum of the same generator in relator.
{
superGen *g;
bool ans = true;
int exps1, exps2, ratio;
ListElt<superGen>* lesg;
superWord found;	// the distinct generators in test
bool ratioDefined = false;

	lesg = test.first();
	if ( lesg == 0 )
		return( true );
	g = &(lesg -> data);

	while ( lesg != 0 ) {
		if (( problemType == mp ) || ( problemType == rp )) {
			while ( appearsIn( *g , gensTargetSubgp )) {
				lesg = lesg -> next;
				if ( lesg == 0 )
					break;
				else
					g = &(lesg -> data);
				}
			}
		if ( lesg == 0 )
			break;
		if ( !appearsIn( *g, found )) {
			found.prepend( *g );
			exps1 = exponentSum( *g, test );
			exps2 = exponentSum( *g, relator );
			if (( exps2 == 0 ) && ( exps1 != 0 )) {
				ans = false;
				break;
				}
			if (( exps2 != 0 ) && ( exps1 % exps2)) {
				ans = false;
				break;
				}
			if (( exps2 != 0 ) && ( exps1 == 0 ) && ( ratioDefined )) {
				ans = false;
				break;
				}
			if (( exps1 != 0) && ( exps2 != 0 )) {
				if ( ratioDefined ) {
					if ( ratio != exps1/exps2 ) {
						ans = false;
						break;
						}
					}
				else {
					ratio = exps1/exps2;
					ratioDefined = true;
					found.release();	// start all over
					lesg = test.first();
					g = &( lesg -> data );
					continue;
					}
				}
			}
		lesg = lesg -> next;
		g = &( lesg -> data );
		}

	if (( ratioDefined ) && ( ans == true )) {
		// search for a generator with nonzero exponent sum in the
		// relator, not appearing in the target subgroup, and
		// not appearing in test
		lesg = relator.first();
		while ( lesg != 0 ) {
			g = &( lesg -> data );
			if (( problemType == mp ) || ( problemType == rp )) {
			 // skip over the generators in
					// the target subgroup
				while ( appearsIn( *g , gensTargetSubgp )) {
					lesg = lesg -> next;
					if ( lesg == 0 )
						break;
					else
						g = &(lesg -> data);
					}
				}
			if ( lesg == 0 )
				break;
			if (( 0 != exponentSum( *g, relator )) &&
			  ( !appearsIn( *g, found ))) {
				ans = false;
				break;
				}
			lesg = lesg -> next;
			}
		}


#ifdef VERBOSE_MODE
 	cout << "\n\nFor the relator\n";
 	printRelator();
	cout << "Gens. target subgp\n";
	gensTargetSubgp.print();
 	cout << "and test word\n";
 	printTestWord();
 	if ( ans == true )
 		cout << "\nabTest() succeeds\n\n";
 	else
 		cout << "\nabTest() fails\n\n";
#endif
	return( ans );
}

void MagProb::printPinchType()
{
cout << "The type of pinch for the current problem is ";
switch ( pinchT ) {
    case none:
		cout << "none";
        break;
    case up:
		cout << "up";
        break;
    case down:
		cout << "down";
        break;
    }
	cout << endl;
}

void cyclicallyReduce( superWord &r ) {

	ListElt<superGen> *lesg1, *lesg2;
	superGen *g1, *g2;
	int x1, x2, x3;

	lesg1 = r.first();
	if ( lesg1 == 0 )
		return;
	lesg2 = lesg1 -> next;
	if ( lesg2 == 0 )
		return;
	while ( lesg2 -> next != 0 )
		lesg2 = lesg2 -> next;
	g1 = &( lesg1 -> data ); // first generator
	g2 = &( lesg2 -> data ); // last generator
	if ( !sameSubscripts( *g1, *g2 ))
		return;
	x1 = g1 -> exp();
	x2 = g2 -> exp();
	x3 = x1 + x2;
	if ( x3 != 0 )
		g2 -> assignExponent( x1 + x2 );
	else {	// remove the last generator
		r.reverse();
		r.del();
		r.reverse();
		}
	r.del(); // remove the first generator
}


bool MagProb::inputRelator()
{
	ListOfPowersOfNamedGens name;

	if ( !( name.userInput() ))
		return( false );
	superWordFromLPNG(name, listNames, relator);
	relator.freelyReduce();
	cyclicallyReduce( relator );
	return( true );
}

void MagProb::inputTest()
{
    ListOfPowersOfNamedGens name;

	name.userInput();
    superWordFromLPNG( name, listNames, test);
	test.freelyReduce();
}


void MagProb::rewriteRelator() // assume relatorLength > 1
{
    superGen g1Modified;   // modify the exponent of the stable letter
    superWord r1, r2;

	chooseStableAccomp( relator, outsideGens, stableLetter,
	accompanyingGen, problemType, gensTargetSubgp, exps1, exps2,
	stableInTargetSubgp );

    if ( !rewrittenRelator.isTrivial() )
        rewrittenRelator.release(); 
           // needed when at the root a second time

    if (exps1 == 0) 
        adjoinSubscriptsByConjugation( relator, stableLetter,
            rewrittenRelator );
    else {
           g1Modified = stableLetter;   // deep copy
           r1 = relator;        // deep copy
           adjoinRootOfGen( r1, stableLetter, exps2 );
                 // replace stableLetter by stableLetter^exps2
           g1Modified.assignExponent(-exps1);
           eltTransform( r1, accompanyingGen, g1Modified, r2);
			 // replace accompanyingGen by accompanyingGen*stableLetter^-exps1
		   r2.freelyReduce();
		   adjoinSubscriptsByConjugation
			   ( r2, g1Modified, rewrittenRelator);
		   }
	rewrittenRelator.freelyReduce();
}

void MagProb::rewriteTest()
{
    superGen g1Modified;
    superWord t1, t2;

    if ( !rewrittenTest.isTrivial() )
        rewrittenTest.release(); 
           // needed when at the root a second time

    if (exps1 == 0)
        adjoinSubscriptsByRestrictedConjugation
		  ( test, stableLetter, lmm, rewrittenTest );
    else {
        g1Modified = stableLetter;  // deep copy
        t1 = test;      // deep copy
        adjoinRootOfGen( t1, stableLetter, exps2 );
        g1Modified.assignExponent(-exps1);
        eltTransform( t1, accompanyingGen, g1Modified, t2 );
          // replace accompanyingGen by accompanyingGen*stableLetter^-exps1
        adjoinSubscriptsByRestrictedConjugation
                ( t2, g1Modified, lmm, rewrittenTest );
        }
}

void MagProb::createMinMaxSubscriptTable()
{
   ListElt<minMaxEntry> *lemme, *search;
   ListElt<superGen> *lesg;
   superGen g; // will run through the generators in relator
   superGen *h; // will run through the generators in rewrittenRelator
   int firstSubscript;
   bool found = false;
   minMaxEntry *pmme, mme;

   if ( !(lmm.isTrivial()) )
       lmm.release();
   lesg = rewrittenRelator.first();

   while (lesg != 0) {
        h = &(lesg -> data);
        firstSubscript = (h -> firstSubscript()) -> data;
        g = *h;        // a deep copy of h
        g.del(); // this advances the subscripts and creates a superGen
                        // in relator
        search = lmm.first();
        while (search != 0) { // see if we already have an entry
           pmme = &(search -> data);
           if ( sameSubscripts( pmme -> entry, g)) { // entry found
                found = true;
				if (firstSubscript < pmme -> small)
                   pmme -> small = firstSubscript; // record smaller element
                if (firstSubscript > pmme -> big)
                   pmme -> big = firstSubscript; // record bigger element
                }
           search = search -> next;
           }
        if ( found == false ) {
           mme.entry = g;   // deep copy
           mme.small = firstSubscript;
           mme.big = firstSubscript;
           lmm.prepend( mme );
           }
        found = false;
        lesg = lesg -> next;
        }       
}
                
void MagProb::printMinMaxSubscripts()
{
   ListElt<minMaxEntry> *lemme;
   minMaxEntry* mme;
    
   cout << "generator  minimum   maximum\n";
   lemme = lmm.first();
   while (lemme !=0) {
        mme = &(lemme -> data);
        (mme -> entry).print();
		cout << "         " <<
           mme -> small << "         " << mme -> big << endl;
        lemme = lemme -> next;
        }
}




int mustNotEliminate(int a, int b)
    // b is the exponent of the only generator in a relator
    // a is the exponent of this generator in the test word
{
    int absb, ret;

    if ((b == 1) || (b == -1))
        return (0);
    absb = (b < 0) ? -b : b;    // absb is the absolute value of b
    ret = a % absb;
    ret = (ret < 0) ? ret + absb : ret;
    return(ret);
}



void reduceOnceByPowerOfGen(superWord &test, const superGen &r)
    // assume that the word test is freely reduced and not trivial
{
    ListElt<superGen>* genp1, *genp0, *genp2; // current, previous and next
    int xp = r.exp();
    int testExp, residue;

    genp1 = test.first();

    if (sameSubscripts( genp1 -> data, r )) {
        testExp = (genp1 -> data).exp();
        residue = mustNotEliminate( testExp, xp );
        if (0 == residue)
            test.advance();  // kill the first generator;
        else
            (genp1 -> data).assignExponent(residue);
        }
    genp0 = genp1;
    genp1 = genp1 -> next;
	while (genp1 != 0) {
        if (sameSubscripts( genp1 -> data, r )) {
            testExp = (genp1 -> data).exp();
            residue = mustNotEliminate( testExp, xp );
            if ( residue == 0 ) { // kill genp1
                genp2 = genp1 -> next;
                genp0 -> next = genp2;
                delete(genp1);
                genp1 = genp2;
                }
            else {
                (genp1 -> data).assignExponent(residue);
                genp0 = genp1;
                genp1 = genp1 -> next;
                }
            }
        else {
            genp0 = genp1;
            genp1 = genp1 -> next;
            }
        }
    test.freelyReduce();
}

void reduceByPowerOfGen( superWord &test, const superGen &r)
{
   int l0, l2, l1;

   l1 = test.length();
   if ( l1 == 0 ) 
     return;
   do {
     reduceOnceByPowerOfGen( test, r);
     l2 = test.length();
     l0 = l1;
     l1 = l2;
   } while (( l1 != 0 ) && ( l1 < l0 ));
}

void MagProb::printInfo()
{
/*@rn
   ListElt<int>* lei = exponentsStableLetter.first();   

   cout << "\n\nChild number " << childNumber << ":\n";
   if ( relatorLength == 1 )
		cout << "The relator has length 1";
   cout << "Relator:\n";
   printRelator();
   cout << "Stable letter: ";
   printStableLetter();
   cout << endl;
   if ( !accompanyingGen.isTrivial() ) {
	 cout << "Accompanying generator: ";
     printAccompanyingGen();
   }
   else 
	 cout << "There is no accompanying generator";
   cout << endl;
   if (( relatorLength > 1 ) && ( !lmm.isTrivial() ))
            printMinMaxSubscripts();
   cout << "Test word:\n";
        printTestWord();
   if ( relatorLength > 1 ) {
		cout << "Rewritten relator:\n";
        printRewrittenRelator();
		cout << "Rewritten test word:\n";
		printRewrittenTestWord();}

   if ( !gensTargetSubgp.isTrivial() ) {
		cout << "Generators of the target subgroup:\n";
		gensTargetSubgp.print();
		}
	else
		cout << "The target subgroup is trivial\n";

   if ( !inheritedTarget.isTrivial() ) {
		cout << "Generators of the inherited target subgroup:\n";
		inheritedTarget.print();
		}
	else
		cout << "The inherited target subgroup is trivial\n";

   if ( !gensAssocSubgp.isTrivial() ) {
		cout << "Generators of the associated subgroup:\n";
		gensAssocSubgp.print();
		}
	else
		cout << "The associated subgroup is trivial\n";

   if ( lei != 0 ) {
		cout << "Exponents of the stable letter:\n";
        while ( lei ) {
			cout << lei -> data;
            if ( lei -> next )
				cout << ",";
            else
				cout << endl;
            lei = lei -> next;
            }
        }                       
        
   printPinchType();
   if ( stableInTargetSubgp )
		cout << "The stable letter is in the target subgp.\n";
   else
		cout << "The stable letter is not in the target subgp.\n";

   if ( problemType == wp )
		cout << "The problem is of type wp\n";
   if ( problemType == rp )
		cout << "The problem is of type rp\n";
   if ( problemType == mp )
		cout << "The problem is of type mp\n";
   cout << "leftExp and rightExp equal " << leftExp << ", "
     << rightExp << endl;
*/
}


class TreeEltMP{
public:
	MagProb data;

	TreeEltMP* nextSibling, *previousSibling, *parent, *firstChild;
	TreeEltMP() { nextSibling = 0; parent = 0; firstChild = 0;
				 previousSibling = 0;}

	bool input();
	void spawn();
	void defineGensTargetAssocSubgpsForChildren();
	void expand();
	TreeEltMP* firstLeaf();
	   // first leaf below given node
	TreeEltMP* nextLeaf( TreeEltMP *); // returns 0 for last leaf
	TreeEltMP* firstChildWithPotentialPinch();
	TreeEltMP* nextSiblingWithPotentialPinch();
	TreeEltMP* nextDesiredSibling();
	TreeEltMP* firstDesiredChild();
	void testFromChildren();
	bool testDecomposes();
	void adjoinInheritedToTargetsOfChildren();
	void prune();   // remove all leaves (thus creating new ones)

};

void TreeEltMP::prune()    // removes the leaves
{
	TreeEltMP* leaf, *temp, *prnt, *nxtsblng;

	leaf = firstLeaf();
	if ( leaf == 0 )
	  return;

	while ( leaf != 0 ) {
		temp = leaf;
		prnt = temp -> parent;
		nxtsblng = temp -> nextSibling;
		leaf = nextLeaf( leaf );
		prnt -> firstChild = nxtsblng;
		delete(temp);
		}
}



void maxIncreaseDecrease( TreeEltMP *pte, int &inc, int &dec )
	// gives a bound in inc on the number of pinches that can increase and
	// a bound in dec on the number of pinches that can decrease the
	// first subscript. Assume that the subscripts are within the bounds.
	// Assume at least two subscripts.

{
   MagProb *prob = &( pte -> data );
   superWord *w = &( prob -> test );
   TreeEltMP *ppte = pte -> parent;	// by assumption nonzero
   list<minMaxEntry> *lmme = &(( ppte -> data ).lmm );
   ListElt<minMaxEntry> *lemme;
   int incr, decr, difference, firstSubscript;
   int max, min;
   bool matchFound = false;
   ListElt<superGen> *lesg, *firstSG;
   superGen* g, h, *currentEntry; // h will be g without the first subscript
   minMaxEntry* mme;

   lemme = lmme -> first();
   firstSG = w -> first();
   lesg = firstSG;

   while (lemme != 0) {
		mme = &(lemme -> data);
		currentEntry = &(mme -> entry);
		max = mme -> big;
		min = mme -> small;
		while (lesg != 0) {  // search for a match of currentEntry with h
		   g = &(lesg -> data);
		   firstSubscript = (g -> firstSubscript()) -> data;
		   h = *g; // local deep copy
		   h.del();  // this removes the first subscript
		   if (sameSubscripts( *currentEntry, h)) {
				if (matchFound == false) {
				   matchFound = true;
				   incr = max - firstSubscript;
				   decr = firstSubscript - min;
				   }
				else {
				   if (max - firstSubscript < incr)
						incr = max - firstSubscript;
				   if (firstSubscript - min < decr)
						decr = firstSubscript - min;
				   }
				}
		   lesg = lesg -> next;
		   }
		lesg = firstSG;
		lemme = lemme -> next;
		}
   dec = ( decr < 0 ) ? 0 : decr; // to be changed: decr should not be < 0
   inc = ( incr < 0 ) ? 0 : incr;
}

TreeEltMP* TreeEltMP::firstChildWithPotentialPinch()
{
    MagProb *prob;
    TreeEltMP* pte = firstChild;

    while ( pte ) {
	prob = &( pte -> data );
	if ( prob -> pinchT != none )
	    break;
        pte = pte -> nextSibling;
        }
    return( pte );
}

TreeEltMP* TreeEltMP::firstDesiredChild()
{
	MagProb *prob = &data;
	ListElt<int> *lei;
    probType pt = prob -> problemType;
    bool sits = prob -> stableInTargetSubgp;

    if ( firstChild == 0 )
        return( 0 );

	if ( pt == mp ) {
        if ( sits ) 
			return( firstChild );
        else {
            if ( firstChild -> nextSibling == 0 ) {
                lei = ( prob -> exponentsStableLetter ).first();
                if ( lei -> data == 0 ) {
                    lei = lei -> next;
                    if ( lei -> data == 0 )
                        return( firstChild );
                    }
                }   
		    }
	    }

    if (( pt == wp ) && ( firstChild -> nextSibling == 0 ))
        return( firstChild );
	return( firstChildWithPotentialPinch() );

}

TreeEltMP* TreeEltMP::nextSiblingWithPotentialPinch()
{
    TreeEltMP* pte = nextSibling;
    MagProb *prob;

    while ( pte ) {
		prob = &( pte -> data );
		if ( prob -> pinchT != none )
			break;
		pte = pte -> nextSibling;
		}
	return( pte );
}

TreeEltMP* TreeEltMP::nextDesiredSibling()
{
    MagProb *pprob;

    if ( parent )
		pprob = &( parent -> data );
	else
		return( 0 );

	if (( pprob -> problemType == mp ) && ( pprob -> stableInTargetSubgp ))
		return( nextSibling );
	return( nextSiblingWithPotentialPinch() );
}



void conjugatesFromSubscripts( superWord &w, const superGen &conjugator,
    superWord &nw )     // it reverses the order
{
	int subscript;
    ListElt<superGen> *lesg;
    superGen *g, h;
    ListElt<int> *lei;

    lesg = w.first();
    if ( lesg == 0 )
        return;

    while ( lesg ) {
        g = &( lesg -> data );
        lei = g -> firstSubscript();
        subscript = lei -> data;
        g -> del();     // remove first subscript
        if ( subscript == 0 )
            nw.prepend( *g );
        else {
            h = conjugator; // deep local copy
            h.assignExponent( subscript );
            nw.prepend( h );
            nw.prepend( *g );
            h.assignExponent( -subscript );
            nw.prepend( h );
            }
        lesg = lesg -> next;
        }

}

void suppressRootOfGen( superWord &w, const superGen &g, int n)
        // replace g^n by g in the word w (assume divisibility)
{
   ListElt<superGen>* le = w.first();
   int exp;

   while (le != 0) {
        if (sameSubscripts( g, le -> data )) {
           exp = (le -> data).exp();
           exp /= n;    // divide the exponent by n
           (le -> data).assignExponent(exp);
           }
        le = le -> next;
        }
}


void TreeEltMP::testFromChildren() //
{

    TreeEltMP *cpte;
    MagProb *childProb;
    ListElt<superGen> *lesg;
    superGen *g, conj;
    superWord t1, t2;
    list<int>* pesl = &( data.exponentsStableLetter );
    ListElt<int>* lei;
    int exp;

    ( data.test ).release();	// release existing memory
    cpte = firstChild;

    lei = pesl -> first();
    while ( lei ) {
	 exp = lei -> data;
	 if ( exp ) {
	     conj = data.stableLetter;	// deep copy
	     conj.assignExponent( exp );
	     t1.prepend( conj );
	     }
	 if ( cpte ) {
	     childProb = &( cpte -> data );
 	     conjugatesFromSubscripts( childProb -> test,
	     data.stableLetter, t1 );
	     cpte = cpte -> nextSibling;
	     }
	 lei = lei -> next;
	 }

     t1.freelyReduce();
     t1.reverse();

     if ( ( data.accompanyingGen ).isTrivial() )
	 data.test = t1;     // deep copy
     else {
	 conj = data.stableLetter;  // deep copy
	 conj.assignExponent( data.exps1 );
	 eltTransform( t1, data.accompanyingGen, conj, t2 );
	 t2.freelyReduce();
	 suppressRootOfGen( t2, data.stableLetter, data.exps2 );
	 data.test = t2;    // deep copy
	 }

}


void TreeEltMP::defineGensTargetAssocSubgpsForChildren()
{

    ListElt<int>* lei;
    TreeEltMP* temp;
    MagProb *mpm;
    ListElt<minMaxEntry> *lemme;
    minMaxEntry *mme;
    superGen g;
    ListElt<superGen> *lesg;
    int count, cn, fsd, rex;
    superWord target, assoc;
    ListElt<int> *fs;
	bool sits = data.stableInTargetSubgp;

	target = data.gensTargetSubgp;  // deep copy

	if ( sits )
		removeGen( target, data.stableLetter );
	else {
		lesg = target.first();
		if ( lesg ) {
			temp = firstChild; // perhaps treated specially
			mpm = &( temp -> data );
			if ( mpm -> leftExp == 0 ) {
				g = lesg -> data; // deep copy
				g.adjoinSubscript( 0 );
				( mpm -> gensTargetSubgp ).prepend( g ); // cyclic subgp
				( mpm -> inheritedTarget ).prepend( g );
				mpm -> problemType = mp;
				}
			}
		}

	if ( sits )
		temp = firstChild;
	else
		temp = firstChildWithPotentialPinch();

	while ( temp != 0 ) {

	  mpm = &( temp -> data );

	  lesg = ( mpm -> test ).first();
	  while ( lesg ) {
		g = lesg -> data;  // deep copy
		g.del(); // remove first subscript
		if (( appearsIn( g, target )) && ( !appearsIn( lesg -> data,
		  mpm -> inheritedTarget )))
			( mpm -> inheritedTarget ).prepend( lesg -> data );
		lesg = lesg -> next;
		}

	  lemme = data.lmm.first();    // assume nonempty
	  while ( lemme != 0 ) {
		mme = &( lemme -> data );
		g = mme -> entry;	// deep copy
		for ( count = mme -> small; count <= mme -> big; ++count ) {
			if (( sits ) && ( appearsIn( g, target ))) {
				g.adjoinSubscript( count );
				if ( appearsIn( g, data.rewrittenRelator )) {
				  if ( !appearsIn( g, mpm -> inheritedTarget ))
					( mpm -> inheritedTarget ).prepend( g );
				  }
				g.del();	// remove subscript
				}
			if (( count < mme -> big ) && ((( sits )
			  && ( mpm -> rightExp < 0 )) || ( mpm -> pinchT == up ))) {
				  g.adjoinSubscript( count );
				  if ( !appearsIn( g, mpm -> gensTargetSubgp ))
					( mpm -> gensTargetSubgp ).prepend( g );
				  if ( !appearsIn( g, mpm -> gensAssocSubgp ))
					( mpm -> gensAssocSubgp ).prepend( g );
				  g.del();	// remove subscript
				  }
			if (( count > mme -> small ) && ((( sits )
			  && ( mpm -> rightExp > 0 )) || ( mpm -> pinchT == down ))) {
				  g.adjoinSubscript( count );
				  if ( !appearsIn( g, mpm -> gensTargetSubgp ))
					( mpm -> gensTargetSubgp ).prepend( g );
				  if ( !appearsIn( g, mpm -> gensAssocSubgp ))
					( mpm -> gensAssocSubgp ).prepend( g );
				  g.del();	// remove subscript
				  }
			}   // the for loop

		lemme = lemme -> next;
		}

	if ( sits ) {
		if (( mpm -> gensTargetSubgp ).isTrivial() )
			mpm -> problemType = wp;
		else 
			mpm -> problemType = mp; // might be reset to rp
		temp = temp -> nextSibling;
		}
	else {
		if (( mpm -> gensTargetSubgp ).isTrivial() )
			mpm -> problemType = wp;
		else
			mpm -> problemType = mp;
		temp = temp -> nextSiblingWithPotentialPinch();
		}
	}
}


void TreeEltMP::expand()
	// assume that relator, test, parent, relatorLength have been defined
	// assume that relatorLength > 1
    // define exps1, stableLetter, accompanyingGen,
    // exps2 if accompanyingGen is not trivial, rewrittenRelator, lmm,
    // rewrittenTest
{
    data.rewriteRelator();
        // it defines stableLetter, its exponent sum exps1, accompanyingGen
        // if accompanyingGen is not trivial it defines its exponentsum exps2
        // it defines rewrittenRelator
    data.createMinMaxSubscriptTable(); // it defines lmm
    data.rewriteTest();  // the test word is not the same among siblings
}




TreeEltMP* TreeEltMP::firstLeaf()
{
    TreeEltMP *temp2 = this;

    if ( temp2 == 0 ) return(0);
    if ( temp2 -> firstChild == 0 )
      return( 0 );
    while ( temp2 -> firstChild != 0 )
        temp2 = temp2 -> firstChild;
    return (temp2);
}

void TreeEltMP::adjoinInheritedToTargetsOfChildren()
{
	TreeEltMP *temp = firstChild;
	MagProb *prob;
	ListElt<superGen>* lesg;
	superGen *g;

	while (temp ) {
		prob = &( temp -> data );
		lesg = ( prob -> inheritedTarget ).first();
		if ( lesg )
			prob -> problemType = mp; // it may have been wp before
		while ( lesg ) {
			g = &( lesg -> data );
			if ( !appearsIn( *g, prob -> gensTargetSubgp ))
				( prob -> gensTargetSubgp ).prepend( *g );
			lesg = lesg -> next;
			}
		temp = temp -> nextSibling;
		}
}



class treeMP{
private:
	friend class treeIterator;
    TreeEltMP* h;  // the root
public:
    treeMP() { h = 0; }
    treeMP(TreeEltMP& te): h( &te ) {}	// planting the root te
    void plantRoot( TreeEltMP *temp ) { h = temp; }
    ~treeMP();
    TreeEltMP* root() { return (h); }
    void pruneBackToRoot();

};

TreeEltMP* TreeEltMP::nextLeaf( TreeEltMP *leaf1 )
    // returns 0 if we are at the last leaf
{
    TreeEltMP *temp2 = leaf1;

    if ( temp2 == 0 ) return(0);
    if ( parent == 0 ) return(0); // the root does not have a next leaf

    while (( temp2 -> nextSibling == 0 ) && ( temp2 != this ))  
         temp2 = temp2 -> parent;
    if (temp2 == this ) 
      return(0); // there are no more leaves
    temp2 = temp2 -> nextSibling;    // it must be nonzero
    if ( temp2 -> firstChild )
      temp2 = temp2 -> firstLeaf();
    return(temp2);
}


void treeMP::pruneBackToRoot()
{
	while ( h -> firstChild != 0 ) h -> prune();
}


treeMP::~treeMP()
{
	pruneBackToRoot();
	delete h;
	h = 0;

}

void TreeEltMP::spawn() // assume that rewrittenRelator has length > 1
// Assume that rewrittenTest is not a power of stableLetter
// It creates firstChild and all its siblings
// It creates a new relator and a new test in each child,
// It defines the list exponentsStableLetter
// Assume that rewrittenTest is nontrivial
{
   ListElt<superGen>* lesg; // will run down the word rewrittenTest
   superGen* g;  // g is the data in lesg
   MagProb* mpm, *ompm;
   superWord* newTest;
   TreeEltMP* temp, *oldTemp;
   superGen* stableL;
   int expStableL;
   ListElt<int>* lei;
   bool mustStartNewTest = true;
   bool startWithStable = false;
   int zero = 0;

   if ( !data.exponentsStableLetter.isTrivial() )
		data.exponentsStableLetter.release();
		   // needed when at the root a second time
   oldTemp = 0; // will signal first time
   stableL = &( data.stableLetter );

   lesg = ( data.rewrittenTest ).first();

		// We will break up rewrittenTest into subwords - the test words
		// of the children

   while (lesg != 0) {

	 g = &(lesg -> data);

     if ( sameSubscripts( *g, *stableL ) ) {

	expStableL = g -> exp();
	data.exponentsStableLetter.prepend( expStableL );
	mustStartNewTest = true;
	if ( oldTemp != 0 ) { // define pinchT
	  ompm = &( oldTemp -> data );
	  ( ompm -> test ).reverse();
	  ompm -> rightExp = expStableL;
	  if (( ompm -> leftExp < 0 ) && ( ompm -> rightExp > 0 ))
		  ompm -> pinchT = down;
	  else {
		if (( ompm -> leftExp > 0 ) && ( ompm -> rightExp < 0 ))
		  ompm -> pinchT = up;
		else
          ompm -> pinchT = none;
	    }
          }
	else // old Temp is 0
	  startWithStable = true;
	}

      else {  // g is not the stable letter

	if ( mustStartNewTest ) {

	  mustStartNewTest = false;
	  temp = new TreeEltMP;
	  if ( temp == 0 ) {
	    cerr << "\nOut of memory!\n";
	    exit(1);
	    }

	  temp -> parent = this;
	  mpm = &(temp -> data);

	  if ( oldTemp == 0 ) { // signals first time
	    mpm -> childNumber = 1;
	    firstChild = temp;
	    if ( !startWithStable ) {
	      data.exponentsStableLetter.prepend( zero );
	      mpm -> leftExp = 0;
	      }
	    else
	      mpm -> leftExp = expStableL;
	    }

	  else {  // oldTemp is the previous child
	    mpm -> childNumber = (( oldTemp -> data ).childNumber ) + 1;
	    oldTemp -> nextSibling = temp;
	    temp -> previousSibling = oldTemp;
	    mpm -> leftExp = expStableL;
		}

	  oldTemp = temp;
	  mpm -> relator = data.rewrittenRelator;    // deep copy
	  mpm -> relatorLength = ( data.rewrittenRelator ).length();
	  newTest = &( mpm -> test );
	  } // end of mustStartNewTest

	newTest -> prepend( *g );

	if ( lesg -> next == 0 ) {
	  data.exponentsStableLetter.prepend( zero );
	  mpm -> rightExp = 0;
	  mpm -> pinchT = none;
	  ( mpm -> test ).reverse();
	  }

	} // end of the case where g is not the stable letter

      lesg = lesg -> next;
      }

   data.exponentsStableLetter.reverse();

}

bool TreeEltMP::input()
{

#ifdef READ_LENGTHS

char c;

#endif

	data.childNumber = 0;
	data.leftExp = 0;
	data.rightExp = 0;
	data.problemType = wp;
	data.pinchT = none;
	data.stableInTargetSubgp = false;

#ifdef READ_LENGTHS

#ifdef INFILE

    if ( !( inFile >> len1 ))
      return( false );
    c = inFile.get();

#else

    cin >> len1;
    c = cin.get();

#endif

    if ( c != '\n' ) {
//@rn        cerr << "\nBad Input!\n";
	exit( 1 );
        }

#endif

	if ( !( data.inputRelator() ))
		return( false ); // define relator
	data.relatorLength = data.relator.length();  // define its length

#ifdef READ_LENGTHS

#ifdef INFILE

    inFile >> len2;
    c = inFile.get();

#else

    cin >> len2;
    c = cin.get();

#endif

    if ( c != '\n' ) {
//@rn        cerr << "\nBad Input!\n";
	exit( 1 );
        }

#endif

	data.inputTest();    // define test
	return( true );
}

void MagProb::defineOutsideGens()
    // generators that appear in the test word and not in r or target
{
	ListElt<superGen> *lesg = test.first();
	superGen *g;

	while ( lesg != 0 ) {
		g = &( lesg -> data );
		if ( ( !appearsIn( *g, relator )) &&
		    ( !appearsIn( *g, gensTargetSubgp )))
			outsideGens.prepend( *g );
		lesg = lesg -> next;
		}
	}

void amalgCycles( const superWord &r, superWord &t )
{
	ListElt<superGen> *lesg = r.first();
	superGen *g1, *g2, *g3;
	int x1, x2, x3, olt, nlt, x;

	g1 = &( lesg -> data );
	x1 = g1 -> exp();
	lesg = lesg -> next;
	g2 = &( lesg -> data );
	x2 = g2 -> exp();
	nlt = t.length();
	do {
		olt = nlt;
		lesg = t.first();
		while ( lesg != 0 ) {
			if ( sameSubscripts( *g2, lesg -> data )) {
				x = ( lesg -> data ).exp();
				if ( x % x2 == 0 ) { // then x is divisible by x2
					lesg -> data = *g1;	// deep copy
					( lesg -> data ).assignExponent( -x1*x/x2 );
					}
				}
			lesg = lesg -> next;
			}
		t.freelyReduce();
		nlt = t.length();
		if ( nlt == olt ) { // then no reduction has occurred
			lesg = t.first();
			while ( lesg != 0 ) {
				if ( sameSubscripts( *g1, lesg -> data )) {
					x = ( lesg -> data ).exp();
					if ( x % x1 == 0 ) { // then x is divisible by x1
						lesg -> data = *g2;	// deep copy
						( lesg -> data ).assignExponent( -x2*x/x1 );
						}
					}
				lesg = lesg -> next;
				}
			t.freelyReduce();
			nlt = t.length();
			}
		} while (( nlt < olt ) && ( nlt > 1));

}

void doAmalgCycles( MagProb *prob )
{
    ListElt< superGen > *lesg, *lesh;
    superGen *g, *h;
    int x1, x2, x3;


    amalgCycles( prob -> relator, prob -> test );
	// the relator defines a free product of a free group with
	// an amalgamated product of 2 cycles; prob -> test will have
	// been reduced by this function

#ifdef VERBOSE_MODE
	    cout << "\n\nAmalgamated product of two cycles:";
	    cout << "\nReduced test word:\n";
	    prob -> printTestWord();
	    cout << "Relator:\n";
	    prob -> printRelator();
		cout << "Generators for the target subgroup:\n";
	    ( prob -> gensTargetSubgp ).print();
	    cout << endl;
#endif

	    lesg = ( prob -> test ).first();
	    while ( lesg != 0 ) {
		g = &( lesg -> data );
		if (( !appearsIn( *g, prob -> gensTargetSubgp )) &&
		  ( appearsIn ( *g, prob -> relator ))) {
		    lesh = ( prob -> relator ).first();
		    h = &( lesh -> data );
		    if ( sameSubscripts( *g, *h )) {
			lesh = lesh -> next;
			h = &( lesh -> data );
			} // g,h are now the generators in r
		    x1 = g -> exp();
		    x2 = exponentSum( *g, prob -> relator );
		    if ( x1 % x2 ) {
		       // then g cannot be written as a power of h
			lesg = lesg -> next;
			continue; // with next generator in prob->test
			}
		    else {
			x3 = exponentSum( *h, prob -> relator );
			h -> assignExponent( -x3*x1/x2 );
			lesg -> data = *h; // deep copy
			break;
			}
		    }
		    lesg = lesg -> next;
		}

	    ( prob -> test ).freelyReduce();


#ifdef VERBOSE_MODE
	    cout << "\nThe test word becomes:\n";
		    prob -> printTestWord();
#endif

}



bool inSubgp( const superWord &test, const superWord &gensSubgp )
{
	ListElt<superGen> *lesg = test.first();
	superGen *g;

	while ( lesg ) {
	g = &( lesg -> data );
	if ( !appearsIn( *g, gensSubgp ))
		return( false );
	lesg = lesg -> next;
	}
	return( true );
}


class treeIterator {
private:
	treeMP *pt; // associated treeMP
	TreeEltMP *pte;  // current node being visited
	answerType answer;
	bool answerTold;
public:
	treeIterator(treeMP& t): pt( &t ), pte( t.h ), answer( maybe ),
		answerTold( false ) {}
	// create an iterator, with associated tree t, visiting the root
	TreeEltMP *nextSibling() { return pte -> nextSibling; }
	TreeEltMP *previousSibling() { return pte -> previousSibling; }
	TreeEltMP *parent() { return pte -> parent; }
	TreeEltMP *firstChild() { return pte -> firstChild; }
	TreeEltMP *currentNode() { return pte; }
	bool atRoot() { if ( !parent() ) return( true );
		else return ( false );}
	void printCurrentNode();
	void genProb();
	void tellYes() { cout << "Yes!\n"; }
	void tellNo() { cout << "No!\n"; }
	void tellAnswer() { if ( answer == yes ) tellYes();
		else tellNo(); answerTold = true; }
	bool replied() { if ( answerTold ) return( true );
		else return( false ); }
	void setAnswerForShortRel();
	void resetAnswerNode();
	void pruneBackToCurrentNode();


};

void treeIterator::pruneBackToCurrentNode() {

	while ( pte -> firstChild != 0 ) pte -> prune();
}


void treeIterator::printCurrentNode()
{
	MagProb *prob;

	if ( pte == 0 )
	return;

	prob  = &( pte -> data );
	prob -> printInfo();

}


void cycPermuteToBeginWith( superWord& w, const superGen& g1 )
	// conjugate so as to put g1 in first position
{
	ListElt<superGen> *lesg;
	superGen *g;
	superWord w1, w2, w3;

	lesg = w.first();
	g = &( lesg -> data );
	if ( sameSubscripts( lesg -> data, g1 ))
		return;

	while ( !sameSubscripts( lesg -> data, g1 )) {
		w1.prepend( *g );
		lesg = lesg -> next;
		if ( lesg == 0 )
			return; // then g1 is absent from w
		g = &( lesg -> data );
		}

	while (lesg ) {
		g = &( lesg -> data );
		w2.prepend( *g );
		lesg = lesg -> next;
		}

	lesg = w1.first();
	while ( lesg ) {
		g = &( lesg -> data );
		w3.prepend( *g );
		lesg = lesg -> next;
		}

	lesg = w2.first();
	while ( lesg ) {
		g = &( lesg -> data );
		w3.prepend( *g );
		lesg = lesg -> next;
		}


	w = w3;
}


bool testDecomp( const superWord &tau, const superWord *assoc,
	const superWord *inherited, superWord &tpart, superWord &apart ) {

	superWord tau_reversed;  // deep copy
	ListElt< superGen > *lesg = tau.first();
	superGen *g;

	while ( lesg ) {
		g = &( lesg -> data );
		tau_reversed.prepend( *g );
		lesg = lesg -> next;
		}

	lesg = tau_reversed.first();
	while ( lesg ) {
		g = &( lesg -> data);
//		if (( appearsIn( *g, *assoc )) && 
//		    ( !appearsIn( *g, *inherited ))) {
		if ( appearsIn( *g, *assoc )) {
			apart.prepend( *g );
			lesg = lesg -> next;
			}
		else {
		  tpart.prepend( *g );
		  lesg = lesg -> next;
		  while ( lesg ) {
		    g = &( lesg -> data );
		    if ( !appearsIn( *g, *inherited ))
		      return( false );
		  else 
		    tpart.prepend( *g );
		  lesg = lesg -> next;
		  }
		}
	}

	// If we get here, then the test word decomposes

	return( true );

}



bool TreeEltMP::testDecomposes()

	// We assume that there is a parent with problem type mp.
	// If the test word decomposes, then the test word of the
	// parent will be modified, as well as the test word of the
	// next sibling (we assume that there is a next sibling).

{
	MagProb *prob = &data;
	int re = prob -> rightExp;
	ListElt< superGen > *lesg = ( prob -> test ).first();
	superGen *g, h;
	superWord *assoc = &( prob -> gensAssocSubgp );
	superWord *inherited = &( prob -> inheritedTarget );
	superWord tpart, apart; // factors of the target subgroup
	TreeEltMP* npte = nextSibling;
	MagProb *nprob;
	TreeEltMP* ppte = parent;
	MagProb *pprob = &( ppte -> data );
	superWord *nextTest;
	TreeEltMP* temp, *temp1;
	MagProb *mpm, *mpm1;
	ListElt<int> *lei;
	int fs, chn, exp, count;
	list< int > newExps;

	if ( assoc -> isTrivial() )
	  return( true );

  #ifdef VERBOSE_MODE

	cout << "\nArrived in testDecomposes()\n" << flush;

  #endif

	if ( npte ) {
		nprob = &( npte -> data );
		nextTest =  &( nprob -> test );
		}

	if ( !testDecomp( prob -> test, assoc, inherited, tpart, apart ))
		return( false );

	if ( apart.isTrivial() )
		return( true );

	if ( tpart.isTrivial() )
		( prob -> test ).release(); // kill it
	else
		prob -> test = tpart;   // deep copy

	if ( re > 0 ) {
		lesg = apart.first();   // decrement subscripts
		while ( lesg ) {
			g = &( lesg -> data );
			lei = g -> firstSubscript();
			fs = lei -> data;
			--fs;
			g -> del();
			g -> adjoinSubscript( fs );
			lesg = lesg -> next;
			}
		}

	if (( re > 1 ) || (( re == 1 ) && ( npte == 0 ))) {
	 // then we must insert a new child

		temp = new TreeEltMP;
		if ( temp == 0 ) {
			cerr << "\nOut of memory!\n";
			exit(1);
			}

		temp -> parent = ppte;
		temp -> previousSibling = this;
		nextSibling = temp;
		temp -> nextSibling = npte;

		mpm = &(temp -> data);

		mpm -> rightExp = re - 1;
		mpm -> leftExp = 1;
		prob -> rightExp = 1;
		if ( npte )
			nprob -> leftExp = mpm -> rightExp;

		chn = prob -> childNumber;
		mpm -> childNumber = chn + 1;

		lei = ( pprob -> exponentsStableLetter ).first();
		count = 0;
		while ( lei ) {
			exp = lei -> data;
			if ( count != chn )
				newExps.prepend( exp );
			else {
				newExps.prepend( 1 );
				newExps.prepend( exp -1 );
				}
			++count;
			lei = lei -> next;
			}
		( pprob -> exponentsStableLetter ).release();
		lei = newExps.first();
		while ( lei ) {
			exp = lei -> data;
			( pprob -> exponentsStableLetter ).prepend( exp );
			lei = lei -> next;
			}
		temp1 = npte;
		while ( temp1 ) {
			mpm1 = &( temp1 -> data );
			++( mpm1 -> childNumber );
			temp1 = temp1 -> nextSibling;
		    }
		mpm -> pinchT = none;
		mpm -> relator = prob -> relator;   // deep copy
		mpm -> test = apart;	// deep copy
		mpm -> relatorLength = prob -> relatorLength;
		if ( re > 0 ) {
		  mpm -> gensAssocSubgp = prob -> gensAssocSubgp; // deep copy
		  mpm -> gensTargetSubgp = prob -> gensAssocSubgp; //deep copy
		}
		lesg = apart.first();
		while ( lesg ) {
		  g = &( lesg -> data );
		  h = *g; // deep copy
		  h.del();
		  if ( appearsIn( h, pprob -> gensTargetSubgp )) {
		      if ( !appearsIn( *g, mpm -> inheritedTarget )) 
			( mpm -> inheritedTarget ).prepend( *g );
		      if ( !appearsIn( *g, mpm -> gensTargetSubgp ))
		        ( mpm -> gensTargetSubgp ).prepend( *g );
		      }
		  lesg = lesg -> next;
		}
		if (( mpm -> gensTargetSubgp ).isTrivial() )
		  mpm -> problemType = wp;
		else
		  mpm -> problemType = mp;

	    }

	if ( re < 0 ) {
		lesg = apart.first();   // increment subscripts
		while ( lesg ) {
			g = &( lesg -> data );
			lei = g -> firstSubscript();
			fs = lei -> data;
			++fs;
			g -> del();
			g -> adjoinSubscript( fs );
			lesg = lesg -> next;
			}
		}

	if (( re < -1 ) || (( re == -1 ) && ( npte == 0 ))) {
	 // then we must insert a new child

		temp = new TreeEltMP;
		if ( temp == 0 ) {
		    cerr << "\nOut of memory!\n";
			exit(1);
		    }

		temp -> parent = ppte;
		temp -> previousSibling = this;
		nextSibling = temp;
		temp -> nextSibling = npte;

		mpm = &(temp -> data);

		mpm -> rightExp = re + 1;
		mpm -> leftExp = -1;
		prob -> rightExp = -1;
		if ( npte )
			nprob -> leftExp = mpm -> rightExp;

		chn = prob -> childNumber;
		mpm -> childNumber = chn + 1;

		lei = ( pprob -> exponentsStableLetter ).first();
		count = 0;
		while ( lei ) {
			exp = lei -> data;
			if ( count != chn )
				newExps.prepend( exp );
			else {
				newExps.prepend( -1 );
				newExps.prepend( exp + 1 );
				}
			++count;
			lei = lei -> next;
			}
		( pprob -> exponentsStableLetter ).release();
		lei = newExps.first();
		while ( lei ) {
			exp = lei -> data;
			( pprob -> exponentsStableLetter ).prepend( exp );
			lei = lei -> next;
			}

		temp1 = npte;
		while ( temp1 ) {
			mpm1 = &( temp1 -> data );
			++( mpm1 -> childNumber );
			temp1 = temp1 -> nextSibling;
			}

		mpm -> pinchT = none;
		mpm -> relator = prob -> relator;   // deep copy
		mpm -> test = apart;	// deep copy
		if ( re < 0 ) {
		  mpm -> gensAssocSubgp = prob -> gensAssocSubgp; // deep copy
		  mpm -> gensTargetSubgp = prob -> gensAssocSubgp; //deep copy
		}

		mpm -> relatorLength = prob -> relatorLength;
		mpm -> gensAssocSubgp = prob -> gensAssocSubgp; // deep copy

		lesg = apart.first();
		while ( lesg ) {
		  g = &( lesg -> data );
		  h = *g; // deep copy
		  h.del();
		  if ( appearsIn( h, pprob -> gensTargetSubgp )) {
		      if ( !appearsIn( *g, mpm -> inheritedTarget )) 
			( mpm -> inheritedTarget ).prepend( *g );
		      if ( !appearsIn( *g, mpm -> gensTargetSubgp ))
		        ( mpm -> gensTargetSubgp ).prepend( *g );
		      }
		  lesg = lesg -> next;
		}
		if (( mpm -> gensTargetSubgp ).isTrivial() )
		  mpm -> problemType = wp;
		else
		  mpm -> problemType = mp;


	}

	if (( re == 1 ) || ( re == -1 )) {
	// move generators; extend the inheritedTarget and target of mpm
        apart.reverse();
	    lesg = apart.first();
	    while ( lesg ) {
		    g = &( lesg -> data );
		    nextTest -> prepend( *g );
		    h = *g; // deep copy
		    h.del();
		    if ( appearsIn( h, pprob -> gensTargetSubgp )) {
		      if ( !appearsIn( *g, nprob -> inheritedTarget )) 
			( nprob -> inheritedTarget ).prepend( *g );
		      if ( !appearsIn( *g, nprob -> gensTargetSubgp ))
		        ( nprob -> gensTargetSubgp ).prepend( *g );
		      }
		    lesg = lesg -> next;
		    }
	    }

	return( true );

}



void treeIterator::setAnswerForShortRel()
{
	MagProb *prob = &( pte -> data );
	int relLen= prob -> relatorLength;
	probType pt = prob -> problemType;
	ListElt< superGen > *lesg;
	TreeEltMP* nds = pte -> nextDesiredSibling();
	TreeEltMP* p = parent();
	bool spits;

    if ( p )
        spits = ( p -> data ).stableInTargetSubgp;

	if ( relLen == 1 ) {
		lesg = ( prob -> relator ).first();
		reduceByPowerOfGen( prob -> test, lesg -> data );
		}

	if ( relLen == 2 ) {
		doAmalgCycles( prob );
		}


#ifdef VERBOSE_MODE
	cout << "\nThe test word reduces to:\n";
		prob -> printTestWord();
#endif

	if (( prob -> test ).isTrivial() )
		answer = yes;

	else {

		if ( pt == wp )
			answer = no;
		else { // then pt must be mp
			if ( inSubgp( prob -> test, prob -> gensTargetSubgp )) {
				if ( nds ) {
					if ( spits ) {
						if ( pte -> testDecomposes() ) // sits is true
							answer = yes;
						else
							answer = no;
						}
					else
					   answer = yes; //
					}
				else
					answer = yes;
				}
			else
				answer = no;
			}
		} // end of case of nontrivial test word
}

void treeIterator::resetAnswerNode() 
  // the answer is yes for rp if the test word is reduced
  // the answer is yes for mp if the test word belongs to the target subgp
  // Do as little as possible
{
	MagProb *prob = &( pte -> data );
	int relatorLength;
	ListElt< superGen > *lesg;
	TreeEltMP* p = parent();
    TreeEltMP *fdc;
	probType tpp;
	probType pt = prob -> problemType;
	bool sits;
	bool spits;
	TreeEltMP* ns = nextSibling();
	TreeEltMP* nds = pte -> nextDesiredSibling();

	if ( p ) {
		tpp = ( p -> data ).problemType;
        spits = ( p -> data ).stableInTargetSubgp;
		}

	switch( answer ) {

	case no:

		if ( atRoot() ) {
			tellAnswer();
			return;
			}

		switch( tpp ) {
			case wp:
				if ( nds ) {
					pte = nds;
					answer = maybe;
					}
				else {
					pte = p;
					answer = no;
					}
				return;
			case rp:
				if ( nds ) {
					pte = nds;
					answer = maybe;
					}
				else {
					pte = p;
					( pte -> data ).problemType = mp;
					pte -> adjoinInheritedToTargetsOfChildren();
					pte = pte -> firstChild;
					answer = maybe;  // reduction is complete
					}
				return;
			case mp:
				if ( spits ) {
					pte = p;
					pte -> testFromChildren();
					answer = no;
					}
				else {
					if ( nds ) {
						pte = nds;
						answer = maybe;
						}
					else {
						pte = p;
						pte -> testFromChildren();
						answer = no;
						}
					}
				return;
			}  // end of switch( tpp )

		break;

	case yes:

		if ( atRoot() ) {
			tellAnswer();
			return;
			}

		switch( tpp ) {
			case wp:
			case rp:
				pte = p;
				pte -> testFromChildren();
				answer = maybe;
				return;
			case mp:
				if (( ns ) && ( spits )) {
					if ( pte -> testDecomposes() ) {

						pte = nextSibling(); // nextSibling may have changed
						answer = maybe;
						}
					else
						answer = no;
					}
				else {
					if ( !spits ) {
						if (( prob -> leftExp == 0 ) &&
						  ( prob -> rightExp == 0 )) {
							pte = p;
							pte -> testFromChildren();
							answer = yes;
							}
						else {
							pte = p;
							pte -> testFromChildren();
							answer = maybe;
							}
						}
					else { // last child
						pte = p;
						pte -> testFromChildren();
						answer = yes;
						}
					}
				return;
			}

		break;

	case maybe:

		if (( prob -> test ).isTrivial() ) {
			answer = yes;
			return;
			}

		if ( !prob -> abTest() ) {
			answer = no;
			return;
			}

		switch( pt ) {

			case mp:
			  if ( inSubgp( prob -> test, prob -> gensTargetSubgp )) {
				  answer = yes;
				  return;
				  }
			  prob -> defineOutsideGens();
			  pte -> expand();
			  sits = prob -> stableInTargetSubgp;
			  if ( !sits ) {
				lesg = ( prob -> gensTargetSubgp ).first();
				cycPermuteToBeginWith( prob -> relator,lesg -> data );
				}
			  pruneBackToCurrentNode();
			  pte -> spawn();
			  pte -> defineGensTargetAssocSubgpsForChildren();
				// the problemType may have changed to rp
			  fdc = pte -> firstDesiredChild();
			  if ( fdc ) {
				  pte = fdc;
				  return;
				  }
			  else {
				  if ( prob -> problemType == rp ) {
					  prob -> problemType = mp;
					  pte -> adjoinInheritedToTargetsOfChildren();
					  fdc = pte -> firstDesiredChild();
					  pte = fdc;
					  }
				  else
					  answer = no;
				  return;
				  }

			case rp: // we can only get here by coming up after reduction
			  if ( inSubgp( prob -> test, prob -> gensTargetSubgp )) {
				  answer = yes;
				  return;
				  }

                          prob -> defineOutsideGens();
			  pte -> expand();
			  pruneBackToCurrentNode();
			  pte -> spawn();
			  pte -> defineGensTargetAssocSubgpsForChildren();
			  fdc = pte -> firstDesiredChild();
			  if ( fdc )
				  pte = fdc;
			  else {
				  prob -> problemType = mp;
				  pte -> adjoinInheritedToTargetsOfChildren();
				  pte = pte -> firstChild;
				  }
			  break;
			case wp:
			  prob -> defineOutsideGens();
			  pte -> expand();
			  pruneBackToCurrentNode();
			  pte -> spawn();
			  pte -> defineGensTargetAssocSubgpsForChildren();
			  fdc = pte -> firstDesiredChild();
			  if ( fdc )
				  pte = fdc;
			  else
				  answer = no;

			} // end of switch( pt )

		}    // end of switch( answer )

}

void treeIterator::genProb() // treats the problem at the currentNode.
{
	MagProb *prob = &( pte -> data );
	bool beenAtRoot = false;
	int relLen = prob -> relatorLength;

  #ifdef VERBOSE_MODE

	TreeEltMP *ppte = pte -> parent;
	TreeEltMP *npte = pte -> nextSibling;
	cout << "\nAt the beginning of genProb() the answer and node are:\n";
	switch( answer ) {
	case no: cout << "\nNo!"; break;
	case yes: cout << "\nYes!"; break;
	case maybe: cout << "\nMaybe!"; break;
	}
	printCurrentNode();
	if ( ppte ) {
		cout << "\nand the parent node is:";
		( ppte -> data ).printInfo();
		}

  #endif

	if ( atRoot() ) {
		if (( prob -> test ).isTrivial()) {
			answer = yes;
			tellAnswer();
			return;
			}
		if ((( prob -> relator ).isTrivial() ) ||
		  ( answer == no )) {
			answer = no;
			tellAnswer();
			return;
			}
		if ( beenAtRoot )
			pt -> pruneBackToRoot();
		beenAtRoot = true;
		prob -> problemType = wp;
		answer = maybe;
		}

	if ( relLen <= 2 )
		setAnswerForShortRel();
	resetAnswerNode();

}


void doTree( TreeEltMP& root )
{
	treeMP probTree( root );
	treeIterator ti( probTree );

	do {
	    ti.genProb(); // at the current node (initially the root)
	    } while ( !ti.replied() );

}


bool treatRelatorTestWord()
{
	TreeEltMP root;

	if ( root.input() ) {

#ifdef READ_LENGTHS

//@rn        cout << "\nThe relator and test word have lengths " <<
//@rn            len1 << ", " << len2 << endl;

        if (( len1 > maxLen1 ) || ( len2 > maxLen2 )) 
            return( true );


#endif

		doTree( root );
		return( true );
		}
	else
		return( false );

}

main()
{
	int pairCount = 0;

	do {
		++pairCount;
//@rn		cout << "Pair number " << pairCount << ": ";
		} while ( treatRelatorTestWord() );

//@rn	cout << "Done!\n";
	return( 0 );
}