File: tietze.c

package info (click to toggle)
gap 4r4p12-2
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 29,584 kB
  • ctags: 7,113
  • sloc: ansic: 98,786; sh: 3,299; perl: 2,263; makefile: 498; asm: 63; awk: 6
file content (1766 lines) | stat: -rw-r--r-- 66,402 bytes parent folder | download | duplicates (4)
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
/****************************************************************************
**
*W  tietze.c                    GAP source                       Frank Celler
*W                                                           & Volkmar Felsch
**
*H  @(#)$Id: tietze.c,v 4.30 2002/04/15 10:04:01 sal Exp $
**
*Y  Copyright 1990-1992,  Lehrstuhl D fuer Mathematik,  RWTH Aachen,  Germany
*Y  (C) 1998 School Math and Comp. Sci., University of St.  Andrews, Scotland
*Y  Copyright (C) 2002 The GAP Group
**
**  This file contains the functions for computing with finite presentations.
*/
#include        "system.h"              /* system dependent part           */

const char * Revision_tietze_c = 
  "@(#)$Id: tietze.c,v 4.30 2002/04/15 10:04:01 sal Exp $";

#include        "gasman.h"              /* garbage collector               */
#include        "objects.h"             /* objects                         */
#include        "scanner.h"             /* scanner                         */

#include        "gap.h"                 /* error handling, initialisation  */
#include        "calls.h"               /* generic call mechanism          */
#include        "gvars.h"               /* global variables                */

#include        "bool.h"                /* booleans                        */

#include        "records.h"             /* generic records                 */
#include        "precord.h"             /* plain records                   */

#include        "lists.h"               /* generic lists                   */
#include        "plist.h"               /* plain lists                     */
#include        "string.h"              /* strings                         */

#define INCLUDE_DECLARATION_PART
#include        "tietze.h"              /* tietze helper functions         */
#undef  INCLUDE_DECLARATION_PART


/****************************************************************************
**

*V  TZ_SOMETHING  . . . . . . defining some constants for the Tietze routines
*/
#define TZ_NUMGENS               1
#define TZ_NUMRELS               2
#define TZ_TOTAL                 3
#define TZ_GENERATORS            4
#define TZ_INVERSES              5
#define TZ_RELATORS              6
#define TZ_LENGTHS               7
#define TZ_FLAGS                 8
#define TZ_FREEGENS              9
#define TZ_LENGTHTIETZE         20


/****************************************************************************
**

*F  CheckTietzeStack( <tietze>, <ptTietze> )
*/
void CheckTietzeStack (
    Obj                 tietze,
    Obj * *             ptTietze )
{
    /*  check the Tietze stack                                             */
    if ( ! IS_PLIST(tietze) ) {
        ErrorQuit( "<tietze> must be a plain list (not a %s)",
                   (Int)TNAM_OBJ(tietze), 0L );
        return;
    }
    if ( LEN_PLIST(tietze) != TZ_LENGTHTIETZE ) {
        ErrorQuit( "<tietze> must have length %d (not %d)",
                   (Int)TZ_LENGTHTIETZE, (Int)LEN_PLIST(tietze) );
        return;
    }
    *ptTietze = ADDR_OBJ(tietze);
}


/****************************************************************************
**
*F  CheckTietzeRelators( <ptTietze>, <rels>, <ptRels>, <numrels> )
*/
void CheckTietzeRelators (
    Obj *               ptTietze,
    Obj *               rels,
    Obj * *             ptRels,
    Int *              numrels )
{
    *rels    = ptTietze[TZ_RELATORS];
    *numrels = INT_INTOBJ(ptTietze[TZ_NUMRELS]);
    if ( *rels == 0 || ! IS_PLIST(*rels) || LEN_PLIST(*rels) != *numrels ) {
        ErrorQuit( "invalid Tietze relators list", 0L, 0L );
        return;
    }
    *ptRels = ADDR_OBJ(*rels);
}


/****************************************************************************
**
*F  CheckTietzeInverses( <ptTietze>, <invs>, <ptInvs>, <numgens> )
*/
void CheckTietzeInverses (
    Obj *               ptTietze,
    Obj *               invs,
    Obj * *             ptInvs,
    Int *              numgens )
{
    /* get and check the Tietze inverses list                              */
    *invs    = ptTietze[TZ_INVERSES];
    *numgens = INT_INTOBJ(ptTietze[TZ_NUMGENS]);
    if ( *invs==0 || !IS_PLIST(*invs) || LEN_PLIST(*invs)!=2*(*numgens)+1 ) {
        ErrorQuit( "invalid Tietze inverses list", 0L, 0L );
        return;
    }
    *ptInvs = ADDR_OBJ(*invs) + (*numgens+1);
}


/****************************************************************************
**
*F  CheckTietzeLengths( <ptTietze>, <numrels>, <lens>, <ptLens> )
*/
void CheckTietzeLengths (
    Obj *               ptTietze,
    Int                 numrels,
    Obj *               lens,
    Obj * *             ptLens )
{
    /*  Get and check the Tietze lengths list                              */
    *lens = ptTietze[TZ_LENGTHS];
    if ( *lens == 0 || ! IS_PLIST(*lens) || LEN_PLIST(*lens) != numrels ) {
        ErrorQuit( "invalid Tietze lengths list", 0L, 0L );
        return;
    }
    *ptLens = ADDR_OBJ(*lens);
}


/****************************************************************************
**
*F  CheckTietzeFlags( <ptTietze>, <numrels>, <flags>, <ptFlags> )
*/
void CheckTietzeFlags (
    Obj *               ptTietze,
    Int                 numrels,
    Obj *               flags,
    Obj * *             ptFlags )
{
    /* get and check the Tietze flags list                                 */
    *flags = ptTietze[TZ_FLAGS];
    if ( *flags==0 || ! IS_PLIST(*flags) || LEN_PLIST(*flags)!=numrels ) {
        ErrorQuit( "invalid Tietze flags list", 0L, 0L );
        return;
    }
    *ptFlags = ADDR_OBJ(*flags);
}


/****************************************************************************
**
*F  CheckTietzeRelLengths( <ptTietze>, <ptRels>, <ptLens>, <nrels>, <total> )
*/
void CheckTietzeRelLengths (
    Obj *               ptTietze,
    Obj *               ptRels,
    Obj *               ptLens,
    Int                 numrels,
    Int  *              total )
{
    Int                i;

    /* Check list <lens> to contain the relator lengths                 */
    *total = 0;
    for ( i = 1;  i <= numrels;  i++ ) {
        if ( ptRels[i] == 0
          || ! IS_PLIST(ptRels[i])
          || INT_INTOBJ(ptLens[i]) != LEN_PLIST(ptRels[i]) )
        {
            ErrorQuit( "inconsistent Tietze lengths list", 0L, 0L );
            return;
        }
        *total += INT_INTOBJ(ptLens[i]);
    }
    if ( *total != INT_INTOBJ(ptTietze[TZ_TOTAL]) ) {
        ErrorQuit( "inconsistent total length", 0L, 0L );
        return;
    }
}


