File: codeman.gi

package info (click to toggle)
gap-guava 3.20%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,804 kB
  • sloc: ansic: 20,501; xml: 10,382; makefile: 254; sh: 55
file content (2317 lines) | stat: -rw-r--r-- 76,098 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
############################################################################
##
#A  codeman.gi              GUAVA library                       Reinald Baart
#A                                                        &Jasper Cramwinckel
#A                                                           &Erik Roijackers
##
##  This file contains functions for manipulating codes
##
## ConstantWeightSubcode revised 10-23-2004
##
## added 12-207 (CJ): ConstructionXCode, ConstructionXXCode, BZCode functions
##

#############################################################################
##
#F  DualCode( <C> ) . . . . . . . . . . . . . . . . . . . .  dual code of <C>
##

InstallMethod(DualCode, "generic method for codes", true, [IsCode], 0,
function(C)
	local Cnew;
	if IsCyclicCode(C) or IsLinearCode(C) then
		return DualCode(C);
	else
		Cnew := CheckMatCode(BaseMat(VectorCodeword(AsSSortedList(C))),
							"dual code", LeftActingDomain(C));
		Cnew!.history := History(C);
		return(Cnew);
	fi;
end);

InstallMethod(DualCode, "method for linear codes", true, [IsLinearCode], 0,
function(C)
	local C1, Pr, n, newwd, wd, oldrow, newrow, i, j, q;
	if IsCyclicCode(C) then
		return DualCode(C);
	elif HasGeneratorMat(C) then
		C1 := CheckMatCode(GeneratorMat(C), "dual code", LeftActingDomain(C));
	elif HasCheckMat(C) then
		C1 := GeneratorMatCode(CheckMat(C), "dual code", LeftActingDomain(C));
	else
		Error("No GeneratorMat or CheckMat for C");
	fi;
	if HasWeightDistribution(C) then
		n := WordLength(C);
		wd := WeightDistribution(C);
		q := Size(LeftActingDomain(C)) - 1;
		newwd := [Sum(wd)];
		oldrow := List([1..n+1],i->1);
		newrow := [];
		for i in [2..n+1] do
            newrow[1] := Binomial(n, i-1) * q^(i-1);
            for j in [2..n+1] do
                newrow[j] := newrow[j-1] - q * oldrow[j] - oldrow[j-1];
            od;
            newwd[i] := newrow * wd;
            oldrow := ShallowCopy(newrow);
        od;
        SetWeightDistribution(C1, newwd / ((q+1) ^ Dimension(C)) );
        Pr := PositionProperty(WeightDistribution(C1){[2..n+1]}, i-> i <> 0);
        if Pr = false then
            Pr := n;
        fi;
        C1!.lowerBoundMinimumDistance := Pr;
        C1!.upperBoundMinimumDistance := Pr;
    fi;
    C1!.history := History(C);
    return C1;
end);

InstallMethod(DualCode, "method for self dual codes", true,[IsSelfDualCode], 0,
function(C)
	return ShallowCopy(C);
end);

InstallMethod(DualCode, "method for cyclic codes", true, [IsCyclicCode], 0,
function(C)
	local C1, r, n, Pr, wd, q, newwd, oldrow, newrow, i, j;
    if HasGeneratorPol(C) then
		r := ReciprocalPolynomial(GeneratorPol(C),Redundancy(C));
		r := r/LeadingCoefficient(r);
		C1 := CheckPolCode(r, WordLength(C), "dual code", LeftActingDomain(C));
	elif HasCheckPol(C) then
		r := ReciprocalPolynomial(CheckPol(C),Dimension(C));
		r := r/LeadingCoefficient(r);
		C1 := GeneratorPolCode(r, WordLength(C), "dual code",
								LeftActingDomain(C));
	else
		Error("No GeneratorPol or CheckPol for C");
	fi;
	if HasWeightDistribution(C) then
		n := WordLength(C);
		wd := WeightDistribution(C);
		q := Size(LeftActingDomain(C)) - 1;
		newwd := [Sum(wd)];
		oldrow := List([1..n+1], i->1);
		newrow := [];
		for i in [2..n+1] do
			newrow[1] := Binomial(n, i-1) * q^(i-1);
			for j in [2..n+1] do
				newrow[j] := newrow[j-1] - q * oldrow[j] - oldrow[j-1];
			od;
            newwd[i] := newrow * wd;
			oldrow := ShallowCopy(newrow);
		od;
		SetWeightDistribution(C1, newwd / ((q+1) ^ Dimension(C)));
	    Pr := PositionProperty(WeightDistribution(C1){[2..n+1]}, i-> i <> 0);
	    if Pr = false then
	         Pr := n;
	    fi;
	    C1!.lowerBoundMinimumDistance := Pr;
	    C1!.upperBoundMinimumDistance := Pr;
	fi;
	C1!.history := History(C);
	return C1;
end);


#############################################################################
##
#F  AugmentedCode( <C> [, <L>] )  . . .  add words to generator matrix of <C>
##

InstallMethod(AugmentedCode, "unrestricted code and codeword list/object",
	true, [IsCode, IsObject], 0,
function (C, L)
	if IsLinearCode(C) then
		return AugmentedCode(C, L);
	else
		Error("argument must be a linear code");
	fi;
end);

InstallOtherMethod(AugmentedCode, "unrestricted code", true, [IsCode], 0,
function(C)
	return AugmentedCode(C, NullMat(1, WordLength(C), LeftActingDomain(C))
								+ One(LeftActingDomain(C)));
end);

InstallMethod(AugmentedCode, "linear code and codeword object/list",
	true, [IsCode, IsObject], 0,
function (C, L)
    local Cnew;
	L := VectorCodeword(Codeword(L, C) );
	if not IsList(L[1]) then
		L := [L];
	else
		L := Set(L);
	fi;
    Cnew := GeneratorMatCode(BaseMat(Concatenation(GeneratorMat(C),L)),
                 Concatenation("code, augmented with ", String(Length(L)),
                         " word(s)"), LeftActingDomain(C));
    if Length(GeneratorMat(Cnew)) > Dimension(C) then
        Cnew!.upperBoundMinimumDistance := Minimum(
                 UpperBoundMinimumDistance(C),
                 Minimum(List(L, l-> Weight(Codeword(l)))));
        Cnew!.history := History(C);
        return Cnew;
    else
        return ShallowCopy(C);
    fi;
end);


#############################################################################
##
#F  EvenWeightSubcode( <C> )  . . .  code of all even-weight codewords of <C>
##

InstallMethod(EvenWeightSubcode, "method for unrestricted codes", true,
	[IsCode], 0,
function(Cold)
	local C, n, Els, E, d, i, s, q, wd;

	if IsCyclicCode(Cold) or IsLinearCode(Cold) then
		return EvenWeightSubcode(Cold);
	fi;

    q := Size(LeftActingDomain(Cold));
    n := WordLength(Cold);
    Els := AsSSortedList(Cold);
    E := [];
	s := 0;
    for i in [1..Size(Cold)] do
        if IsEvenInt(Weight(Els[i])) then
            Append(E, [Els[i]]);
            s := s + 1;
        fi;
    od;
    if s <> Size(Cold) then
        C := ElementsCode( E, "even weight subcode", GF(q) );
        d := [LowerBoundMinimumDistance(Cold),
              UpperBoundMinimumDistance(Cold)];
        for i in [1..2] do
            if q=2 and IsOddInt(d[i] mod 2) then
                d[i] := Minimum(d[i]+1,n);
            fi;
        od;
        C!.lowerBoundMinimumDistance := d[1];
        C!.upperBoundMinimumDistance := d[2];
        if HasWeightDistribution(Cold) then
            wd := ShallowCopy(WeightDistribution(Cold));
            for i in [1..QuoInt(n+1,2)] do
                wd[2*i] := 0;
            od;
        	SetWeightDistribution(C, wd);
		fi;
        C!.history := History(Cold);
        return C;
    else
        return ShallowCopy(Cold);
    fi;
end);

InstallMethod(EvenWeightSubcode, "method for linear codes", true,
	[IsLinearCode], 0,
function(Cold)
    local C, P, edited, n, G, Els, E, i, s,q, Gold, wd, lbmd;
    if IsCyclicCode(Cold) then
		return EvenWeightSubcode(Cold);
	fi;
	q := Size(LeftActingDomain(Cold));
    n := WordLength(Cold);
    edited := false;
    if q = 2 then
        # Why is the next line needed?
        P := NullVector(n, GF(2));
        G := [];
        Gold := GeneratorMat(Cold);
        for i in [1..Dimension(Cold)] do
            if Weight(Codeword(Gold[i])) mod 2 <> 0 then
                if not edited then
                    P := Gold[i];
                    edited := true;
                else
                    Append(G, [Gold[i]+P]);
                fi;
            else
                Append(G, [Gold[i]]);
            fi;
        od;
        if edited then
            C := GeneratorMatCode(BaseMat(G),"even weight subcode",GF(q));
        fi;
    else
        Els := AsSSortedList(Cold);
        E := []; s := 0;
        for i in [1..Size(Cold)] do
            if IsEvenInt(Weight(Els[i])) then
                Append(E, [Els[i]]);
                s := s + 1;
            fi;
        od;
        edited := (s <> Size(Cold));
        if edited then
            C := ElementsCode(E, "even weight subcode", GF(q) );
        fi;
    fi;

    if edited then
        lbmd := Minimum(n, LowerBoundMinimumDistance(Cold));
        if q = 2 and IsOddInt(lbmd) then
            lbmd := lbmd + 1;
        fi;
        C!.lowerBoundMinimumDistance := lbmd;
		if HasWeightDistribution(Cold) then
            wd := ShallowCopy(WeightDistribution(Cold));
            for i in [1..QuoInt(n+1,2)] do
                wd[2*i] := 0;
            od;
			SetWeightDistribution(C, wd);
		fi;
		C!.history := History(Cold);
        return C;
    else
        return ShallowCopy(Cold);
    fi;
end);

##LR See co'd roots stuff, nd reinstate sometime.
InstallMethod(EvenWeightSubcode, "method for cyclic codes", true,
	[IsCyclicCode], 0,
function(Cold)
    local C, P, edited, n, Els, E, i, q, lbmd, wd;
    q := Size(LeftActingDomain(Cold));
    n := WordLength(Cold);
    edited := false;
    if (q =2) then
        P := Indeterminate(GF(2))-One(GF(2));
        if Gcd(P, GeneratorPol(Cold)) <> P then
            C := GeneratorPolCode( GeneratorPol(Cold)*P, n,
                         "even weight subcode", LeftActingDomain(Cold));
            #if IsBound(C.roots) then
            #    AddSet(C.roots, Z(2)^0);
            #fi;
            edited := true;
        fi;
    else
        Els := AsSSortedList(Cold);
        E := [];
        for i in [1..Size(Cold)] do
            if IsEvenInt(Weight(Els[i])) then
                Append(E, [Els[i]]);
            else
                edited := true;
            fi;
        od;
        if edited then
            C := ElementsCode(E, "even weight subcode", LeftActingDomain(Cold));
        fi;
    fi;

    if edited then
        lbmd := Minimum(n, LowerBoundMinimumDistance(Cold));
        if q = 2 and IsOddInt(lbmd) then
            lbmd := lbmd + 1;
        fi;
        C!.lowerBoundMinimumDistance := lbmd;
		if HasWeightDistribution(Cold) then
            wd := ShallowCopy(WeightDistribution(Cold));
            for i in [1..QuoInt(n+1,2)] do
                wd[2*i] := 0;
            od;
        	SetWeightDistribution(C, wd);
		fi;
        C!.history := History(Cold);
        return C;
    else
        return ShallowCopy(Cold);
    fi;
end);


#############################################################################
##
#F  ConstantWeightSubcode( <C> [, <w>] )  .  all words of <C> with weight <w>
##

InstallMethod(ConstantWeightSubcode, "method for unrestricted code, weight",
	true, [IsCode, IsInt], 0,
function(C, wt)
  local D, Els,path;
  if IsLinearCode(C) then
	return ConstantWeightSubcode(C, wt);
  fi;
  Els := Filtered(AsSSortedList(C), c -> Weight(c) = wt);
  if Els <> [] then
    D := ElementsCode(Els, Concatenation( "code with codewords of weight ", String(wt)), LeftActingDomain(C) );
    D!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    D!.history := History(C);
    return D;
   else
    Error("no words of weight", wt);
  fi;
end);

InstallOtherMethod(ConstantWeightSubcode, "method for unrestricted code",
	true, [IsCode], 0,
function(C)
  local wt;
  if IsLinearCode(C) then
	return ConstantWeightSubcode(C, MinimumDistance(C));
  fi;
  wt := PositionProperty(WeightDistribution(C){[2..WordLength(C)+1]}, i-> i > 0);
  if wt = false then
	wt := WordLength(C);
  fi;
 return ConstantWeightSubcode(C, wt);
end);

InstallMethod(ConstantWeightSubcode, "method for linear code, weight", true,
	[IsLinearCode, IsInt], 0,
function(C, wt)
   local S, c, a, CWS, path, F, incode, infile, cwsc, Els, i, D;
   a:=wt;
   if wt = 0 then
      return NullCode(WordLength(C), LeftActingDomain(C));
   fi;
   if Dimension(C) = 0 then
      Error("no constant weight subcode of a null code is defined");
   fi;

   path := DirectoriesPackagePrograms( "guava" );

   if ForAny( ["desauto", "leonconv", "wtdist"],
                 f -> Filename( path, f ) = fail ) then
      Print("the C code programs are not compiled, so using GAP code...\n");
      F:=LeftActingDomain(C);
      S:=[];
      for c in Elements(C) do
         if WeightCodeword(c)=a then
            S:=Concatenation([c],S);
         fi;
      od;
      CWS:=ElementsCode(S,"constant weight subcode",F);
      CWS!.lowerBoundMinimumDistance:=a;
      CWS!.upperBoundMinimumDistance:=a;
      return CWS;
   else
      #Print("the C code programs are compiled, so using Leon's binary....\n");
      incode := TmpName();
      PrintTo( incode, "\n" );
      infile := TmpName();
      cwsc := TmpName();
      PrintTo( infile, "\n" );
      GuavaToLeon(C, incode);
      Process(DirectoryCurrent(),
         Filename(DirectoriesPackagePrograms("guava"), "wtdist"),
	 InputTextNone(),
	 OutputTextNone(),
	 ["-q",  Concatenation(incode,"::code"), wt,
	  Concatenation(cwsc,"::code")]
      );
      if IsReadableFile( cwsc ) then
         Process(DirectoryCurrent(),
              Filename(DirectoriesPackagePrograms("guava"), "leonconv"),
              InputTextNone(),
              OutputTextNone(),
              ["-c", cwsc, infile]
         );
      else
         Error("\n Sorry, no codes words of weight ",wt,"\n");
      fi;
      Read(infile);
      RemoveFiles(incode,cwsc,infile);
      Els := [];
      for i in AsSSortedList(LeftActingDomain(C)){[2..Size(LeftActingDomain(C))]} do
         Append(Els, i * GUAVA_TEMP_VAR);
      od;
      if Els <> [] then
         D := ElementsCode(Els, Concatenation( "code with codewords of weight ",
                 String(wt)), LeftActingDomain(C)
         );
         D!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
         D!.history := History(C);
         return D;
      else
         Error("no words of weight ",wt);
         Print("\n no words of weight ",wt);
      fi;
   fi; ## end if-then-else
end);

InstallOtherMethod(ConstantWeightSubcode, "method for linear code", true,
	[IsLinearCode], 0,
function(C)
	return ConstantWeightSubcode(C, MinimumDistance(C));
end);


#############################################################################
##
#F  ExtendedCode( <C> [, <i>] ) . . . . . code with added parity check symbol
##

InstallMethod(ExtendedCode, "method to extend unrestricted code i times", true,
	[IsCode, IsInt], 0,
function(Cold, nrcolumns)
	local n, q, zeros, elements, word, vec, lbmd, ubmd, i, indist, wd, C;
	if nrcolumns < 1 then
		return ShallowCopy(Cold);
	elif IsLinearCode(Cold) then
		return ExtendedCode(Cold,nrcolumns);
	fi;

    n := WordLength(Cold)+1;
    q := Size(LeftActingDomain(Cold));
    zeros:= List( [ 2 .. nrcolumns ], i-> Zero(LeftActingDomain(Cold)) );
    elements := [];
    for word in AsSSortedList(Cold) do
        vec := VectorCodeword(word);
        Add(elements, Codeword(Concatenation(vec, [-Sum(vec)], zeros)));

    od;
    C := ElementsCode( elements, "extended code", q );
    lbmd := LowerBoundMinimumDistance(Cold);
    ubmd := UpperBoundMinimumDistance(Cold);
    if q = 2 then
        if lbmd mod 2 = 1 then
            lbmd := lbmd + 1;
        fi;
        if ubmd mod 2 = 1 then
            ubmd := ubmd + 1;
        fi;
        C!.lowerBoundMinimumDistance := lbmd;
		C!.upperBoundMinimumDistance := ubmd;
		if HasInnerDistribution(Cold) then
            indist := NullVector(n+1);
            indist[1] := InnerDistribution(Cold)[1];
            for i in [1 .. QuoInt( WordLength(Cold), 2 ) ] do
                indist[i*2+1]:= InnerDistribution(Cold)[i*2+1]+
                                    InnerDistribution(Cold)[i*2];
            od;
            if IsOddInt(WordLength(Cold)) then
                indist[WordLength(Cold) + 2] :=
                  InnerDistribution(Cold)[WordLength(Cold) + 1];
            fi;
        	SetInnerDistribution(C, indist);
		fi;
        if HasWeightDistribution(Cold) then
            wd := NullVector( n + 1);
            wd[1] := WeightDistribution(Cold)[1];
            for i in [1 .. QuoInt( WordLength(Cold), 2 ) ] do
                wd[i*2+1]:= WeightDistribution(Cold)[i*2+1]+
                                WeightDistribution(Cold)[i*2];
            od;
            if IsOddInt(WordLength(Cold)) then
                wd[WordLength(Cold) + 2] :=
                  WeightDistribution(Cold)[WordLength(Cold) + 1];
            fi;
        	SetWeightDistribution(C, wd);
		fi;
        if IsBound(Cold!.boundsCoveringRadius)
           and Length( Cold!.boundsCoveringRadius ) = 1 then
            C!.boundsCoveringRadius :=
              [ Cold!.boundsCoveringRadius[ 1 ] + nrcolumns ];
        fi;
    else
        C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(Cold) + 1;
    fi;
    C!.history := History(Cold);
    return C;
end);

InstallOtherMethod(ExtendedCode, "method for unrestricted code",
	true, [IsCode], 0,
function(C)
	return ExtendedCode(C, 1);
end);

InstallMethod(ExtendedCode, "method to extend linear code i times", true,
	[IsLinearCode, IsInt], 0,
function(Cold, nrcolumns)
    local C, G, word, zeros, i, n, q, lbmd, ubmd, wd;
	if nrcolumns < 1 then
		return ShallowCopy(C);
	fi;

    n := WordLength(Cold) + nrcolumns;
    zeros := List( [2 .. nrcolumns], i-> Zero(LeftActingDomain(Cold)) );
    q := Size(LeftActingDomain(Cold));
    G := List(GeneratorMat(Cold), i-> ShallowCopy(i));
    for word in G do
        Add(word, -Sum(word));
        Append(word, zeros);
    od;
    C := GeneratorMatCode(G, "extended code", q);
    lbmd := LowerBoundMinimumDistance(Cold);
    ubmd := UpperBoundMinimumDistance(Cold);
    if q = 2 then
        if IsOddInt( lbmd ) then
            lbmd := lbmd + 1;
        fi;
        if IsOddInt( ubmd ) then
            ubmd := ubmd + 1;
        fi;
        C!.lowerBoundMinimumDistance := lbmd;
		C!.upperBoundMinimumDistance := ubmd;
		if HasWeightDistribution(Cold) then
            wd := NullVector(n + 1);
            wd[1] := 1;
            for i in [ 1 .. QuoInt( WordLength(Cold), 2 ) ] do
                wd[i*2+1]:=WeightDistribution(Cold)[i*2+1]+
                                 WeightDistribution(Cold)[i*2];
            od;
            if IsOddInt(WordLength(Cold)) then
                wd[WordLength(Cold) + 2] :=
                  WeightDistribution(Cold)[WordLength(Cold) + 1];
            fi;
        	SetWeightDistribution(C, wd);
		fi;
        if IsBound(Cold!.boundsCoveringRadius)
           and Length( Cold!.boundsCoveringRadius ) = 1 then
            C!.boundsCoveringRadius :=
              [ Cold!.boundsCoveringRadius[ 1 ] + nrcolumns ];
        fi;
    else
        C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(Cold) + 1;
    fi;
    C!.history := History(Cold);
    return C;
end);


#############################################################################
##
#F  ShortenedCode( <C> [, <L>] )  . . . . . . . . . . . . . .  shortened code
##
##