/****************************************************************************
**

*F  FuncTzSortC( <self>, <stack> )  . . . . . . . sort the relators by length
*/
Obj FuncTzSortC (
    Obj                 self,
    Obj                 tietze )
{
    Obj *               ptTietze;       /* pointer to the Tietze stack     */
    Obj                 rels;           /* relators list                   */
    Obj *               ptRels  ;       /* pointer to this list            */
    Obj                 lens;           /* lengths list                    */
    Obj *               ptLens;         /* pointer to this list            */
    Obj                 flags;          /* handle of the flags list        */
    Obj *               ptFlags;        /* pointer to this list            */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 i, h, k;        /* loop variables                  */
    Obj                 rel, len, flag; /* list entries                    */
    Int                 total;

    /* check the Tietze stack                                              */
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze lengths list                               */
    CheckTietzeLengths( ptTietze, numrels, &lens, &ptLens );

    /* get and check the Tietze flags list                                 */
    CheckTietzeFlags( ptTietze, numrels, &flags, &ptFlags );

    /* check list <lens> to contain the relator lengths                    */
    CheckTietzeRelLengths( ptTietze, ptRels, ptLens, numrels, &total );

    /* sort the list                                                       */
    h = 1;
    while ( 9 * h + 4 < numrels )
        h = 3 * h + 1;
    while ( 0 < h ) {
        for ( i = h + 1; i <= numrels; i++ ) {
            rel = ptRels[i];  len = ptLens[i];  flag = ptFlags[i];
            k = i;
            if ( INT_INTOBJ(len) ) {
                while ( h < k
                  && ( !INT_INTOBJ(ptLens[k-h])
                     || len < ptLens[k-h]
                     || (len == ptLens[k-h] && flag > ptFlags[k-h])))
                {
                    ptRels[k] = ptRels[k-h];
                    ptLens[k] = ptLens[k-h];
                    ptFlags[k] = ptFlags[k-h];
                    k = k - h;
                }
            }
            ptRels[k] = rel;  ptLens[k] = len;  ptFlags[k] = flag;
        }
        h = h / 3;
    }
    for ( i = numrels;  i > 0;  i-- ) {
        if ( INT_INTOBJ(ptLens[i]) )
            break;
    }
    if ( i < numrels ) {
        SET_LEN_PLIST( rels,  i );  SHRINK_PLIST( rels,  i );
        SET_LEN_PLIST( lens,  i );  SHRINK_PLIST( lens,  i );
        SET_LEN_PLIST( flags, i );  SHRINK_PLIST( flags, i );
        ptTietze[TZ_NUMRELS] = INTOBJ_INT(i);
        CHANGED_BAG(tietze);
    }

    return 0;
}


/****************************************************************************
**
*F  FuncTzRenumberGens( <self>, <stack> ) . .  renumber the Tietze generators
*/
Obj FuncTzRenumberGens (
    Obj                 self,
    Obj                 tietze )
{
    Obj *               ptTietze;       /* pointer to this stack           */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 invs;           /* handle of the inverses list     */
    Obj *               ptInvs;         /* pointer to this list            */
    Obj *               ptRel;          /* pointer to the ith relator      */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 old;            /* generator or inverse            */
    Int                 leng;           /* relator length                  */
    Int                 i, j;           /* loop variables                  */

    /* check the Tietze stack                                              */
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze inverses list                              */
    CheckTietzeInverses( ptTietze, &invs, &ptInvs, &numgens );

    /*  Loop over all relators and replace the occurring generators        */
    for ( i = 1;  i <= numrels;  i++ ) {
        ptRel = ADDR_OBJ( ptRels[i] );
        leng  = LEN_PLIST( ptRels[i] );

        /* run through the relator and replace the occurring generators    */
        for ( j = 1;  j <= leng;  j++ ) {
            old = INT_INTOBJ( ptRel[j] );
            if ( old < -numgens || numgens < old || old == 0 ) {
                ErrorQuit( "gen no. %d in rel no. %d out of range", j,i );
                return 0;
            }
            ptRel[j] = ptInvs[-old];
        }
    }

    return 0;
}


/****************************************************************************
**
*F  FuncTzReplaceGens( <self>, <stack> )  replace Tietze generators by others
*/
Obj FuncTzReplaceGens (
    Obj                 self,
    Obj                 tietze )
{
    Obj *               ptTietze;       /* pointer to this stack           */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 lens;           /* handle of the lengths list      */
    Obj *               ptLens;         /* pointer to this list            */
    Obj                 flags;          /* handle of the flags list        */
    Obj *               ptFlags;        /* pointer to this list            */
    Obj                 invs;           /* handle of the inverses list     */
    Obj *               ptInvs;         /* pointer to this list            */
    Obj                 rel;            /* handle of a relator             */
    Obj *               ptRel;          /* pointer to this relator         */
    Obj *               pt1;            /* pointer to a relator            */
    Obj *               pt2;            /* pointer to a relator            */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 total;          /* total length of relators        */
    Int                 old, new;       /* generators or inverses          */
    Int                 leng, reduced;  /* relator lengths                 */
    Int                 altered;        /* flag                            */
    Int                 i, j;           /* loop variables                  */

    /* check the Tietze stack                                              */
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze lengths list                               */
    CheckTietzeLengths( ptTietze, numrels, &lens, &ptLens );

    /* check list <lens> to contain the relator lengths                    */
    CheckTietzeRelLengths( ptTietze, ptRels, ptLens, numrels, &total );

    /* get and check the Tietze flags list                                 */
    CheckTietzeFlags( ptTietze, numrels, &flags, &ptFlags );

    /* get and check the Tietze inverses list                              */
    CheckTietzeInverses( ptTietze, &invs, &ptInvs, &numgens );

    /* loop over all relators                                              */
    for ( i = 1; i <= numrels; i++ ) {
        rel = ptRels[i];
        pt2 = ptRel = ADDR_OBJ( rel );
        leng = INT_INTOBJ( ptLens[i] );
        altered = 0;

        /* don't change a square relator defining a valid involution       */
        if ( INT_INTOBJ( ptFlags[i] ) == 3 && leng == 2 &&
            ptRel[1] == ptInvs[-INT_INTOBJ(ptRel[1])] ) {
            continue;  /*  loop over i  */
        }

        /* run through the relator and replace the occurring generators    */
        for ( j = 1; j <= leng; j++ ) {

            old = INT_INTOBJ( ptRel[j] );
            if ( old < -numgens || numgens < old || old == 0 ) {
                ErrorQuit( "gen no. %d in rel no. %d out of range",
                           (Int)j, (Int)i );
                return 0;
            }

            new = INT_INTOBJ( ptInvs[-old] );
            if ( ! new ) {
                altered = 1;
                continue;  /*  loop over j  */
            }

            if ( pt2 > ptRel && *pt2 == ptInvs[new] ) {
                altered = 1;
                --pt2;
            }
            else {
                if ( new != old )  { altered = 1; }
                *++pt2 = INTOBJ_INT( new );
            }
        }

        if ( ! altered )  {
            continue; /*  loop over i  */
        }

        /* now cyclically reduce the relator                               */
        pt1 = ++ptRel;
        while ( pt1 < pt2 && *pt1 == ptInvs[INT_INTOBJ(*pt2)] ) {
            ++pt1;  --pt2;
        }
        if ( ptRel < pt1 ) {
            while ( pt1 <= pt2 )  { *ptRel++ = *pt1++; }
            pt2 = --ptRel;
        }

        /* resize the resulting relator, if necessary                      */
        ptRel = ADDR_OBJ( rel );
        reduced = pt2 - ptRel;
        if ( reduced < leng ) {
            SET_LEN_PLIST( rel, reduced );
            ptLens[i] = INTOBJ_INT( reduced );
            total = total - leng + reduced;
            SHRINK_PLIST( rel, reduced );
            CHANGED_BAG(rels);
            ptRels  = ADDR_OBJ( rels );
            ptLens  = ADDR_OBJ( lens );
            ptFlags = ADDR_OBJ( flags );
            ptInvs  = ADDR_OBJ( invs ) + (numgens + 1);
        }

        /*  Redefine the corresponding search flag                         */
        ADDR_OBJ( flags )[i] = INTOBJ_INT( 1 );
    }
    ptTietze = ADDR_OBJ( tietze );
    ptTietze[TZ_TOTAL] = INTOBJ_INT( total );

    return 0;
}


/****************************************************************************
**
*F  FuncTzSubstituteGen( <self>, <stack>, <gennum>, <word> )
*/
Obj FuncTzSubstituteGen (
    Obj                 self,
    Obj                 tietze,
    Obj                 gennum,
    Obj                 word )
{
    Obj *               ptTietze;       /* pointer to this stack           */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 lens;           /* handle of the lengths list      */
    Obj *               ptLens;         /* pointer to this list            */
    Obj                 flags;          /* handle of the flags list        */
    Obj *               ptFlags;        /* pointer to this list            */
    Obj                 invs;           /* handle of the inverses list     */
    Obj *               ptInvs;         /* pointer to this list            */
    Obj *               ptWrd;          /* pointer to this word            */
    Obj                 iwrd;           /* handle of the inverse word      */
    Obj *               ptIwrd;         /* pointer to this word            */
    Obj                 new;            /* handle of a modified relator    */
    Obj *               ptNew;          /* pointer to this relator         */
    Obj                 rel;            /* handle of a relator             */
    Obj *               ptRel;          /* pointer to this relator         */
    Obj *               pt1;            /* pointer to a relator            */
    Obj *               pt2;            /* pointer to a relator            */
    Obj *               pt3;            /* pointer to a relator            */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 total;          /* total length of relators        */
    Int                 given;          /* given generator and inverse     */
    Int                 gen, ginv;      /* given generator and inverse     */
    Int                 next;           /* generator or inverse            */
    Int                 leng, newleng;  /* relator lengths                 */
    Int                 wleng;          /* length of the replacing word    */
    Int                 occ;            /* number of occurrences           */
    Int                 i, j;           /* loop variables                  */

    /* check the Tietze stack                                              */
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze lengths list                               */
    CheckTietzeLengths( ptTietze, numrels, &lens, &ptLens );

    /* get and check the Tietze flags list                                 */
    CheckTietzeFlags( ptTietze, numrels, &flags, &ptFlags );

    /* get and check the Tietze inverses list                              */
    CheckTietzeInverses( ptTietze, &invs, &ptInvs, &numgens );

    /* check the second argument (generator number)                        */
    if ( ! IS_INTOBJ(gennum) ) {
        ErrorQuit( "<gennum> must be an integer", 0L, 0L );
        return 0;
    }
    given = INT_INTOBJ(gennum);
    gen   = ( given > 0 ) ? given : -given;
    if ( gen <= 0 || numgens < gen ) {
        ErrorQuit( "generator number %d out of range", (Int)gen, 0L );
        return 0;
    }
    ginv = INT_INTOBJ(ptInvs[gen]);

    /* check the third argument (replacing word)                           */
    if ( ! IS_PLIST(word) ) {
        ErrorQuit( "invalid replacing word", 0L, 0L );
        return 0;
    }
    ptWrd = ADDR_OBJ(word);
    wleng = LEN_PLIST(word);
    for ( i = 1;  i <= wleng;  i++ ) {
        next = INT_INTOBJ( ptWrd[i] );
        if ( next < -numgens || next == 0 || next > numgens ) {
            ErrorQuit( "entry [%d] of <Tietze word> out of range",
                       (Int)i, 0L );
            return 0;
        }
    }

    /* check list <lens> to contain the relator lengths                    */
    CheckTietzeRelLengths( ptTietze, ptRels, ptLens, numrels, &total );

    /* allocate a bag for the inverse of the replacing word                */
    iwrd   = NEW_PLIST( T_PLIST, wleng );
    ptRels = ADDR_OBJ( rels );
    ptLens = ADDR_OBJ( lens );
    ptInvs = ADDR_OBJ( invs ) + (numgens + 1);
    ptWrd  = ADDR_OBJ( word );
    ptIwrd = ADDR_OBJ( iwrd );

    /* invert the replacing word                                           */
    SET_LEN_PLIST( iwrd, wleng );
    pt1 = ptWrd;
    pt2 = ptIwrd + wleng;
    while ( pt2 > ptIwrd ) {
        *pt2-- = ptInvs[INT_INTOBJ(*++pt1)];
    }
    if ( given < 0 ) {
        new = word;  word = iwrd;  iwrd = new;
        ptWrd = ADDR_OBJ(word);  ptIwrd = ADDR_OBJ(iwrd);
    }

    /* loop over all relators                                              */
    for ( i = 1;  i <= numrels;  i++ ) {
        rel = ptRels[i];
        ptRel = ADDR_OBJ(rel);
        leng = INT_INTOBJ(ptLens[i]);
        if ( leng == 0 )  { 
            continue;
        }

        /* run through the relator and count the occurrences of gen        */
        occ = 0;
        for ( j = 1;  j <= leng;  j++ ) {
            next = INT_INTOBJ( ptRel[j] );
            if ( next < -numgens || numgens < next ) {
                ErrorQuit( "gen no. %d in rel no. %d out of range",
                           (Int)j, (Int)i );
                return 0;
            }
            if (next == gen || next == ginv )
                ++occ;
        }
        if ( occ == 0 )  {
            continue;
        }

        /* allocate a bag for the modified Tietze relator                  */
        new = NEW_PLIST( T_PLIST, leng + occ * (wleng - 1) );
        pt2 = ptNew = ADDR_OBJ( new );
        ptLens = ADDR_OBJ( lens );
        ptInvs = ADDR_OBJ( invs ) + (numgens + 1);
        ptWrd  = ADDR_OBJ( word );
        ptIwrd = ADDR_OBJ( iwrd );
        ptRel  = ADDR_OBJ( rel );

        /* now run again through the relator and modify it                 */
        for ( j = 1;  j <= leng;  j++ ) {
            next = INT_INTOBJ( ptRel[j] );
            if ( next == gen || next == -gen ) {
                pt1 = ( next > 0 ) ? ptWrd : ptIwrd;
                pt3 = pt1 + wleng;
                while ( pt1 < pt3 ) {
                    ++pt1;
                    if ( pt2 > ptNew && *pt2 == ptInvs[INT_INTOBJ(*pt1)] )
                        --pt2;
                    else
                        *++pt2 = *pt1;
                }
            }
            else {
                if ( pt2 > ptNew && *pt2 == ptInvs[next] )
                    --pt2;
                else
                    *++pt2 = INTOBJ_INT( next );
            }
        }

        /*  now cyclically reduce the relator                              */
        pt1 = ++ptNew;
        while ( pt1 < pt2 && *pt1 == ptInvs[INT_INTOBJ(*pt2)] ) {
            ++pt1;  --pt2;
        }
        if ( ptNew < pt1 ) {
            while ( pt1 <= pt2 )   *ptNew++ = *pt1++;
            pt2 = --ptNew;
        }

        /*  resize and save the resulting relator                          */
        ptNew = ADDR_OBJ( new );
        newleng = pt2 - ptNew;
        SET_LEN_PLIST( new, newleng );
        ptLens[i] = INTOBJ_INT( newleng );
        total = total - leng + newleng;
        SHRINK_PLIST( new, newleng );
        ptRels = ADDR_OBJ( rels );
        ptLens = ADDR_OBJ( lens );
        ptRels[i] = new;
        ADDR_OBJ( flags )[i] = INTOBJ_INT( 1 );
        CHANGED_BAG(rels);
    }

    ptTietze = ADDR_OBJ( tietze );
    ptTietze[TZ_TOTAL] = INTOBJ_INT( total );

    return 0;
}