InstallMethod(ShortenedCode, "Method for unrestricted code, position list",
	true, [IsCode, IsList], 0,
function(C, L)
    local Cnew, i, e, zero, q, baseels, element, max, number,
          temp, els, n;
	if IsLinearCode(C) then
		return ShortenedCode(C,L);
	fi;
	L := Reversed(Set(L));
    zero := Zero(LeftActingDomain(C));
    baseels := AsSSortedList(LeftActingDomain(C));
    q := Size(LeftActingDomain(C));
    els := VectorCodeword(AsSSortedList(C));
    for i in L do
        temp := List(els, x -> x[i]);
        max := 0;
        for e in baseels do
            number := Length(Filtered(temp, x -> x=e));
            if number > max then
                max := number;
                element := e;
            fi;
        od;
        temp := [];
        n := Length(els[1]);
        for e in els do
            if e[i] = element then
                Add(temp,Concatenation(e{[1..i-1]},e{[i+1..n]}));
            fi;
            els := temp;
        od;
    od;
    Cnew := ElementsCode(temp, "shortened code", LeftActingDomain(C));
    Cnew!.history := History(C);
    Cnew!.lowerBoundMinimumDistance := Minimum(LowerBoundMinimumDistance(C),
                                              WordLength(Cnew));
    return Cnew;
end);

InstallOtherMethod(ShortenedCode, "method for unrestricted code, int position",
	true, [IsCode, IsInt], 0,
function(C, i)
	return ShortenedCode(C, [i]);
end);

InstallOtherMethod(ShortenedCode, "method for unrestricted code", true,
	[IsCode], 0,
function(C)
	return ShortenedCode(C, [1]);
end);

InstallMethod(ShortenedCode, "method for linear code and position list",
	true, [IsLinearCode, IsList], 0,
function(C, L)
	local Cnew, G, i, e, zero, q, baseels, temp, n;
	L := Reversed(Set(L));
    zero := Zero(LeftActingDomain(C));
    baseels := AsSSortedList(LeftActingDomain(C));
    q := Size(LeftActingDomain(C));
    G := ShallowCopy(GeneratorMat(C));
    for i in L do
        e := 0;
        repeat
            e := e + 1;
        until (e > Length(G)) or (G[e][i] <> zero);
        if G <> [] then
            n := Length(G[1]);
        else
            n := WordLength(C);
        fi;
        if e <= Length(G) then
            temp := G[e];
            G := Concatenation(G{[1..e-1]},G{[e+1..Length(G)]});
            G := List(G, x-> x - temp * (x[i] / temp[i]));
        fi;
        G := List(G, x->Concatenation(x{[1..i-1]},x{[i+1..n]}));
        if G = [] then
            return NullCode(WordLength(C)-Length(L), LeftActingDomain(C));
        fi;
    od;
    Cnew := GeneratorMatCode(BaseMat(G), "shortened code", LeftActingDomain(C));
    Cnew!.history := History(C);
    Cnew!.lowerBoundMinimumDistance := Minimum(LowerBoundMinimumDistance(C),
                                              WordLength(Cnew));
	if IsCyclicCode(C) then
		Cnew!.upperBoundMinimumDistance := Minimum(WordLength(Cnew),
											UpperBoundMinimumDistance(C));

	fi;
	return Cnew;
end);


#############################################################################
##
#F  PuncturedCode( <C> [, <list>] ) . . . . . . . . . . . . .  punctured code
##
##  PuncturedCode(C [, remlist]) punctures a code by leaving out the
##  coordinates given in list remlist. If remlist is omitted, then
##  the last coordinate will be removed.
##

InstallMethod(PuncturedCode,
	"method for unrestricted codes, position list provided",
	true, [IsCode, IsList], 0,
function(Cold, remlist)
	local keeplist, n, C;
	if IsLinearCode(Cold) then
		return PuncturedCode(Cold, remlist);
	fi;
	n := WordLength(Cold);
	remlist := Set(remlist);
	keeplist := [1..n];
	SubtractSet(keeplist, remlist);
    C := ElementsCode(
                 VectorCodeword(Codeword(
				 	AsSSortedList(Cold))){[1 .. Size(Cold)]}{keeplist},
                 "punctured code", LeftActingDomain(Cold));
    C!.history := History(Cold);
    C!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(Cold) -
                                           Length(remlist), 1);
    C!.upperBoundMinimumDistance := Minimum( Maximum( 1,
                                           UpperBoundMinimumDistance(Cold) ),
                                           n-Length(remlist));
    return C;
end);

InstallOtherMethod(PuncturedCode,
	"method for unrestricted codes, int position provided",
	true, [IsCode, IsInt], 0,
function(C, n)
	return PuncturedCode(C, [n]);
end);

InstallOtherMethod(PuncturedCode, "method for unrestricted codes", true,
	[IsCode], 0,
function(C)
	return PuncturedCode(C, [WordLength(C)]);
end);

InstallMethod(PuncturedCode, "method for linear codes, position list provided",
	true, [IsLinearCode, IsList], 0,
function(Cold, remlist)
	local C, keeplist, n;
	n := WordLength(Cold);
	remlist := Set(remlist);
	keeplist := [1..n];
	SubtractSet(keeplist, remlist);
    C := GeneratorMatCode(
                 GeneratorMat(Cold){[1..Dimension(Cold)]}{keeplist},
                 "punctured code", LeftActingDomain(Cold) );
    C!.history := History(Cold);
    C!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(Cold) -
                                           Length(remlist), 1);

# Cyclic codes always have at least one codeword with minimal weight in the
# i-th column (for every i), so if you remove a column, that word has a
# weight of one less -> the minimumdistance is reduced by one
	if IsCyclicCode(Cold) then
		C!.upperBoundMinimumDistance := Minimum( Maximum( 1,
									   UpperBoundMinimumDistance(Cold)-1),
									   n - Length(remlist) );
	else
		C!.upperBoundMinimumDistance := Minimum( Maximum( 1,
                                           UpperBoundMinimumDistance(Cold) ),
                                           n - Length(remlist));
    fi;
	return C;
end);


#############################################################################
##
#F  ExpurgatedCode( <C>, <L> )  . . . . .  removes codewords in <L> from code
##
##  The usual way of expurgating a code is removing all words of odd weight.
##

InstallMethod(ExpurgatedCode, "method for unrestricted codes, codeword list",
	true, [IsCode, IsList], 0,
function(C, L)
	if IsLinearCode(C) then
		return ExpurgatedCode(C, L);
	else
		Error("can't expurgate a non-linear code; ",
			  "consider using RemovedElementsCode");
	fi;
end);

InstallOtherMethod(ExpurgatedCode, "method for unrestricted code, codeword",
	true, [IsCode, IsCodeword], 0,
function(C, w)
	return ExpurgatedCode(C, [w]);
end);

InstallOtherMethod(ExpurgatedCode, "method for unrestricted code", true,
	[IsCode], 0,
function(C)
	if IsLinearCode(C) then
		return ExpurgatedCode(C);
	else
		Error("can't expurgate a non-linear code; ");
	fi;
end);

InstallMethod(ExpurgatedCode, "method for linear code, codeword list",
	true, [IsLinearCode, IsList], 0,
function(Cold, L)
    local C, num, H, F;
	L := VectorCodeword( L );
	L := Set(L);
    F := LeftActingDomain(Cold);
    L := Filtered(L, l-> Codeword(l) in Cold);
    H := List(L, function(l)
        local V,p;
        V := NullVector(WordLength(Cold), F);
        p := PositionProperty(l, i-> not (i = Zero(F)));
        if not (p = false) then
            V[p] := One(F);
        fi;
        return V;
    end);
	H := BaseMat(Concatenation(CheckMat(Cold), H));
    num := Length(H) - Redundancy(Cold);
    if num > 0 then
        C := CheckMatCode( H, Concatenation("code, expurgated with ",
                     String(num), " word(s)"), F);
        C!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(Cold);
        C!.history := History(Cold);
        return C;
    else
        return ShallowCopy(Cold);
    fi;
end);

InstallOtherMethod(ExpurgatedCode, "method for linear code", true,
	[IsLinearCode], 0,
function(C)
	local C2;
	C2 := EvenWeightSubcode(C);
	##LR - prob if C2 not lin.  Try on DualCode(RepetitionCode(5, GF(3)))
	if Dimension(C2) = Dimension(C) then
		## No words of odd weight, so expurgate by removing first row of
		## generator matrix.
		return ExpurgatedCode(C, Codeword(GeneratorMat(C)[1]));
	else
		return C2;
	fi;
end);


#############################################################################
##
#F  AddedElementsCode( <C>, <L> ) . . . . . . . . . .  adds words in list <L>
##

InstallMethod(AddedElementsCode, "method for unrestricted code, codeword list",
	true, [IsCode, IsList], 0,
function(C, L)
    local Cnew, e, w, E, CalcWD, wd, num;
    L := VectorCodeword( L );
	L := Set(L);
    E := ShallowCopy(VectorCodeword(AsSSortedList(C)));
    if HasWeightDistribution(C) then
        wd := ShallowCopy(WeightDistribution(C));
        CalcWD := true;
    else
        CalcWD := false;
    fi;
    num := 0;
    for e in L do
        if not (e in C) then
            Add(E, e);
            num := num + 1;
            if CalcWD then
                w := Weight(Codeword(e)) + 1;
                wd[w] := wd[w] + 1;
            fi;
        fi;
    od;
    if num > 0 then
        Cnew := ElementsCode(E, Concatenation( "code with ", String(num),
                " word(s) added"), LeftActingDomain(C));
        if CalcWD then
            SetWeightDistribution(Cnew, wd);
        fi;
        Cnew!.history := History(C);
        return Cnew;
    else
        return ShallowCopy(C);
    fi;
end);

InstallOtherMethod(AddedElementsCode, "method for unrestricted code, codeword",
	true, [IsCode, IsCodeword], 0,
function(C, w)
	return AddedElementsCode(C, [w]);
end);


#############################################################################
##
#F  RemovedElementsCode( <C>, <L> ) . . . . . . . . removes words in list <L>
##

InstallMethod(RemovedElementsCode,
	"method for unrestricted code, codeword list",
	true, [IsCode, IsList], 0,
function(C, L)
    local E, E2, e, num, s, CalcWD, wd, w, Cnew;
    L := VectorCodeword( L );
    E := Set(VectorCodeword(AsSSortedList(C)));
    E2 := [];
    if HasWeightDistribution(C) then
        wd := ShallowCopy(WeightDistribution(C));
        CalcWD := true;
    else
        CalcWD := false;
    fi;
    for e in E do
        if not (e in L) then
            Add(E2, e);
        elif CalcWD then
            w := Weight(Codeword(e)) + 1;
            wd[w] := wd[w] - 1;
        fi;
    od;
    num := Size(E) - Size(E2);
    if num > 0 then
        Cnew := ElementsCode(E2, Concatenation( "code with ", String(num),
                " word(s) removed"), LeftActingDomain(C) );
        if CalcWD then
            SetWeightDistribution(Cnew, wd);
        fi;
        Cnew!.history := History(C);
        Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
        return Cnew;
    else
        return ShallowCopy(C);
    fi;
end);

InstallOtherMethod(RemovedElementsCode,
	"method for unrestricted code, codeword",
	true, [IsCode, IsCodeword], 0,
function(C, w)
	return RemovedElementsCode(C, [w]);
end);


#############################################################################
##
#F  LengthenedCode( <C> [, <i>] ) . . . . . . . . . . . . . .  lengthens code
##

InstallMethod(LengthenedCode, "method for unrestricted code, number of columns",
	true, [IsCode, IsInt], 0,
function(C, nrcolumns)
    local Cnew;
    Cnew := ExtendedCode(AugmentedCode(C), nrcolumns);
    Cnew!.history := History(C);
    Cnew!.name := Concatenation("code, lengthened with ",String(nrcolumns),
            " column(s)");
    return Cnew;
end);

InstallOtherMethod(LengthenedCode, "unrestricted code", true, [IsCode], 0,
function(C)
	return LengthenedCode(C, 1);
end);


#############################################################################
##
#F  ResidueCode( <C> [, <w>] )  . .  takes residue of <C> with respect to <w>
##
##  If w is omitted, a word from C of minimal weight is used
##

InstallMethod(ResidueCode, "method for unrestricted code, codeword", true,
	[IsCode, IsCodeword], 0,
function(C, w)
	if not IsLinearCode(C) then
		Error("argument must be a linear code");
	else
		return ResidueCode(C, w);
	fi;
end);

InstallOtherMethod(ResidueCode, "method for unrestricted code", true,
	[IsCode], 0,
function(C)
	if not IsLinearCode(C) then
		Error("argument must be a linear code");
	else
		return ResidueCode(C);
	fi;
end);

InstallOtherMethod(ResidueCode, "method for linear code", true,
	[IsLinearCode], 0,
function(C)
    local w, i, d;
	d := MinimumDistance(C);
	i := 2;
	while Weight(CodewordNr(C, i)) > d do
		i := i + 1;
	od;
	w := CodewordNr(C, i);
    return ResidueCode(C, w);
end);

InstallMethod(ResidueCode, "method for linear code, codeword", true,
	[IsLinearCode, IsCodeword], 0,
function(C, w)
    local Cnew, q, d;
    if Weight(w) = 0 then
		Error("word of weight 0 is not allowed");
	elif Weight(w) = WordLength(C) then
		Error("all-one word is not allowed");
	fi;
	Cnew := PuncturedCode(ExpurgatedCode(C, w), Support(w));
    q := Size(LeftActingDomain(C));
    d := MinimumDistance(C) - Weight(w) * ( (q-1) / q );
    if not IsInt(d) then
        d := Int(d) + 1;
    fi;
    Cnew!.lowerBoundMinimumDistance := d;
    Cnew!.history := History(C);
    Cnew!.name := "residue code";
    return Cnew;
end);


#############################################################################
##
#F  ConstructionBCode( <C> )  . . . . . . . . . . .  code from construction B
##
##  Construction B (See M&S, Ch. 18, P. 9) assumes that the check matrix has
##  a first row of weight d' (the dual distance of C). The new code has a
##  check matrix equal to this matrix, but with columns removed where the
##  first row is 1.
##

InstallMethod(ConstructionBCode, "method for unrestricted codes", true,
	[IsCode], 0,
function(C)
	if LeftActingDomain(C) <> GF(2) then
		Error("only valid for binary codes");
	elif IsLinearCode(C) then
		return ConstructionBCode(C);
	else
		Error("only valid for linear codes");
	fi;
end);

InstallMethod(ConstructionBCode, "method for linear codes", true,
	[IsLinearCode], 0,
function(C)
    local i, H, dd, M, mww, Cnew, DC, keeplist;
	if LeftActingDomain(C) <> GF(2) then
		Error("only valid for binary codes");
	fi;
	DC := DualCode(C);
    H := ShallowCopy(GeneratorMat(DC));        # is check matrix of C
    M := Size(DC);
    dd := MinimumDistance(DC);          # dual distance of C
    i := 2;
    repeat
        mww := CodewordNr(DC, i);
        i := i + 1;
    until Weight(mww) = dd;
    i := i - 2;
    keeplist := Set([1..WordLength(C)]);
    SubtractSet(keeplist, Support(mww));
    mww := VectorCodeword(mww);
    # make sure no row dependencies arise;
    H[Redundancy(C)-LogInt(i, Size(LeftActingDomain(C)))] := mww;
    H := List(H, h -> h{keeplist});
    Cnew := CheckMatCode(H, Concatenation("Construction B (",String(dd),
            " coordinates)"), LeftActingDomain(C));
    Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    Cnew!.history := History(DC);
    return Cnew;
end);

#############################################################################
##
#F  ConstructionB2Code( <C> )  . . . . . . . . . .  code from construction B2
##
##  Construction B2 is mixtures of shortening and puncturing. Given an
##  [n,k,d] code which has dual code of minimum distance s, we obtain
##  an [n-s, k-s+2j+1, d-2j] code for each j with 2j+1 < s.
##
##  For more details, see A. Brouwer (1998), "Bounds on the size of linear
##  codes,", in Handbook of Coding Theory, V. S. Pless and W. C. Huffmann
##  ed., pp. 311
##
##  added by CJ, April 2006  -  FIXME this function is NOT complete
##

InstallMethod(ConstructionB2Code, "method for unrestricted codes", true,
	[IsCode], 0,
function(C)
	Error("ConstructionB2 is not implemented yet ....... sorry\n");
end);

#############################################################################
##
#F  SubCode( <C>, [<s>] ) . .  . . . . . . . . . . . . . . . . subcode of C
##
##  Given C, an [n,k,d] code, return a subcode of C with dimension k-s.
##  If s is not given, it is assumed to be 1.
##
##  added by CJ, April 2006  -  FIXME this function is NOT complete
##

InstallMethod(SubCode, "method for linear codes, int provided", true,
	[IsCode, IsInt], 0,
function(C, s)
	local G, Gs, Cs;
	if (IsLinearCode(C) = false) then
		Error("SubCode only works for linear code\n");
	fi;
	if (Dimension(C)-s = 0) then
		return NullCode(CodeLength(C), LeftActingDomain(C));
	elif (Dimension(C) <= s) then
		Error("Dimension of the code must be greater than s\n");
	else
		G  := ShallowCopy(GeneratorMat(C));
		Gs := List([1..Length(G)-s], x->G[x]);
   	 	Cs := GeneratorMatCode(BaseMat(Gs), "subcode", LeftActingDomain(C));
	    Cs!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(C), 1);
    	Cs!.upperBoundMinimumDistance := Minimum(Maximum(1, UpperBoundMinimumDistance(C)), CodeLength(C));
    	Cs!.history := History(C);
    	return Cs;
	fi;
end);

InstallOtherMethod(SubCode, "method for linear codes", true,
	[IsCode], 0,
function(C)
	return SubCode(C, 1);
end);

#############################################################################
##
#F  PermutedCode( <C>, <P> )  . . . . . . . permutes coordinates of codewords
##

InstallMethod(PermutedCode, "method for unrestricted codes", true,
	[IsCode, IsPerm], 0,
function(Cold, P)
	local C, field, fields;
	if IsCyclicCode(Cold) or IsLinearCode(Cold) then
		return PermutedCode(Cold, P);
	fi;

    C := ElementsCode(
				PermutedCols(VectorCodeword(Codeword(AsSSortedList(Cold))), P),
                "permuted code", LeftActingDomain(Cold));
    # Copy the fields that stay the same:
    fields := [WeightDistribution, InnerDistribution, IsPerfectCode,
				IsSelfDualCode, MinimumDistance, CoveringRadius];
	for field in fields do
		if Tester(field)(Cold) then
			Setter(field)(C, field(Cold));
		fi;
	od;
	fields := ["lowerBoundMinimumDistance", "upperBoundMinimumDistance",
				"boundsCoveringRadius"];
	for field in fields do
		if IsBound(Cold!.(field)) then
			C!.(field) := Cold!.(field);
		fi;
	od;
	C!.history := History(Cold);
    return C;
end);

InstallMethod(PermutedCode, "method for linear codes", true,
	[IsLinearCode, IsPerm], 0,
function(Cold, P)
	local C, field, fields;
	if IsCyclicCode(Cold) then
		return PermutedCode(Cold, P);
	fi;
    C := GeneratorMatCode(
                 PermutedCols(GeneratorMat(Cold), P),
                 "permuted code", LeftActingDomain(Cold));
    # Copy the fields that stay the same:
    fields := [WeightDistribution, IsPerfectCode, IsSelfDualCode,
				MinimumWeightOfGenerators, MinimumDistance, CoveringRadius];
	for field in fields do
        if Tester(field)(Cold) then
			Setter(field)(C, field(Cold));
		fi;
	od;
	fields := ["lowerBoundMinimumDistance", "upperBoundMinimumDistance",
				"boundsCoveringRadius"];
	for field in fields do
        if IsBound(Cold!.(field)) then
			C!.(field) := Cold!.(field);
		fi;
	od;
	C!.history := History(Cold);
    return C;
end);

InstallMethod(PermutedCode, "method for cyclic codes", true,
	[IsCyclicCode, IsPerm], 0,
function(Cold, P)
    local C, field, fields;
    C := GeneratorMatCode(
                 PermutedCols(GeneratorMat(Cold), P),
                 "permuted code", LeftActingDomain(Cold) );
    # Copy the fields that stay the same:
	fields := [WeightDistribution, IsPerfectCode, IsSelfDualCode,
                MinimumWeightOfGenerators, MinimumDistance, CoveringRadius,
				UpperBoundOptimalMinimumDistance];
	for field in fields do
		if Tester(field)(Cold) then
	        Setter(field)(C, field(Cold));
	    fi;
	od;
	fields := ["lowerBoundMinimumDistance", "upperBoundMinimumDistance",
	            "boundsCoveringRadius"];
	for field in fields do
	    if IsBound(Cold!.(field)) then
	        C!.(field) := Cold!.(field);
	    fi;
	od;

    C!.history := History(Cold);
    return C;
end);


#############################################################################
##
#F  StandardFormCode( <C> ) . . . . . . . . . . . . standard form of code <C>
##

##LR - all of these methods used to use a ShallowCopy, but that doesn't
##	   allow for unbinding/unsetting of attributes.  So now a whole new
##	   code is created.  However, should figure out what can be saved and
##	   use that.

InstallMethod(StandardFormCode, "method for unrestricted code", true,
	[IsCode], 0,
function(C)
	local Cnew;
	if IsLinearCode(C) then
		return StandardFormCode(C);
	fi;
	Cnew := ElementsCode(AsSSortedList(C), "standard form",
						 LeftActingDomain(C));
	Cnew!.history := History(C);
	return Cnew;
end);