/****************************************************************************
**
*F  FuncTzOccurrences( <self>, <args> ) . .  occurrences of Tietze generators
*/
Obj FuncTzOccurrences ( 
    Obj                 self,
    Obj                 args )
{
    Obj                 tietze;         /* handle of the Tietze stack      */
    Obj *               ptTietze;       /* pointer to the Tietze stack     */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 res;            /* handle of the result            */
    Obj                 cnts;           /* list of the counts              */
    Obj *               ptCnts;         /* pointer to the counts list      */
    Obj                 mins;           /* list of minimal occurence list  */
    Obj *               ptMins;         /* pointer to the minimals list    */
    Obj                 lens;           /* list of lengths of those        */
    Obj *               ptLens;         /* pointer to the lengths list     */
    Obj                 rel;            /* handle of a relator             */
    Obj *               ptRel;          /* pointer to this relator         */
    Obj                 aux;            /* auxiliary list                  */
    Int  *              ptAux;          /* pointer to the lengths list     */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 leng;           /* length of a relator             */
    Int                 num, next;      /* generators or inverses          */
    Int                 i, k;           /* loop variables                  */
    Int                 c;              /* count of one generator          */
    Int                 nr;             /* number of occurrences           */
    Int                 nr1;            /* nr of occurrences in one word   */
    Int                 nrm;            /* minimal value of 'nr1'          */
    Int                 min;            /* word that has this minimum      */

    /* get and check arguments                                             */
    if ( ! IS_SMALL_LIST(args) || 2 < LEN_LIST(args) || LEN_LIST(args) < 1 ) {
        ErrorQuit( "usage: TzOccurrences( <Tietze stack>[, <gen no.> ] )",
                   0L, 0L );
        return 0;
    }

    /* check the first argument (Tietze stack)                             */
    tietze = ELM_LIST( args, 1 );
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );
    numgens = INT_INTOBJ(ptTietze[TZ_NUMGENS]);

    /* get and check the given generator number                            */
    if ( LEN_LIST(args) == 2 ) {
        num = INT_INTOBJ( ELM_LIST(args,2) );
        if ( num <= 0 || numgens < num ) {
            ErrorQuit( "given generator number out of range", 0L, 0L );
            return 0;
        }
        numgens = 1;
    }
    else {
        num = numgens;
    }

    /* allocate the result lists                                           */
    cnts = NEW_PLIST( T_PLIST, numgens );
    SET_LEN_PLIST( cnts, numgens );
    for ( k = 1;  k <= numgens;  k++ )
        ADDR_OBJ(cnts)[k] = INTOBJ_INT(0);

    mins = NEW_PLIST( T_PLIST, numgens );
    SET_LEN_PLIST( mins, 0 );

    lens = NEW_PLIST( T_PLIST, numgens );
    SET_LEN_PLIST( lens, 0 );
    
    res = NEW_PLIST( T_PLIST, 3 );
    SET_LEN_PLIST( res, 3 );
    ADDR_OBJ(res)[1] = cnts;
    ADDR_OBJ(res)[2] = mins;
    ADDR_OBJ(res)[3] = lens;
    CHANGED_BAG(res);

    /* allocate an auxiliary list                                          */
    ptAux = 0;
    if ( numgens > 1 ) {
        aux   = NEW_STRING( (numgens+1)*sizeof(Int4) );
        ptAux = (Int*)ADDR_OBJ(aux);
        ptAux[0] = numgens;
        for ( k = 1;  k <= numgens;  k++ )
            ptAux[k] = 0;

    }

    /* now we can safely grab pointers                                     */
    ptRels = ADDR_OBJ(rels);
    ptCnts = ADDR_OBJ(cnts);
    ptLens = ADDR_OBJ(lens);
    ptMins = ADDR_OBJ(mins);

    /* handle special case of single generator in generator list           */
    if ( numgens == 1 ) {

        /* initialize the counters                                         */
        nr = 0;  nrm = 0;  min = 0;

        /* loop over all relators                                          */
        for ( i = 1;  i <= numrels;  i++ ) {
            rel = ptRels[i];
            if ( rel == 0 || ! IS_PLIST(rel) ) {
                ErrorQuit( "invalid entry [%d] in Tietze relators list",
                           (Int)i, 0L );
                return 0;
            }
            ptRel = ADDR_OBJ(rel);
            leng  = LEN_PLIST(rel);

            /* loop over the letters of the relator                        */
            nr1 = 0;
            for ( k = 1;  k <= leng;  k++ ) {
                next = INT_INTOBJ( ptRel[k] );
                if ( next == num || next == -num )  {
                    nr1++;
                }
            }

            /* check whether the number of occurrences of num is less than */
            /* in the preceding relators                                   */
            nr += nr1;
            if ( nrm == 0
              || (0 < nr1 && nr1 < nrm)
              || (nr1 == nrm && LEN_PLIST(rel) < LEN_PLIST(ptRels[min])) )
            {
                nrm = nr1;  min = i;
            }
        }

        /* put the information into the result bags                        */
        ptCnts[1] = INTOBJ_INT( nr );
        if ( nr != 0 ) {
            ptCnts[1] = INTOBJ_INT( nr );
            SET_LEN_PLIST( lens, 1 );
            SET_ELM_PLIST( lens, 1, INTOBJ_INT(nrm) );
            SET_LEN_PLIST( mins, 1 );
            SET_ELM_PLIST( mins, 1, INTOBJ_INT(min) );
        }
    }

    /* handle general case of all Tietze generators                        */
    else {

        /* loop over all relators                                          */
        for ( i = 1;  i <= numrels;  i++ ) {
            rel = ptRels[i];
            if ( rel == 0 || ! IS_PLIST(rel) ) {
                ErrorQuit( "invalid entry [%d] in Tietze relators list",
                           (Int)i, 0L );
                return 0;
            }
            ptRel = ADDR_OBJ(rel);
            leng  = LEN_PLIST(rel);

            /* loop over the letters of the relator                        */
            for ( k = 1;  k <= leng;  k++ ) {
                next = INT_INTOBJ( ptRel[k] );
                if ( next < 0 ) next = -next;
                if ( next == 0 || numgens < next ) {
                    ErrorQuit( "invalid entry [%d][%d] in Tietze rels list",
                               (Int)i, (Int)k );
                    return 0;
                }
                (ptAux[next])++;
            }

            /* loop over the generators, collecting the counts             */
            for ( k = 1;  k <= numgens;  k++ ) {
                c = ptAux[k];
                if ( !c )
                    continue;
                ptAux[k] = 0;
                if ( ! SUM_INTOBJS( ptCnts[k], ptCnts[k], INTOBJ_INT(c) ) ) {
                    ErrorQuit( "integer overflow", 0L, 0L );
                    return 0;
                }
                if ( 0 < c ) {
                    if ( ptLens[k] == 0 || c < INT_INTOBJ(ptLens[k])
                      || (c == INT_INTOBJ(ptLens[k]) 
                       && LEN_PLIST(rel) 
                          < LEN_PLIST(ptRels[INT_INTOBJ(ptMins[k])])) )
                    {
                        ptLens[k] = INTOBJ_INT(c);
                        ptMins[k] = INTOBJ_INT(i);
                    }
                }
            }
        }

        /* find the correct length of the minimals and lengths lists       */
        k = numgens;
        while ( ptMins[k] == 0 )
            k--;
        SET_LEN_PLIST( mins, k );
        SET_LEN_PLIST( lens, k );
    }

    /* return the result                                                   */
    return res;
}