InstallMethod(StandardFormCode, "method for linear codes", true,
	[IsLinearCode], 0,
function(C)
	local G, P, Cnew;
	G := ShallowCopy(GeneratorMat(C));
	P := PutStandardForm(G, true, LeftActingDomain(C));
	if P = () then
		Cnew := ShallowCopy(C);
		# this messes up code names
		#Cnew!.name := "standard form";
	else
		Cnew := GeneratorMatCode(G,
			Concatenation("standard form, permuted with ",
			               String(P)),
				      LeftActingDomain(C));
	fi;
	Cnew!.history := History(C);
	return Cnew;
end);


#############################################################################
##
#F  ConversionFieldCode( <C> )  . . . . . converts code from GF(q^m) to GF(q)
##

InstallMethod(ConversionFieldCode, "method for unrestricted code", true,
	[IsCode], 0,
function (C)
	local F, x, q, m, i, ConvertElms, Cnew;
	if IsLinearCode(C) then
		return ConversionFieldCode(C);
	fi;

    ConvertElms := function (M)
        local res,n,k,vec,coord, ConvTable, Nul, g, zero;
        res := [];
        n := Length(M[1]);
        k := Length(M);
        g := MinimalPolynomial(GF(q), Z(q^m));
        zero := Zero(F);
        Nul := List([1..m], i -> zero);
        ConvTable := [];
        x := Indeterminate(GF(q));
        for i in [1..Size(F) - 1] do
            ConvTable[i] := VectorCodeword(Codeword(x^(i-1) mod g, m));
        od;
        for vec in [1..k] do
            res[vec] := [];
            for coord in [1..n] do
                if M[vec][coord] <> zero then
                    Append(res[vec],
							ConvTable[LogFFE(M[vec][coord], Z(q^m)) + 1]);
                else
                    Append(res[vec], Nul);
                fi;
            od;
        od;
        return res;
    end;

    F := LeftActingDomain(C);
    q := Characteristic(F);
    m := Dimension(F);
    Cnew := ElementsCode(
                    ConvertElms(VectorCodeword(AsSSortedList(C))),
                    Concatenation("code, converted to basefield GF(",
                            String(q),")"),
                    F );
    Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    Cnew!.upperBoundMinimumDistance := Minimum(WordLength(C),
                                              m*UpperBoundMinimumDistance(C));
    Cnew!.history := History(C);
    return Cnew;
end);

InstallOtherMethod(ConversionFieldCode, "method for linear code", true,
	[IsLinearCode], 0,
function(C)
    local F, Cnew;
    F := LeftActingDomain(C);
    Cnew := GeneratorMatCode(
                    HorizontalConversionFieldMat( GeneratorMat(C), F),
                    Concatenation("code, converted to basefield GF(",
                            String(Characteristic(F)), ")"),
                    GF(Characteristic(F)));
    Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    Cnew!.upperBoundMinimumDistance := Minimum(WordLength(C),
                                 Dimension(F) * UpperBoundMinimumDistance(C));
    Cnew!.history := History(C);
    return Cnew;
end);


#############################################################################
##
#F  CosetCode( <C>, <f> ) . . . . . . . . . . . . . . . . . . .  coset of <C>
##

InstallMethod(CosetCode, "method for unrestricted codes", true,
	[IsCode, IsCodeword], 0,
function(C, f)
	local i, els, Cnew;
	if IsLinearCode(C) then
		return CosetCode(C, f);
	fi;
    f := Codeword(f, LeftActingDomain(C));
    els := [];
    for i in [1..Size(C)] do
        Add(els, AsSSortedList(C)[i] + f);
    od;
    Cnew := ElementsCode(els, "coset code", LeftActingDomain(C) );
    Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    Cnew!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C);
    Cnew!.history := History(C);
    return Cnew;
end);

InstallMethod(CosetCode, "method for linear codes", true,
	[IsLinearCode, IsCodeword], 0,
function(C, f)
    local Cnew, i, els, Cels;
    f := Codeword(f, LeftActingDomain(C));
    if f in C then
        return ShallowCopy(C);
    fi;
    els := [];
    Cels := AsSSortedList(C);
    for i in [1..Size(C)] do
        Add(els, Cels[i] + f);
    od;
    Cnew := ElementsCode(els, "coset code", LeftActingDomain(C) );
	if HasWeightDistribution(C) then
        SetInnerDistribution(Cnew, ShallowCopy(WeightDistribution(C)));
    fi;
    Cnew!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C);
    Cnew!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C);
    Cnew!.history := History(C);
    return Cnew;
end);


#############################################################################
##
#F  DirectSumCode( <C1>, <C2> ) . . . . . . . . . . . . . . . . .  direct sum
##
##  DirectSumCode(C1, C2) creates a (n1 + n2 , M1 M2 , min{d1 , d2} ) code
##  by adding each codeword of the second code to all the codewords of the
##  first code.
##

InstallMethod(DirectSumCode, "method for unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	local i, j, C, els, n, sumcr, wd, id;
	if IsLinearCode(C1) and IsLinearCode(C2) then
        return DirectSumCode(C1, C2);
	fi;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
        Error("Codes are not in the same basefield");
	fi;

    els := [];
    for i in VectorCodeword(AsSSortedList(C1)) do
        Append(els,List(VectorCodeword(AsSSortedList(C2)),
                x-> Concatenation(i, x ) ) );
    od;
    C := ElementsCode( els, "direct sum code", LeftActingDomain(C1) );
    n := WordLength(C1) + WordLength(C2);
    if Size(C) <= 1 then
        C!.lowerBoundMinimumDistance := n;
        C!.upperBoundMinimumDistance := n;
    else
        C!.lowerBoundMinimumDistance := Minimum(LowerBoundMinimumDistance(C1),
                                               LowerBoundMinimumDistance(C2));
        C!.upperBoundMinimumDistance := Minimum(UpperBoundMinimumDistance(C1),
                                               UpperBoundMinimumDistance(C2));
    fi;
    if HasWeightDistribution(C1) and HasWeightDistribution(C2) then
        wd := NullVector(WordLength(C)+1);
        for i in [1..WordLength(C1)+1] do
            for j in [1..WordLength(C2)+1] do
                wd[i+j-1] := wd[i+j-1]+
                             WeightDistribution(C1)[i] *
                             WeightDistribution(C2)[j];
            od;
        od;
    	SetWeightDistribution(C, wd);
	fi;
    if HasInnerDistribution(C1) and HasInnerDistribution(C2) then
        id := NullVector(WordLength(C) + 1);
        for i in [1..WordLength(C1) + 1 ] do
            for j in [1..WordLength(C2) + 1 ] do
                id[i+j-1] := id[i+j-1]+
                             InnerDistribution(C1)[i] *
                             InnerDistribution(C2)[j];

            od;
        od;
		SetInnerDistribution(C, id);
	fi;
    if IsBound(C1!.boundsCoveringRadius)
       and IsBound(C2!.boundsCoveringRadius) then
        sumcr := List( C1!.boundsCoveringRadius,
          x -> x + C2!.boundsCoveringRadius);
        sumcr := Set( Flat( sumcr ) );
        IsRange( sumcr );
        C!.boundsCoveringRadius := sumcr;
    fi;
    C!.history := MergeHistories(History(C1), History(C2));
    return C;
end);

InstallMethod(DirectSumCode, "method for linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local i, j, C, zeros1, zeros2, G, n, sumcr, wd;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
        Error("Codes are not in the same basefield");
	fi;

	zeros1 := NullVector(WordLength(C1), LeftActingDomain(C1));
    zeros2 := NullVector(WordLength(C2), LeftActingDomain(C1));
    G := List(GeneratorMat(C1),x -> Concatenation(x,zeros2));
    Append(G,List(GeneratorMat(C2),x -> Concatenation(zeros1,x)));
    C := GeneratorMatCode( G, "direct sum code", LeftActingDomain(C1) );
    n := WordLength(C1) + WordLength(C2);
    if Size(C) <= 1 then
        C!.lowerBoundMinimumDistance := n;
        C!.upperBoundMinimumDistance := n;
    else
        C!.lowerBoundMinimumDistance := Minimum(LowerBoundMinimumDistance(C1),
                                               LowerBoundMinimumDistance(C2));
        C!.upperBoundMinimumDistance := Minimum(UpperBoundMinimumDistance(C1),
                                               UpperBoundMinimumDistance(C2));
    fi;
    if HasWeightDistribution(C1) and HasWeightDistribution(C2) then
        wd := NullVector(WordLength(C)+1);
        for i in [1..WordLength(C1)+1] do
            for j in [1..WordLength(C2)+1] do
                wd[i+j-1] := wd[i+j-1]+
                             WeightDistribution(C1)[i] *
                             WeightDistribution(C2)[j];
            od;
        od;
    	SetWeightDistribution(C, wd);
	fi;
    if IsBound(C1!.boundsCoveringRadius)
       and IsBound(C2!.boundsCoveringRadius) then
        sumcr := List( C1!.boundsCoveringRadius,
          x -> x + C2!.boundsCoveringRadius);
        sumcr := Set( Flat( sumcr ) );
        IsRange( sumcr );
        C!.boundsCoveringRadius := sumcr;
    fi;
    if HasIsNormalCode(C1) and HasIsNormalCode(C2) and
       IsNormalCode( C1 ) and IsNormalCode( C2 ) then
        SetIsNormalCode(C, true);
    fi;
    if HasIsSelfOrthogonalCode(C1) and HasIsSelfOrthogonalCode(C2)
       and IsSelfOrthogonalCode(C1) and IsSelfOrthogonalCode(C2) then
        SetIsSelfOrthogonalCode(C, true);
    fi;
    C!.history := MergeHistories(History(C1), History(C2));
    return C;
end);


#############################################################################
##
#F  ConcatenationCode( <C1>, <C2> ) . . . . .  concatenation of <C1> and <C2>
##

InstallMethod(ConcatenationCode, "method for unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	local E,e,C;
	if IsLinearCode(C1) and IsLinearCode(C2) then
		return ConcatenationCode(C1, C2);
	elif Size(C1) <> Size(C2) then
		Error("both codes must have equal size");
	elif LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("both codes must be over the same field");
	fi;

	E := [];
	for e in [1..Size(C1)] do
		Add(E,Concatenation(VectorCodeword(AsSSortedList(C1)[e]),
				VectorCodeword(AsSSortedList(C2)[e])));
	od;
	C := ElementsCode( E, "concatenation code", LeftActingDomain(C1) );
	C!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C1) +
								   LowerBoundMinimumDistance(C2);
	C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C1) +
								   UpperBoundMinimumDistance(C2);
	# CoveringRadius?
	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);