/****************************************************************************
**
*F  FuncTzOccurrencesPairs( <self>, <args> )  . . . . .  occurrences of pairs
*/
Obj FuncTzOccurrencesPairs (
    Obj                 self,
    Obj                 args )
{
    Obj                 tietze;         /* handle of the Tietze stack      */
    Obj *               ptTietze;       /* pointer to the Tietze stack     */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 invs;           /* handle of the inverses list     */
    Obj *               ptInvs;         /* pointer to this list            */
    Obj                 res;            /* handle of the resulting list    */
    Obj *               ptRes;          /* pointer to this list            */
    Obj                 rel;            /* handle of a relator             */
    Obj *               ptRel;          /* pointer to this relator         */
    Obj                 numObj;         /* handle of generator number      */
    Obj                 invObj;         /* handle of inverse gen number    */
    Int                 num, i, ii;     /* generator numbers               */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 length;         /* length of the current relator   */
    Int                 j1, j2, r;      /* loop variables                  */

    /* get and check arguments                                             */
    if ( ! IS_SMALL_LIST(args) || 3 < LEN_LIST(args) || LEN_LIST(args) < 2 ) {
        ErrorQuit(
          "usage: TzOccurrencesPairs( <Tietze stack>, <gen>[, <list>] )",
          0L, 0L );
        return 0;
    }

    /* check the first argument (Tietze stack)                             */
    tietze = ELM_LIST( args, 1 );
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze inverses list                              */
    CheckTietzeInverses( ptTietze, &invs, &ptInvs, &numgens );

    /* get and check the Tietze generator number                           */
    numObj = ELM_LIST( args, 2 );
    if ( ! IS_INTOBJ(numObj) ) {
        ErrorQuit( "<gen> must be a Tietze generator number", 0L, 0L );
        return 0;
    }
    num = INT_INTOBJ(numObj);
    if ( num <= 0 || num > numgens ) {
        ErrorQuit( "given generator number is out of range", 0L, 0L );
        return 0;
    }

    /*  Get and check the list for the results, if specified               */
    if ( LEN_PLIST(args) == 2 ) {
        res = NEW_PLIST( T_PLIST, 4*numgens );
        SET_LEN_PLIST( res, 4*numgens );
    }
    else {
        res = ELM_LIST( args, 3 );
        if ( res == 0 || ! IS_PLIST(res) || LEN_PLIST(res) != 4*numgens ) {
            ErrorQuit( "<list> must be a list of length %d",
                       (Int)4*numgens, 0L );
            return 0;
        }
    }

    /*  return, if num = numgens                                           */
    if ( num == numgens )  {
        return res;
    }

    /*  get pointers to the involved lists                                 */
    ptRels = ADDR_OBJ( rels );
    ptInvs = ADDR_OBJ( invs ) + (numgens + 1);
    ptRes  = ADDR_OBJ( res );

    /* get the handle of the inverse of the given generator                */
    invObj = ptInvs[num];

    /* ptRes[i]           counts the occurrences of gen * gen[i]           */
    /* ptRes[numgens+i]   counts the occurrences of gen * gen[i]^-1        */
    /* ptRes[2*numgens+i] counts the occurrences of gen^-1 * gen[i]        */
    /* ptRes[3*numgens+i] counts the occurrences of gen^-1 * gen[i]^-1     */

    /* initialize the counters                                             */
    for ( i = 1; i <= 4 * numgens; i++ ) {
        ptRes[i] = INTOBJ_INT(0);
    }

    /* loop over the relators                                       */
    for ( r = 1; r <= numrels; r++ ) {
        rel = ptRels[r];
        if ( rel == 0 || ! IS_PLIST(rel) ) {
            ErrorQuit( "invalid Tietze relator [%d]", (Int)r, 0L );
            return 0;
        }
        ptRel = ADDR_OBJ(rel) + 1;

        /* skip the current relator if its length is less than 2           */
        length = LEN_PLIST( rel );
        if ( length < 2 )  {
            continue;
        }

        /* loop over the current relator and investigate the pairs         */
        /* ( ptRel[j1], ptRel[j2] )                                        */
        j1 = length - 1;
        for ( j2 = 0;  j2 < length;  j1 = j2, j2++ ) {

            /* count any "forward" pair  gen * gen[i],  gen * gen[i]^-1,   */
            /* gen^-1 * gen[i],  or  gen^-1 * gen[i]^-1  ( with num < i )  */
            if ( ptRel[j1] == numObj || ptRel[j1] == invObj ) {
                i = INT_INTOBJ( ptRel[j2] );
                if ( -num <= i && i <= num )  {
                    continue;
                }
                if ( i < -numgens || numgens < i ) {
                    ErrorQuit( "invalid entry %d in Tietze relator [%d]",
                               (Int)i, (Int)r );
                    return 0;
                }
                if ( i < 0 )
                    i = numgens - i;
                if ( ptRel[j1] != numObj )
                    i = i + 2 * numgens;
                if ( ! SUM_INTOBJS( ptRes[i], ptRes[i], INTOBJ_INT(1) ) ) {
                    ErrorQuit( "integer overflow", 0L, 0L );
                    return 0;
                }
            }

            /* count any "backward" pair  gen[i]^-1 * gen^-1,              */
            /* gen[i] * gen^-1,  gen[i]^-1 * gen,  or  gen[i] * gen        */
            /* ( with num < i )  which is not covered by a forward pair    */
            else if ( ptRel[j2] == numObj || ptRel[j2] == invObj ) {
                i = INT_INTOBJ( ptRel[j1] );
                if ( -num <= i && i <= num )  {
                    continue;
                }
                if ( i < - numgens || numgens < i ) {
                    ErrorQuit( "invalid entry %d in Tietze relator [%d]",
                               (Int)i, (Int)r );
                    return 0;
                }
                ii = INT_INTOBJ( ptInvs[i] );
                if ( !( (numObj == invObj
                        && ptRel[(j2+1)%length] == INTOBJ_INT(ii))
                     || (i == ii
                        && ptInvs[INT_INTOBJ(ptRel[(j1+length-1)%length])] 
                           == ptRel[j2]) ) )
                {
                    if ( ii < 0 )
                        ii = numgens - ii;
                    if ( ptRel[j2] != invObj )
                        ii = ii + 2 * numgens;
                    if ( !SUM_INTOBJS(ptRes[ii],ptRes[ii],INTOBJ_INT(1)) ) {
                        ErrorQuit( "integer overflow", 0L, 0L );
                        return 0;
                    }
                }
            }
        }
    }

    return res;
}