InstallMethod(ConcatenationCode, "method for linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local e, C, G, G1, G2;
	if Size(C1) <> Size(C2) then
        Error("both codes must have equal size");
	elif LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("both codes must be over the same field");
	fi;

	G := [];
	G1 := GeneratorMat(C1);
	G2 := GeneratorMat(C2);
	for e in [1..Dimension(C1)] do
		Add(G, Concatenation(G1[e], G2[e]));
	od;
	C := GeneratorMatCode(G, "concatenation code", LeftActingDomain(C1));
	C!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C1) +
								   LowerBoundMinimumDistance(C2);
	C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C1) +
								   UpperBoundMinimumDistance(C2);
	# CoveringRadius?
	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);


#############################################################################
##
#F  DirectProductCode( <C1>, <C2> ) . . . . . . . . . . . . .  direct product
##
##  DirectProductCode constructs a new code from the direct product of two
##  codes by taking the Kronecker product of the two generator matrices
##

InstallMethod(DirectProductCode, "method for unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	if IsLinearCode(C1) and IsLinearCode(C2) then
		return DirectProductCode(C1,C2);
	else
		Error("both codes must be linear");
	fi;
end);

InstallMethod(DirectProductCode, "method for linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local C;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("both codes must have the same basefield");
	fi;
	C := GeneratorMatCode(
				 KroneckerProduct(GeneratorMat(C1), GeneratorMat(C2)),
				 "direct product code",
				 LeftActingDomain(C1));
	if Dimension(C) = 0 then
		C!.lowerBoundMinimumDistance := WordLength(C);
		C!.upperBoundMinimumDistance := WordLength(C);
	else
		C!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C1) *
									   LowerBoundMinimumDistance(C2);
		C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C1) *
									   UpperBoundMinimumDistance(C2);
	fi;
	C!.history := MergeHistories(History(C1), History(C2));
	if IsBound( C1!.boundsCoveringRadius ) and
	   IsBound( C2!.boundsCoveringRadius ) then
		C!.boundsCoveringRadius := [
		Maximum( WordLength( C1 ) * C2!.boundsCoveringRadius[ 1 ],
				   WordLength( C2 ) * C1!.boundsCoveringRadius[ 1 ] )
		  .. GeneralUpperBoundCoveringRadius( C ) ];
	fi;
	return C;
end);


#############################################################################
##
#F  UUVCode( <C1>, <C2> ) . . . . . . . . . . . . . . .  u | u+v construction
##
##  Uuvcode(C1, C2) # creates a ( 2n , M1 M2 , d = min{2 d1 , d2} ) code
##  with codewords  (u | u + v) for all u in C1 and v in C2
##

InstallMethod(UUVCode, "method for linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local C, F, diff, zeros, zeros2, G, n;
	if LeftActingDomain(C1)<>LeftActingDomain(C2) then
        Error("Codes are not in the same basefield");
	fi;
	F := LeftActingDomain(C1);
	n := WordLength(C1)+Maximum(WordLength(C1),WordLength(C2));
	diff := WordLength(C1)-WordLength(C2);
	zeros := NullVector(WordLength(C1), F);
	zeros2 := NullVector(AbsInt(diff), F);
	if diff < 0 then
		G := List(GeneratorMat(C1),u -> Concatenation(u,u,zeros2));
		Append(G,List(GeneratorMat(C2),v -> Concatenation(zeros,v)));
	else
		G:=List(GeneratorMat(C1),u -> Concatenation(u,u));
		Append(G,List(GeneratorMat(C2),v->Concatenation(zeros,v,zeros2)));
	fi;
	C := GeneratorMatCode( G, "U|U+V construction code", F );
	if Dimension(C1) = 0 then
		if Dimension(C2) = 0 then
			C!.lowerBoundMinimumDistance := n;
			C!.upperBoundMinimumDistance := n;
		else
			C!.lowerBoundMinimumDistance := LowerBoundMinimumDistance(C2);
			C!.upperBoundMinimumDistance := UpperBoundMinimumDistance(C2);
		fi;
	elif Dimension(C2) = 0 then
		C!.lowerBoundMinimumDistance := 2*LowerBoundMinimumDistance(C1);
		C!.upperBoundMinimumDistance := 2*UpperBoundMinimumDistance(C1);
	else
		C!.lowerBoundMinimumDistance := Minimum(
			2*LowerBoundMinimumDistance(C1),LowerBoundMinimumDistance(C2));
		C!.upperBoundMinimumDistance := Minimum(
			2*UpperBoundMinimumDistance(C1),UpperBoundMinimumDistance(C2));
	fi;

	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);

InstallMethod(UUVCode, "method for unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	local C, F, i, M1, diff, zeros, extended, Els1, Els2, els, n;
    if LeftActingDomain(C1)<>LeftActingDomain(C2) then
		Error("Codes are not in the same basefield");
	elif IsLinearCode(C1) and IsLinearCode(C2) then
		return UUVCode(C1, C2);
	fi;
	F := LeftActingDomain(C1);
	n := WordLength(C1)+Maximum(WordLength(C1),WordLength(C2));
	diff := WordLength(C1)-WordLength(C2);
	M1 := Size(C1);
	zeros := NullVector(AbsInt(diff), F);
	els := [];
	Els1 := AsSSortedList(C1);
	Els2 := AsSSortedList(C2);
	if diff>0 then
		extended := List(Els2,x->Concatenation(VectorCodeword(x),zeros));
		for i in [1..M1] do
			Append(els, List(extended,x-> Concatenation(VectorCodeword(Els1[i]),
					VectorCodeword(Els1[i]) + x ) ) );
		od;
	elif diff<0 then
		for i in [1..M1] do
			extended := Concatenation(VectorCodeword(Els1[i]),zeros);
			Append(els,List(Els2,x-> Concatenation(VectorCodeword(Els1[i]),
					extended + VectorCodeword(x) ) ) );
		od;
	else
		for i in [1..M1] do
			Append(els,List(Els2,x-> Concatenation(VectorCodeword(Els1[i]),
					VectorCodeword(Els1[i]) + VectorCodeword(x) ) ) );
		od;
	fi;
	C := ElementsCode(els, "U|U+V construction code", F);
	C!.lowerBoundMinimumDistance := Minimum(2*LowerBoundMinimumDistance(C1),
										   LowerBoundMinimumDistance(C2));
	C!.upperBoundMinimumDistance := Minimum(2*UpperBoundMinimumDistance(C1),
										   UpperBoundMinimumDistance(C2));

	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);


#############################################################################
##
#F  UnionCode( <C1>, <C2> ) . . . . . . . . . . . . .  union of <C1> and <C2>
##

InstallMethod(UnionCode, "method for two linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local C, Els, e;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("codes are not in the same basefield");
	elif WordLength(C1) <> WordLength(C2) then
		Error("wordlength must be the same");
	fi;
	C := AugmentedCode(C1, GeneratorMat(C2));
	C!.upperBoundMinimumDistance := Minimum(UpperBoundMinimumDistance(C1),
										   UpperBoundMinimumDistance(C2));
	C!.history := MergeHistories(History(C1), History(C2));
	C!.name := "union code";
	return C;
end);

# should there be a special function for cyclic codes? Or in other words:
# If C1 and C2 are cyclic, does that mean that UnionCode(C1, C2) is cyclic?

InstallMethod(UnionCode, "method for one or both unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	if IsLinearCode(C1) and IsLinearCode(C2) then
		return UnionCode(C1,C2);
	else
		Error("use AddedElementsCode for non-linear codes");
	fi;
end);


#############################################################################
##
#F  IntersectionCode( <C1>, <C2> )  . . . . . . intersection of <C1> and <C2>
##

InstallMethod(IntersectionCode, "method for unrestricted codes", true,
	[IsCode, IsCode], 0,
function(C1, C2)
	local C, Els, e;
	if (IsCyclicCode(C1) and IsCyclicCode(C2)) or
	   (IsLinearCode(C1) and IsLinearCode(C2)) then
		return IntersectionCode(C1, C2);
	fi;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("codes are not in the same basefield");
	elif WordLength(C1) <> WordLength(C2) then
		Error("wordlength must be the same");
	fi;
	Els := [];
	for e in AsSSortedList(C1) do
		if e in C2 then Add(Els, e); fi;
	od;
	if Els = [] then
		return false; # or an Error?
	else
		C := ElementsCode(Els, "intersection code", LeftActingDomain(C1));
	fi;
	C!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(C1),
										   LowerBoundMinimumDistance(C2));
	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);

InstallMethod(IntersectionCode, "method for linear codes", true,
	[IsLinearCode, IsLinearCode], 0,
function(C1, C2)
	local C;
	if IsCyclicCode(C1) and IsCyclicCode(C2) then
		return IntersectionCode(C1, C2);
	fi;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
		Error("codes are not in the same basefield");
	elif WordLength(C1) <> WordLength(C2) then
		Error("wordlength must be the same");
	fi;
	C := DualCode(AugmentedCode(DualCode(C1), CheckMat(C2)));
	C!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(C1),
										   LowerBoundMinimumDistance(C2));
	C!.history := MergeHistories(History(C1), History(C2));
	C!.name := "intersection code";
	return C;
end);

InstallMethod(IntersectionCode, "method for cyclic codes", true,
	[IsCyclicCode, IsCyclicCode], 0,
function(C1, C2)
	local C;
	if LeftActingDomain(C1) <> LeftActingDomain(C2) then
        Error("codes are not in the same basefield");
	elif WordLength(C1) <> WordLength(C2) then
		Error("wordlength must be the same");
	fi;
	C := GeneratorPolCode(
				 Lcm(GeneratorPol(C1), GeneratorPol(C2)), WordLength(C1),
				 "intersection code", LeftActingDomain(C1) );
	if HasRootsOfCode(C1) and HasRootsOfCode(C2) then
		SetRootsOfCode(C, UnionSet(RootsOfCode(C1), RootsOfCode(C2)));
	fi;
	C!.lowerBoundMinimumDistance := Maximum(LowerBoundMinimumDistance(C1),
										   LowerBoundMinimumDistance(C2));
	C!.history := MergeHistories(History(C1), History(C2));
	return C;
end);

#############################################################################
##
#F    ConstructionXCode( <C>, <A> )  ... code from Construction X
##
##
InstallMethod(ConstructionXCode, "linear code constructed using Construction X",
	true, [IsList, IsList], 0,
function( C, A )
	#
	# Construction X (see N. Sloane, S. Reddy and C. Chen, ``New binary codes,''
	#                     IEEE Trans. Inform. Theory, vol. IT-18, pp. 503-510,
	#                     Jul. 1972
	#                )
	#
	# Consider a list of linear codes of the same length N, C := [ C_1, C_2, ... , C_j ],
	# where the parameter of ith code, C_i, is [N, K_i, D_i] and C_1 > C_2 > ... > C_j.
	# Consider a list of (Size(C)-1) auxiliary linear codes A := [ A_1, A_2, ..., A_{j-1} ]
	# where the parameter of ith code A_i is [n_i, k_i=(K_1-K_{i+1}), d_i], a [n, k, d]
	# can be constructed where n = N + (n_1 + n_2 + ... + n_{j-1}), k = K_1, and
	# d = min{ D_j, D_{j-1} + d_{j-1}, D_{j-2} + d_{j-2} + d_{j-1}, ..., D_1 + (d_1 +
	# ... + d_{j-1}) }.
	#
	local i, j, k, p, r,
    	  K, S, GC, GA, GX, CX, ZeroVec;

	# Make sure list C contains all linear codes
	if (PositionNot( List([1..Size(C)], i->IsLinearCode(C[i])), true ) < Size(C)) then
		Error("The list C contains non linear code(s)\n"); return (0);
	fi;

	# Make sure list A contains all linear codes
	if (PositionNot( List([1..Size(A)], i->IsLinearCode(A[i])), true ) < Size(A)) then
		Error("The list A contains non linear code(s)\n"); return (0);
	fi;

	# Make sure all codes in C and A have the same LeftActingDomain
	K:=Filtered([2..Size(C)], i->LeftActingDomain(C[i]) <> LeftActingDomain(C[1]));;
	if Size(K) > 0 then
		Error("Codes in C are not of the same left-acting-domain\n");
	fi;
	S:=Filtered([2..Size(A)], i->LeftActingDomain(A[i]) <> LeftActingDomain(A[1]));;
	if Size(S) > 0 then
		Error("Codes in A are not of the same left-acting-domain\n");
	fi;
	if LeftActingDomain(C[1]) <> LeftActingDomain(A[1]) then
		Error("Codes in C and A are of different left-acting-domain\n");
	fi;

	# Ensure that Dimension(C[1]) < Dimension(C[2]) < ... < Dimension(C[j]), i.e. we need to sort them
	K:=List([1..Size(C)], i->Dimension(C[i]));;
	S:=List([1..Size(C)], i->Dimension(C[i]));;
	Sort(S);;
	C:=List([1..Size(K)], i->C[Position(K, S[i])]);;

	# Need to make sure that C[1] < C[2] < ... < C[j], i.e. subset
	if (PositionNot(List([0..Size(C)-2], i->IsSubset(C[Size(C)-i], C[Size(C)-i-1])), true) < Size(C)-1) then
		Error("Inappropriate chain of codes\n");
	fi;

	# Now, ensure that codes in A are sorted such that their dimensions are in ascending order
	K:=List([1..Size(A)], i->Dimension(A[i]));;
	S:=List([1..Size(A)], i->Dimension(A[i]));;
	Sort(S);;
	A:=List([1..Size(K)], i->A[Position(K, S[i])]);;

	# Number codes in A should be 1 less than that in C
	if (Size(A) <> Size(C)-1) then
		Error("Inappropriate list of codes given\n");
	fi;

	# Need to make sure that the dimension of each of the auxiliary codes (codes in A)
	# is equal to the difference in dimension between the appropriate pair of codes in C.
	for i in [1..Size(A)] do;
		if (Dimension(A[i]) <> (Dimension(C[Size(C)])-Dimension(C[Size(C)-i]))) then
			Error("Inappropriate auxiliary codes\n");
		fi;
	od;

	# Generator matrices of the chain codes
	GC:=List([1..Size(C)], i->ShallowCopy(GeneratorMat(C[i])));;
	GA:=List([1..Size(A)], i->ShallowCopy(GeneratorMat(A[i])));;

	# Generator matrix of the largest code in chain format
	GX:=GC[Size(C)];;
	i:=1;;
	p:=1;;
	while (i < Size(C)) do
		for j in [p..Dimension(C[i])] do;
			GX[p] := GC[i][j];
			p := p + 1;
		od;
		i := i + 1;
	od;

	GX:=ShallowCopy(GX);;
	# Add the G matrix of the tail codes
	k:=Dimension(C[Size(C)]);;
	for i in [1..Size(A)] do
		r:=1;;
		ZeroVec:=List([1..CodeLength(A[i])], i->Zero( LeftActingDomain(C[1]) ));;
		while (r <= k-Dimension(A[i])) do
			GX[r]:=ShallowCopy(GX[r]);;
			Append(GX[r], ZeroVec);;
			r := r + 1;;
		od;
		j:=1;;
		while (r <= k) do
			GX[r]:=ShallowCopy(GX[r]);;
			Append(GX[r], GA[i][j]);;
			j := j + 1;;
			r := r + 1;;
		od;
	od;
	CX:=GeneratorMatCode(GX, "Construction X code", LeftActingDomain(C[1]));

	K:=[C[1]!.lowerBoundMinimumDistance];;
	S:=[C[1]!.upperBoundMinimumDistance];;
	i:=1;;
	while (i <= Size(A)) do;
		r:=0;;
		p:=0;;
		for j in [1..i] do;
			r := r + A[Size(A)-j+1]!.lowerBoundMinimumDistance;
			p := p + A[Size(A)-j+1]!.upperBoundMinimumDistance;
		od;
		Append(K, [r + C[i+1]!.lowerBoundMinimumDistance]);
		Append(S, [p + C[i+1]!.upperBoundMinimumDistance]);
		i := i + 1;
	od;
	CX!.lowerBoundMinimumDistance := Minimum(K);;
	CX!.upperBoundMinimumDistance := Minimum(S);;

	# This can be displayed using Display(C) or History(C). This shows the
	# component codes that are used to construct the concatenated code
	CX!.history := [ Concatenation(String("Base codes: "), String(C)),
					 Concatenation(String("Auxiliary codes: "), String(A)) ];

	return CX;
end);

#########################################################################################
##
#F    ConstructionXXCode( <C1>, <C2>, <C3>, <A1>, <A2> )  ... code from Construction XX
##
##
InstallMethod(ConstructionXXCode, "linear code constructed using Construction XX",
	true, [IsCode, IsCode, IsCode, IsCode, IsCode], 0,
function( C1, C2, C3, A1, A2 )
	#
	# Construction XX (see W.O. Alltop, ``A method for extending binary linear codes,''
	#                      IEEE Trans. Inform. Theory, vol. 30, pp. 871-872, 1984
	#                 )
	#
	# Consider a set of linear codes of the same length n, C1 [n, k_1, d_1], C2 [n, k_2, d_2]
	# and C3 [n, k_3, d_3] such that C1 contains C2, C1 contains C3 and C4 [n,k_4,d_4] is the
	# intersection code of C2 and C3. Given two auxiliary codes A1 [n_1, k_1-k-2, e_1] and
	# A2 [n_2, k_1-k_3, e_2], there exists a [n + n_1 + n_2, k_1, d] CXX code where
	# d = min{d_4, d_3 + e_1, d_2 + e_2, d_1 + e_1 + e_2}.
	#
	# The codewords of CXX can be partitioned into 3 sections ( v | a | b ) where v has length
	# n, a has length n_1 and b has length n_2. A codeword from Construction XX takes the form:
	#    ( v | 0...0 | 0...0 ) if v is a codeword of C4,
	#    ( v |  a_1  | 0...0 ) if v is a codeword of C3\C4,
	#    ( v | 0...0 |  a_2  ) if v is a codeword of C2\C4,
	#    ( v |  a_1  |  a_2  ) otherwise.
	#
	local i, q, p, a1, a2,
		K, L, U, G1, G2, G3, G4, C4, GA1, GA2, GXX, CXX, ZeroVec1, ZeroVec2;

	# Make sure all codes are linear
	if ( (IsLinearCode(C1) = false) or (IsLinearCode(C2) = false) or
		(IsLinearCode(C3) = false) or (IsLinearCode(A1) = false) or
   	 	(IsLinearCode(A2) = false) ) then
		Error("Not all codes are linear\n");
	fi;

	# Make sure all codes have the same LeftActingDomain
	q:=LeftActingDomain(C1);;
	if ((LeftActingDomain(C2) <> q) or (LeftActingDomain(C3) <> q) or
  	 	(LeftActingDomain(A1) <> q) or (LeftActingDomain(A2) <> q)) then
		Error("Not all codes have the same left-acting-domain\n");
	fi;

	# Ensure that Dimension(C[1]) > Dimension(C[2]) > ... > Dimension(C[j]), i.e. we need to sort them
	if (Dimension(C1) < Dimension(C2)) then
		if (Dimension(C1) > Dimension(C3)) then
			K:=C1;; C1:=C2;; C2:=K;;
		else
        	if (Dimension(C2) > Dimension(C3)) then
        		K:=C1;; C1:=C2;; C2:=C3;; C3:=K;;
        	else
         	   K:=C1;; C1:=C3;; C3:=K;;
        	fi;
		fi;
	fi;

	# Need to make sure that C[1] > C[2] and C[1] > C[3], i.e. superset
	if (IsSubset(C1, C2) = false or IsSubset(C1, C3) = false) then
		Error("Inappropriate chain of codes, C1 must contain C2 and must also contain C3\n");
	fi;

	# Now, ensure that codes in A1 and A2 has the right dimension
	if (Dimension(A1) <> Dimension(C1)-Dimension(C2)) then
		Error("Inappropriate auxiliary code A1, dim(A1) <> dim(C1)-dim(C2)\n");
	fi;
	if (Dimension(A2) <> Dimension(C1)-Dimension(C3)) then
		Error("Inappropriate auxiliary code A2, dim(A2) <> dim(C1)-dim(C3)\n");
	fi;

	C4:=IntersectionCode(C2,C3);
	L:=[];; U:=[];;
	Append(L, [LowerBoundMinimumDistance(C1) + LowerBoundMinimumDistance(A1) + LowerBoundMinimumDistance(A2)]);;
	Append(L, [LowerBoundMinimumDistance(C2) + LowerBoundMinimumDistance(A2)]);;
	Append(L, [LowerBoundMinimumDistance(C3) + LowerBoundMinimumDistance(A1)]);;
	Append(U, [UpperBoundMinimumDistance(C1) + UpperBoundMinimumDistance(A1) + UpperBoundMinimumDistance(A2)]);;
	Append(U, [UpperBoundMinimumDistance(C2) + UpperBoundMinimumDistance(A2)]);;
	Append(U, [UpperBoundMinimumDistance(C3) + UpperBoundMinimumDistance(A1)]);;
	Append(L, [LowerBoundMinimumDistance(C4)]);;
	Append(U, [UpperBoundMinimumDistance(C4)]);;

	# Generator matrices of the chain codes
	G1 :=ShallowCopy(GeneratorMat(C1));;
	G2 :=ShallowCopy(GeneratorMat(C2));;
	G3 :=ShallowCopy(GeneratorMat(C3));;
	G4 :=ShallowCopy(GeneratorMat(C4));;
	GA1:=ShallowCopy(GeneratorMat(A1));;
	GA2:=ShallowCopy(GeneratorMat(A2));;

	# Generator matrix of the largest code in chain format
	GXX:=G1;;
	GXX:=ShallowCopy(GXX);;
	p:=1;;
	a1:=1;; a2:=1;;
	ZeroVec1:=List([1..CodeLength(A1)], i->Zero(q));;
	ZeroVec2:=List([1..CodeLength(A2)], i->Zero(q));;
	for i in [1..Dimension(C4)] do;		# G(C_4) on the top k_4 rows
		GXX[i] := ShallowCopy(G4[i]);;
		Append(GXX[i], ZeroVec1);; Append(GXX[i], ZeroVec2);;
		p := p + 1;;
	od;
	for i in [1..(Dimension(C2)-Dimension(C4))] do; # Proper coset of C4 in C2
		GXX[p] := ShallowCopy(G2[Dimension(C4)+i]);;
		GA2[a2] := ShallowCopy(GA2[a2]);;
    	Append(GXX[p], ZeroVec1);; Append(GXX[p], GA2[a2]);;
		p := p + 1;; a2:=a2+1;;
	od;
	for i in [1..(Dimension(C3)-Dimension(C4))] do; # Proper coset of C4 in C3
		GXX[p] := ShallowCopy(G3[Dimension(C4)+i]);;
		GA1[a1] := ShallowCopy(GA1[a1]);;
		Append(GXX[p], GA1[a1]);; Append(GXX[p], ZeroVec2);;
		p := p + 1;; a1:=a1+1;;
	od;
	for i in [1..(Dimension(C1)-(Dimension(C2)+Dimension(C3)-Dimension(C4)))] do;
		GXX[p]  := ShallowCopy(G1[p]);;
		GA1[a1] := ShallowCopy(GA1[a1]);;
		GA2[a2] := ShallowCopy(GA2[a2]);;
		Append(GXX[p], GA1[a1]);; Append(GXX[p], GA2[a2]);;
		p := p + 1;; a1:=a1+1;; a2:=a2+1;;
	od;

	CXX:=GeneratorMatCode(GXX, "Construction XX code", q);
	CXX!.lowerBoundMinimumDistance := Minimum(L);
	CXX!.upperBoundMinimumDistance := Minimum(U);

	# This can be displayed using Display(C) or History(C). This shows the
	# component codes that are used to construct this code
	CXX!.history := [ Concatenation(String("C1: "), String(C1)),
					  Concatenation(String("C2: "), String(C2)),
					  Concatenation(String("C3: "), String(C3)),
					  Concatenation(String("A1: "), String(A1)),
					  Concatenation(String("A2: "), String(A2))
                    ];

	return CXX;
end);