/****************************************************************************
**
*F  FuncTzSearchC( <self>, <args> ) . find subword matches in Tietze relators
*/
Obj FuncTzSearchC (
    Obj                 self,
    Obj                 args )
{
    Obj                 tietze;         /* handle of the Tietze stack      */
    Obj *               ptTietze;       /* pointer to this stack           */
    Obj                 rels;           /* handle of the relators list     */
    Obj *               ptRels;         /* pointer to this list            */
    Obj                 lens;           /* handle of the lengths list      */
    Obj *               ptLens;         /* pointer to this list            */
    Obj                 invs;           /* handle of the inverses list     */
    Obj *               ptInvs;         /* pointer to this list            */
    Obj                 flags;          /* handle of the flags list        */
    Obj *               ptFlags;        /* pointer to this list            */
    Obj                 word;           /* handle of the given relator     */
    Obj                 lo;             /* handle of current list relator  */
    Obj                 wo;             /* handle of a relator             */
    Obj                 tmp;            /* handle of the second argument   */
    Obj                 equ;            /* handle of the fifth argument    */
    UInt1               keys1[8192];    /* hash table of key values        */
    UInt1               keys2[8192];    /* hash table of key values        */
    UInt1               keys3[8192];    /* hash table of key values        */
    UInt                inv;            /* inverse for key computation     */
    UInt                key;            /* key value of subword            */
    Int                 numgens;        /* number of Tietze generators     */
    Int                 numrels;        /* number of Tietze relators       */
    Int                 total;          /* total length of relators        */
    Obj *               ptr;            /* pointer to a relator            */
    Obj *               v;              /* pointers into relators          */
    Obj *               w;              /* pointers into relators          */
    Obj *               ptx;            /* pointers into relators          */
    Obj *               pty;            /* pointers into relators          */
    Int                 i1, j1;         /* loop variables                  */
    Int                 i2, j2;         /* loop variables                  */
    Int                 i3, j3;         /* loop variables                  */
    Int                 len1;           /* relator length                  */
    Int                 lmin, lmax;     /* bound for relator lengths       */
    Int                 pos1, pos2;     /* position of the given relator   */
    Int                 xmax;           /* position of the given relator   */
    Int                 newflag, flag1; /* Tietze relator flags            */
    Int                 xflag, yflag;   /* Tietze relator flags            */
    Int                 xlen, xlen1;    /* length of the given relator     */
    Int                 mlen;           /* length of the wanted match      */
    Int                 ylen, ylen1;    /* length of the current relator   */
    Int                 newlen;         /* length of a new relator         */
    Int                 n, m;           /* subword lengths                 */
    Int                 count;          /* number of altered relators      */
    Int                 i, j, jj, x, y; /* loop variables                  */
    Int                 lasty;          /* flag                            */
    Int                 altered;        /* flag                            */
    Int                 equal;          /* flag                            */

    /* get and check arguments                                             */
    if ( ! IS_SMALL_LIST(args) || 4 < LEN_LIST(args) || LEN_LIST(args) < 3 ) {
        ErrorQuit(
          "usage: TzSearchC( <Tietze stack>, <pos1>, <pos2>[, <equal>] )",
          0L, 0L );
        return 0;
    }

    /* check the first argument (Tietze stack)                             */
    tietze = ELM_LIST( args, 1 );
    CheckTietzeStack( tietze, &ptTietze );

    /* get and check the Tietze relators list                              */
    CheckTietzeRelators( ptTietze, &rels, &ptRels, &numrels );

    /* get and check the Tietze lengths list                               */
    CheckTietzeLengths( ptTietze, numrels, &lens, &ptLens );

    /* get and check the Tietze flags list                                 */
    CheckTietzeFlags( ptTietze, numrels, &flags, &ptFlags );

    /* check list <lens> to contain the relator lengths                    */
    CheckTietzeRelLengths( ptTietze, ptRels, ptLens, numrels, &total );

    /* get and check the Tietze inverses list                              */
    CheckTietzeInverses( ptTietze, &invs, &ptInvs, &numgens );

    /* check the second argument                                           */
    tmp = ELM_LIST( args, 2 );
    if ( ! IS_INTOBJ(tmp) ) {
        ErrorQuit( "<pos1> must be a positive int", 0L ,0L );
        return 0;
    }
    pos1 = INT_INTOBJ(tmp);
    if ( pos1 > numrels ) {
        ErrorQuit( "<pos1> out of range: %d", (Int)pos1, 0L );
        return 0;
    }

    /* check the third argument                                            */
    tmp = ELM_LIST( args, 3 );
    if ( ! IS_INTOBJ(tmp) ) {
        ErrorQuit( "<pos2> must be a positive int", 0L ,0L );
        return 0;
    }
    pos2 = INT_INTOBJ(tmp);
    if ( pos2 > numrels ) {
        ErrorQuit( "<pos2> out of range: %d", (Int)pos2, 0L );
        return 0;
    }

    /* check the fourth argument                                           */
    if ( LEN_LIST(args) == 3 ) {
        equ = False;
    }
    else {
        equ = ELM_LIST( args, 4 );
        if ( equ != False && equ != True ) {
            ErrorQuit( "<equal> must be false or true", 0L, 0L );
            return 0;
        }
    }
    equal = ( equ == True );

    /* Skip relators of inconvenient lengths or with inconvenient flags,   */
    /*  and return if the remaining range is empty                         */
    while ( pos1 <= pos2
        && (INT_INTOBJ( ptLens[pos1] ) < 2
         || INT_INTOBJ( ptFlags[pos1] ) > 1
         || (equal && ( INT_INTOBJ( ptLens[pos1] ) < 4
                     || INT_INTOBJ( ptLens[pos1] ) % 2 == 1 ) ) ) )
    {
        pos1++;
    }
    if ( pos1 > pos2 || pos1 == numrels ) {
        return INTOBJ_INT(0);
    }

    /* get the range of compatible relator lengths                         */
    len1 = INT_INTOBJ( ptLens[pos1] );
    lmin = len1 - ( len1 % 2 );
    lmax = ( equal ) ? lmin : lmin + 1;

    /* initialize some variables                                           */
    newflag = ( equal ) ? 1 : 2;
    count = 0;
    lasty = 0;
    xmax = pos1 - 1;
    flag1 = INT_INTOBJ( ptFlags[pos1] );

    /* Compute the length of the wanted match and the corresponding        */
    /*  inverse factor                                                     */
    mlen = equal ? ( lmin + 1 ) / 2 : lmin / 2 + 1;
    inv = 1;
    for ( i = 1; i <= mlen; i++ )
       inv = 109109 * inv;

    /* initialize the hash table                                           */
    for ( i = 0; i < 2048; i++ )
       ((UInt4 *)keys1)[i] = ((UInt4 *)keys2)[i] = ((UInt4 *)keys3)[i] = 0;

    /* loop over the Tietze relators, starting at position pos1            */
    for ( y = pos1;  y < numrels;  ) {
       word  = ptRels[y];
       ylen  = INT_INTOBJ( ptLens[y] );
       yflag = INT_INTOBJ( ptFlags[y] );
       if ( y <= pos2 && lmin <= ylen && ylen <= lmax && yflag <= 1 ) {

          /* add the key values of the current relator to the hash table   */
          ptr = ADDR_OBJ(word);

          key = 0;

          for ( i = 0, w = ptr+1;  i < mlen;  i++, w++ )
             key = 109109 * key + ((UInt)*w >> 2);

          for ( i = 0, v = ptr+1, w = v+mlen; i < ylen; i++, v++, w++ ) {
             keys1[ key & 8191 ] = 1;
             keys2[ (key >> 11) & 8191 ] |= (1 << ((key >> 8) & 7));
             keys3[ (key >> 19) & 8191 ] |= (1 << ((key >> 16) & 7));
             if ( i == ylen-mlen )
                 w = ptr+1;
             key = 109109 * key - inv * ((UInt)*v >> 2) + ((UInt)*w >> 2);
          }

          key = 0;

          for ( i = 0, w = ptr+ylen; i < mlen; i++, w-- ) {
             key = 109109 * key + ((UInt) ptInvs[INT_INTOBJ(*w)] >> 2);
          }

          for ( i = 0, v = ptr+ylen, w = v-mlen; i < ylen; i++, v--, w-- ) {
             keys1[ key & 8191 ] = 1;
             keys2[ (key >> 11) & 8191 ] |= (1 << ((key >> 8) & 7));
             keys3[ (key >> 19) & 8191 ] |= (1 << ((key >> 16) & 7));
             if ( i == ylen-mlen )
                 w = ptr+ylen;
             key = 109109 * key
                 - inv * ((UInt) ptInvs[INT_INTOBJ(*v)] >> 2)
                 + ( (UInt) ptInvs[INT_INTOBJ(*w)] >> 2 );
          }
          if ( len1 > ylen )
              len1 = ylen;
          if ( flag1 < yflag )
              flag1 = yflag;
          xmax = y;
       }

       /* move to next relator                                             */
       y++;

       /* initialize some variables                                        */
       lo      = ptRels[y];
       ylen    = INT_INTOBJ( ptLens[y] );
       yflag   = INT_INTOBJ( ptFlags[y] );
       ylen1   = ylen - 1;
       altered = 0;

       /* Loop to the next relator, if the current relator is too short    */
       if ( y > lasty
         && (ylen < len1 || yflag > 1 || (!equal && !(yflag + flag1)) ) )
       {
          continue;  /*  loop over y */
       }
       lasty = y;

       /* Compute the key values of the current relator                    */
       ptr = ADDR_OBJ(lo);

       key = 0;

       for ( j = 0, w = ptr+1; j < mlen; j++, w++ )
          key = 109109 * key + ( (UInt)*w >> 2 );

       for ( j = 0; j < ylen; j++ ) {

          /* check for key match in the tables                             */
          if ( keys1[ key & 8191 ]
             && (keys2[ (key >> 11) & 8191 ] & (1 << ((key >> 8) & 7)))
             && (keys3[ (key >> 19) & 8191 ] & (1 << ((key >> 16) & 7))) ){

             /* loop over the (relevant) given relators                    */
             for ( x = pos1; x <= xmax; x++ ) {

                wo    = ptRels[x];
                xlen  = INT_INTOBJ( ptLens[x] );
                xflag = INT_INTOBJ( ptFlags[x] );
                if ( xlen < len1 || xlen > lmax || xlen > ylen
                  || xflag > 1 || (!equal && !( xflag + yflag )) )
                {
                   continue;  /*  loop over x */
                }

                xlen1 = xlen - 1;
                ptx = ADDR_OBJ(wo) + 1;
                pty = ADDR_OBJ(lo) + 1;

                /* loop over all possible positions in the given relator   */
                for ( i = 0; i < xlen; i++ ) {

                   /* search forward for a match of length at least mlen   */
                   i2 = i;  j2 = j;
                   for ( n = 0; n < xlen; n++,
                      i2 = (i2 == xlen1) ? 0 : i2 + 1,
                      j2 = (j2 == ylen1) ? 0 : j2 + 1 ) {
                      if ( ptx[i2] != pty[j2] )
                          break;  /* loop over n */
                   }
                   if ( n < mlen )  continue;  /*  loop over i             */

                   /* search backward to find the whole match              */
                   i1 = (i == 0) ? xlen1 : i - 1;
                   j1 = (j == 0) ? ylen1 : j - 1;
                   for ( ; n < xlen; n++,
                      i1 = (i1 == 0) ? xlen1 : i1 - 1,
                      j1 = (j1 == 0) ? ylen1 : j1 - 1 )
                   {
                      if ( ptx[i1] != pty[j1] )
                          break;  /* loop over n */
                   }

                   /* replace a matching substring of equal length         */
                   if ( n == xlen - n ) {
                      j2 = j;
                      for ( m = 0; m < n; m++,
                         i1 = (i1 == 0) ? xlen1 : i1 - 1,
                         j2 = (j2 == ylen1) ? 0 : j2 + 1 )
                      {
                         pty[j2] = ptInvs[INT_INTOBJ(ptx[i1])];
                      }

                      /* Now replace all exact occurrences of this string  */
                      /*  in the current word (not relator)                */
                      i3 = (i + n) % xlen;

                      for ( jj = 0; jj <= ylen - n; jj++ ) {
                         i2 = i;  j2 = jj;
                         for ( m = 0; m < n; m++,
                            i2 = (i2 == xlen1) ? 0 : i2 + 1,
                            j2 = (j2 == ylen1) ? 0 : j2 + 1 ) {
                            if ( ptx[i2] != pty[j2] )
                                break;  /* loop over m */
                         }
                         if ( m < n )
                             continue;  /* loop over jj */

                         i1 = (i == 0) ? xlen1 : i - 1;
                         if ( ptx[i1] == pty[(jj + ylen1) % ylen] ||
                            ptx[i3] == pty[(jj + n) % ylen] )
                         {
                            continue;  /* loop over jj */
                         }

                         j2 = jj;
                         for ( m = 0; m < n; m++,
                            i1 = (i1 == 0) ? xlen1 : i1 - 1,
                            j2 = (j2 == ylen1) ? 0 : j2 + 1 ) {
                            pty[j2] = ptInvs[INT_INTOBJ(ptx[i1])];
                         }

                         jj = -1;
                      }

                      ptFlags[y] = INTOBJ_INT( newflag );
                      altered = 1;
                      ++count;
                      break;  /* loop over i */
                   }

                   m = ylen - n;  n = xlen - n;

                   /* find all canceling factors                           */
                   if ( n == 0 ) {
                      for ( ; 1 < m; m -= 2,
                         j1 = (j1 == 0) ? ylen1 : j1 - 1,
                         j2 = (j2 == ylen1) ? 0 : j2 + 1 )
                      {
                         if ( pty[j1] != ptInvs[INT_INTOBJ(pty[j2])] )
                            break;  /*  loop over m                        */
                      }
                   }

                   /* create the modified relator and save it              */
                   newlen = m + n;
                   if ( j2 > 0 ) {
                      if ( j2 <= j1 )  {
                          jj = 0;  j3 = j1;  j1 = m - 1;
                      }
                      else  {
                          jj = j1 + n + 1;  j3 = ylen - 1;
                      }
                      for ( ; j2 <= j3; ) {
                         pty[jj++] = pty[j2++];
                      }
                   }
                   for ( ; n > 0; n--, i1 = (i1 == 0) ? xlen1 : i1 - 1 ) {
                      pty[++j1] = ptInvs[INT_INTOBJ(ptx[i1])];
                   }
                   SET_LEN_PLIST( lo, newlen );
                   ptLens[y] = INTOBJ_INT(newlen);
                   total = total - ylen + newlen;
                   ptFlags[y] = INTOBJ_INT(newflag);

                   /* reduce the bag size                                  */
                   SHRINK_PLIST( lo, newlen );
                   CHANGED_BAG(rels);
                   ptRels  = ADDR_OBJ( rels );
                   ptLens  = ADDR_OBJ( lens );
                   ptFlags = ADDR_OBJ( flags);
                   ptInvs  = ADDR_OBJ( invs ) + (numgens + 1);

                   altered = 1;
                   ++count;
                   --y;
                   break;  /* loop over i */
                }

                if ( altered )
                    break;  /* loop over x */

                /* now try the inverse of the given relator                */
                for ( i = 0;  i < xlen;  i++ ) {

                   /* search forward for a match of length at least mlen   */
                   i2 = xlen1 - i;  j2 = j;
                   for ( n = 0; n < xlen; n++,
                      i2 = (i2 == 0) ? xlen1 : i2 - 1,
                      j2 = (j2 == ylen1) ? 0 : j2 + 1 )
                   {
                      if ( ptInvs[INT_INTOBJ(ptx[i2])] != pty[j2] )
                         break;  /* loop over n */
                   }
                   if ( n < mlen )
                       continue;  /* loop over i */

                   /* search backward to find the whole match              */
                   i1 = (i == 0) ? 0 : xlen - i;
                   j1 = (j == 0) ? ylen1 : j - 1;
                   for ( ; n < xlen; n++,
                      i1 = (i1 == xlen1) ? 0 : i1 + 1,
                      j1 = (j1 == 0) ? ylen1 : j1 - 1 )
                   {
                      if ( ptInvs[INT_INTOBJ(ptx[i1])] != pty[j1] )
                         break;  /* loop over n */
                   }

                   /* replace a matching substring of equal length         */
                   if ( n == xlen - n ) {
                      j2 = j;
                      for ( m = 0; m < n; m++,
                         i1 = (i1 == xlen1) ? 0 : i1 + 1,
                         j2 = (j2 == ylen1) ? 0 : j2 + 1 )
                      {
                         pty[j2] = ptx[i1];
                      }

                      ptFlags[y] = INTOBJ_INT( newflag );
                      altered = 1;
                      ++count;
                      break;  /* loop over i */
                   }

                   m = ylen - n;  n = xlen - n;

                   /* Find all canceling factors                           */
                   if ( n == 0 ) {
                      for ( ; 1 < m; m -= 2,
                         j1 = (j1 == 0) ? ylen1 : j1 - 1,
                         j2 = (j2 == ylen1) ? 0 : j2 + 1 )
                      {
                         if ( pty[j1] != ptInvs[INT_INTOBJ(pty[j2])] )
                            break;  /* loop over m */
                      }
                   }

                   /* create the modified relator and save it              */
                   newlen = m + n;
                   if ( j2 > 0 )  {
                      if ( j2 <= j1 )  {
                          jj = 0;  j3 = j1;  j1 = m - 1;
                      }
                      else  {
                          jj = j1 + n + 1;  j3 = ylen - 1;
                      }
                      for ( ;  j2 <= j3;  ) {
                         pty[jj++] = pty[j2++];
                      }
                   }
                   for ( ;  n > 0;  n--, i1 = (i1 == xlen1) ? 0 : i1 + 1 ) {
                      pty[++j1] = ptx[i1];
                   }
                   SET_LEN_PLIST( lo, newlen );
                   ptLens[y] = INTOBJ_INT(newlen);
                   total = total - ylen + newlen;
                   ptFlags[y] = INTOBJ_INT(newflag);

                   /* reduce the bag size                                  */
                   SHRINK_PLIST( lo, newlen );
                   CHANGED_BAG(rels);
                   ptRels  = ADDR_OBJ( rels );
                   ptLens  = ADDR_OBJ( lens );
                   ptFlags = ADDR_OBJ( flags);
                   ptInvs  = ADDR_OBJ( invs ) + numgens + 1;

                   altered = 1;
                   ++count;
                   --y;
                   break;  /* loop over i */
                }

                if ( altered )
                    break;  /* loop over x */
             }
          }

          if ( altered )
              break;  /* loop over j */

          v = ptr + ( 1 + j ); 
          w = ptr + ( 1 + ( j + mlen ) % ylen );
          key = 109109 * key - inv * ( (UInt)*v >> 2 )
              + ( (UInt)*w >> 2 );
       }
    }

    ADDR_OBJ( tietze )[TZ_TOTAL] = INTOBJ_INT(total);

    /* return the number of altered relators                               */
    return INTOBJ_INT( count );
}