#########################################################################
##
#F BZCode( <O>, <I> ) . . . . . . . . . . Blokh Zyablov concatenated code
##
## Given a set of outer codes O_i=[N, K_i, D_i] over GF(q^e_i), where
## i=1,2,...,t and a set of inner codes I_i=[n, k_i, d_i] over GF(q),
## BZCode returns a multilevel concatenated code with parameter
## [ n*N, e_1*K_1 + e_2*K_2 + ... + e_t*K_t, min(d_i * D_i)] over GF(q).
##
## Note that the set inner codes must satisfy chain condition, i.e.
## I_1=[n,k_1,d_1] < I_2=[n,k_2,d_2] < ... < I_t=[n,k_t,d_t] where
## 0=k_0 < k_1 < k_2 < ... < k_t.
##
## The dimensions of the inner code must satisfy the condition
## e_i = k_i - k_{i-1}, where GF(q^e_i) is the field of the ith
## outer code.
##
__G_BZCode := function(O, I)
	local encode_code, VectorRep, i, j, l, e, u, v, ik, n, k, F,
          G, GIBZ, GOBZ, M, L, oi, oj, cw;

	# Two helper functions ...
	encode_code := function(u, G)
		return (u * G);
	end;

	VectorRep := function(e, F)
		local a, f, MF;
		if IsZero(e) then;
			return List([1..LogInt(Size(F), Characteristic(F))], i->Zero(GF(Characteristic(F))));
		fi;
		a := PrimitiveElement(F);
		f := MinimalPolynomial( GF(Characteristic(F)), a);
		MF:= CompanionMat( f );
		return TransposedMat(MF^LogFFE(e, a))[1];
	end;

	# Make sure that both O and I have the same number of codes
	if Size(O) <> Size(I) then
		Error("Unequal number of inner and outer codes\n");
	fi;

	# Make sure list O (outer codes) contains all linear codes
	if (PositionNot( List([1..Size(O)], i->IsLinearCode(O[i])), true ) < Size(O)) then
		Error("The list O contains non linear code(s)\n");
	fi;

	# Make sure list I (inner codes) contains all linear codes
	if (PositionNot( List([1..Size(I)], i->IsLinearCode(I[i])), true ) < Size(I)) then
		Error("The list I contains non linear code(s)\n");
	fi;

	# Make sure that all outer codes have the same length
	if (PositionNot(List([1..Size(O)], i->CodeLength(O[i])), CodeLength(O[1])) < Size(O)) then
		Error("Code lengths of all outer codes are required to be the same\n");
	fi;

	# Need to make sure that I[1] < I[2] < ... < I[s], i.e. subset
	if (PositionNot(List([0..Size(I)-2], i->IsSubset(I[Size(I)-i], I[Size(I)-i-1])), true) < Size(I)-1) then
		Error("Inappropriate chain of inner codes\n");
	fi;

	# Make sure that e_i = k_i - k_{i-1} where k_i is the dimension of the ith inner code
	ik := [0];
	for i in [1..Size(I)] do;
		Append(ik, [ Dimension(I[i]) ]);
	od;
	for i in [1..Size(I)] do;
		e := ik[i+1] - ik[i];
		if GF(Characteristic(LeftActingDomain(O[i]))^e) <> LeftActingDomain(O[i]) then
			Error("Field size of outer code O[", i, "] does not equal to the difference in dimension between the inner code I[", i, "] and that of inner code I[", i-1, "]\n");
			return (0);
		fi;
	od;

	# Generator matrix of the inner codes (in chain form)
	GIBZ := [];
	for i in [1..Size(I)] do;
		G := ShallowCopy( GeneratorMat(I[i]) );
		TriangulizeMat(G);
		for j in [1..(ik[i+1] - ik[i])] do;
			Append(GIBZ, [ G[ik[i] + j] ]);
		od;
	od;

	# Generator matrix of the outer codes -- in reduced-echelon form
	GOBZ := [];
	for i in [1..Size(O)] do;
		G := ShallowCopy( GeneratorMat(O[i]) );
		TriangulizeMat(G);
		Append(GOBZ, [ G ]);
	od;

	# What are the length and dimension of the resulting concatenated code?
	n := CodeLength(O[1]) * CodeLength(I[1]);
	k := Sum(List([1..Size(O)], i->(Dimension(O[i]) * (ik[i+1] - ik[i]))));

	# Construct the generator matrix of the BZ code
	v := [];
	for i in [1..Size(O)] do;
		Append(v, [ List([1..Dimension(O[i])], x->Zero(LeftActingDomain(O[i]))) ]);
	od;
	G := [];
	for i in [1..Size(O)] do;
		F := LeftActingDomain(O[i]);
		# Enumerate all elements of F
		L := [ Zero(F) ];
		for j in [1..(Size(F)-1)] do;
			Append(L, [ PrimitiveElement(F)^j ]);
		od;
		e := ik[i+1] - ik[i];
		for j in [1..Dimension(O[i])] do;
			for l in [1..e] do;
				v[i][j] := L[l+1];
				cw := [];
				for oi in [1..Size(O)] do;
					Append(cw, [ encode_code(v[oi], GOBZ[oi]) ]);
				od;
				M := [];
				for oj in [1..Length(cw[1])] do;
					u := [];
					for oi in [1..Size(O)] do;
						Append(u, VectorRep(cw[oi][oj], LeftActingDomain(O[oi])));
					od;
					Append(M, encode_code(u, GIBZ));
				od;
				Append(G, [ M ]);
				v[i][j] := Zero(LeftActingDomain(O[i]));
			od;
		od;
	od;

	if Rank(G) < k then
		Error("Cannot build the generator matrix of the concatenated code. Please report this to <ctjhai@plymouth.ac.uk> and supply the list of your inner and outer codes\n");
	fi;

	return G;
end;

InstallMethod(BZCode, "linear code constructed using Blokh Zyablov concatenation",
	true, [IsList, IsList], 0,
function( O, I )
	local G, C;

	# Obtain generator matrix
	G := __G_BZCode(O, I);

	C := GeneratorMatCode(G, "Blokh Zyablov concatenated code", LeftActingDomain(I[1]));

	C!.GeneratorMat := ShallowCopy(G);

	# Upper- and lower-bound of minimum distance
	C!.lowerBoundMinimumDistance := Minimum( List([1..Size(O)],
		i->O[i]!.lowerBoundMinimumDistance * I[i]!.lowerBoundMinimumDistance) );
	C!.upperBoundMinimumDistance := Minimum( List([1..Size(O)],
		i->O[i]!.upperBoundMinimumDistance * I[i]!.upperBoundMinimumDistance) );

	# This can be displayed using Display(C) or History(C). This shows the
	# component codes that are used to construct the concatenated code
	C!.history := [ Concatenation(String("Inner codes: "), String(I)),
					Concatenation(String("Outer codes: "), String(O)) ];

	return C;
end);

# Faster version - without covering radius estimation
InstallMethod(BZCodeNC, "linear code constructed using Blokh Zyablov concatenation",
	true, [IsList, IsList], 0,
function( O, I )
	local G, C;

	# Obtain generator matrix
	G := __G_BZCode(O, I);

	C := GeneratorMatCodeNC(G, LeftActingDomain(I[1]));

	C!.GeneratorMat := ShallowCopy(G);

	C!.name := "Blokh Zyablov concatenated code";
	# Upper- and lower-bound of minimum distance
	C!.lowerBoundMinimumDistance := Minimum( List([1..Size(O)],
		i->O[i]!.lowerBoundMinimumDistance * I[i]!.lowerBoundMinimumDistance) );
	C!.upperBoundMinimumDistance := Minimum( List([1..Size(O)],
		i->O[i]!.upperBoundMinimumDistance * I[i]!.upperBoundMinimumDistance) );

	# Set covering radius to unknown
    C!.boundsCoveringRadius := [ 0, WordLength(C) ];

	# This can be displayed using Display(C) or History(C). This shows the
	# component codes that are used to construct the concatenated code
	C!.history := [ Concatenation(String("Inner codes: "), String(I)),
					Concatenation(String("Outer codes: "), String(O)) ];

	return C;
end);

#############################################################################
##
#F  HullCode( <C> ) . . . . . . . . . . . . . . . . . . . .  hull of <C>
##

InstallMethod(HullCode, "generic method for codes", true, [IsLinearCode], 0,
function(C)
  return IntersectionCode(C,DualCode(C));
end);