/* rewriting using tz form relators */

Obj  FuncReduceLetterRepWordsRewSys (
 Obj  self,
 Obj  tzrules,
 Obj  a_w )
{
 UInt n,lt,i,k,p,j,lrul,eq,rlen,newlen,a;
 Obj w,nw,rul;
 Obj * wa;
 Obj * nwa;
 
 w=a_w;

 /* n := Length( w ); */
 n=LEN_PLIST(w);
 
 /* lt := Length( tzrules ); */
 lt=LEN_PLIST(tzrules);
 
 /* i := 1; */
 i=1;
 
 /* while i in [ 1 .. n ] od */
 while (i<=n) {
  
  /* k := 1; */
  k=1;
  
  /* while k in [ 1 .. lt ] od */
  while (k<=lt) {
    
    /* rul := tzrules[k][1]; */
    rul = ELM_PLIST(tzrules,k);
    rul = ELM_PLIST(rul,1);
    lrul = LEN_PLIST(rul);
   
   /* if Length( tzrules[k][1] ) <= i then */
   if (lrul<=i) {
    
    /* eq := true; */
    eq=1;

    /* p := i; */
    p=i;
    
    /* j := Length( rul ); */
    j=lrul;
    
    /* while eq and j > 0 od */
    while ((eq==1) && (j>0) ) {
     
     /* eq := w[p] = rul[j]; */
     eq=((ELM_LIST(w,p)==ELM_LIST(rul,j))?1:0);
     
     /* p := p - 1; */
     p--;
     
     /* j := j - 1; */
     j--;
     
    }
    /* od */
    
    /* if eq then */
    if (eq==1) {
     
     /* make the new plist */

     rlen=LEN_PLIST(ELM_PLIST(ELM_PLIST(tzrules,k),2));
     newlen = n-lrul+rlen;

     if (newlen==0) {
       nw=NEW_PLIST(T_PLIST_EMPTY,0);
     }
     else {
	/* make space for the new word */
	nw = NEW_PLIST(TNUM_OBJ(w),newlen);

       /* addresses */
       wa=ADDR_OBJ(w);
       nwa=ADDR_OBJ(nw);
       wa++;
       nwa++;

       /* for a in [ 1 .. p ] do */
       /* Add( nw, w[a] ); */
       for (a=1; a<=p;a++) {
 	 *nwa++=*wa++;
       }
       /* od */

       /* rul := tzrules[k][2]; */
       rul = ELM_PLIST(tzrules,k);
       rul = ELM_PLIST(rul,2);
       wa=ADDR_OBJ(rul);
       wa++;

       /* for a in [ 1 .. Length( rul ) ] do */
       /* Add( nw, rul[a] ); */
       for (a=1;a<=rlen;a++) {
	 *nwa++=*wa++;
       }
       /* od */

       /* for a in [ i + 1 .. n ] do */
       /* there must be a better way for giving this address ... */
       wa=(Obj*) &(ADDR_OBJ(w)[i+1]);
       /* Add( nw, w[a] ); */
       for (a=i+1;a<=n;a++) {
	 *nwa++=*wa++;
       }
       /* od */

     }

     /* w := nw; */
     SET_LEN_PLIST(nw,newlen);
     w = nw;
     
     /* i := i - Length( tzrules[k][1] ); */
     i=i-lrul;
     
     /* n := Length( w ); */
     n=newlen;
     
     /* k := lt; */
     k = lt;
     
    }
    /* fi */
    
   }
   /* fi */
   
   /* k := k + 1; */
   k++;
   
  }
  /* od */
  
  /* i := i + 1; */
  i++;
  
 }
 /* od */
 
 /* return w; */
 return w;
 
}



/****************************************************************************
**

*F * * * * * * * * * * * * * initialize package * * * * * * * * * * * * * * *
*/

/****************************************************************************
**

*V  GVarFuncs . . . . . . . . . . . . . . . . . . list of functions to export
*/
static StructGVarFunc GVarFuncs [] = {

    { "TzSortC", 1, "tietze",
      FuncTzSortC, "src/tietze.c:TzSortC" },

    { "TzRenumberGens", 1, "tietze",
      FuncTzRenumberGens, "src/tietze.c:TzRenumberGens" },
    
    { "TzReplaceGens", 1, "tietze",
      FuncTzReplaceGens, "src/tietze.c:TzReplaceGens" },

    { "TzSubstituteGen", 3, "tietze, gennum, word",
      FuncTzSubstituteGen, "src/tietze.c:TzSubstituteGen" },

    { "TzOccurrences", -1, "args",
      FuncTzOccurrences, "src/tietze.c:TzOccurrences" },

    { "TzOccurrencesPairs", -1, "args",
      FuncTzOccurrencesPairs, "src/tietze.c:TzOccurrencesPairs" },

    { "TzSearchC", -1, "args",
      FuncTzSearchC, "src/tietze.c:TzSearchC" },

    { "REDUCE_LETREP_WORDS_REW_SYS", 2, "tzwords, word",
  FuncReduceLetterRepWordsRewSys,"src/tietze.c:REDUCE_LETREP_WORDS_REW_SYS" },

    { 0 }

};


/****************************************************************************
**

*F  InitKernel( <module> )  . . . . . . . . initialise kernel data structures
*/
static Int InitKernel (
    StructInitInfo *    module )
{
    /* init filters and functions                                          */
    InitHdlrFuncsFromTable( GVarFuncs );

    /* return success                                                      */
    return 0;
}


/****************************************************************************
**
*F  InitLibrary( <module> ) . . . . . . .  initialise library data structures
*/
static Int InitLibrary (
    StructInitInfo *    module )
{
    /* init filters and functions                                          */
    InitGVarFuncsFromTable( GVarFuncs );

    /* return success                                                      */
    return 0;
}


/****************************************************************************
**
*F  InitInfoTietze()  . . . . . . . . . . . . . . . . table of init functions
*/
static StructInitInfo module = {
    MODULE_BUILTIN,                     /* type                           */
    "tietze",                           /* name                           */
    0,                                  /* revision entry of c file       */
    0,                                  /* revision entry of h file       */
    0,                                  /* version                        */
    0,                                  /* crc                            */
    InitKernel,                         /* initKernel                     */
    InitLibrary,                        /* initLibrary                    */
    0,                                  /* checkInit                      */
    0,                                  /* preSave                        */
    0,                                  /* postSave                       */
    0                                   /* postRestore                    */
};

StructInitInfo * InitInfoTietze ( void )
{
    module.revision_c = Revision_tietze_c;
    module.revision_h = Revision_tietze_h;
    FillInVersion( &module );
    return &module;
}


/****************************************************************************
**

*E  tietze.c  . . . . . . . . . . . . . . . . . . . . . . . . . . . ends here
*/