summaryrefslogtreecommitdiff
path: root/lib/unicore/mktables
blob: 1e1f7ed48b00c0648ab51cb8d4ba6f7bd6d139aa (plain)
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
#!/usr/bin/perl -w
use strict;
use Carp;
##
## mktables -- create the runtime Perl Unicode files (lib/unicore/**/*.pl)
## from the Unicode database files (lib/unicore/*.txt).
##

mkdir("In", 0755);
mkdir("Is", 0755);
mkdir("To", 0755);

##
## Process any args.
##
my $Verbose = 0;

while (@ARGV)
{
    my $arg = shift @ARGV;
    if ($arg eq '-v') {
        $Verbose = 1;
    } elsif ($arg eq '-q') {
        $Verbose = 0;
    } else {
        die "usage: $0 [-v|-q]";
    }
}

my $LastUnicodeCodepoint = 0x10FFFF; # As of Unicode 3.1.1.

my $HEADER=<<"EOF";
# !!!!!!!   DO NOT EDIT THIS FILE   !!!!!!! 
# This file is built by $0 from e.g. Unicode.txt.
# Any changes made here will be lost!

EOF

##
## The main datastructure (a "Table") represents a set of code points that
## are part of a particular quality (that are part of \pL, \p{InGreek},
## etc.). They are kept as ranges of code points (starting and ending of
## each range).
##
## For example, a range ASCII LETTERS would be represented as:
##   [ [ 0x41 => 0x5A, 'UPPER' ],
##     [ 0x61 => 0x7A, 'LOWER, ] ]
##
sub RANGE_START() { 0 } ## index into range element
sub RANGE_END()   { 1 } ## index into range element
sub RANGE_NAME()  { 2 } ## index into range element

## Conceptually, these should really be folded into the 'Table' objects
my %TableInfo;
my %TableDesc;
my %FuzzyNames;
my %AliasInfo;

##
## Turn something like
##    OLD-ITALIC
## to
##    OldItalic
##
sub CanonicalName($)
{
    my $name = lc shift;
    $name =~ s/(?<![a-z])(\w)/\u$1/g;
    $name =~ s/[_\W]+//g;
    return $name;
}

##
## Turn something like
##    OLD-ITALIC
## to
##    Old_Italic
##
sub CanonicalNameForPattern($)
{
    my $name = lc shift;
    $name =~ s/(?<![a-z])(\w)/\u$1/g;
    $name =~ s/[_\W]+/_/;
    return $name;
}


##
## Associates a property ("Greek", "Lu", "Assigned",...) with a Table.
##
## Called like:
##       New_Prop(In => 'Greek', $Table, Desc => 'Greek Block', Fuzzy => 1);
##
## Normally, these parameters are set when the Table is created (when the
## Table->New constructor is called), but there are times when it needs to
## be done after-the-fact...)
##
sub New_Prop($$$@)
{
    my $Type = shift; ## "Is" or "In";
    my $Name = shift;
    my $Table = shift;

    ## remaining args are optional key/val
    my %Args = @_;

    my $Fuzzy = delete $Args{Fuzzy};
    my $Desc  = delete $Args{Desc}; # description

    $Name = CanonicalNameForPattern($Name) if $Fuzzy;

    ## sanity check a few args
    if (%Args or ($Type ne 'Is' and $Type ne 'In') or not ref $Table) {
        confess "$0: bad args to New_Prop"
    }

    if (not $TableInfo{$Type}->{$Name})
    {
        $TableInfo{$Type}->{$Name} = $Table;
        $TableDesc{$Type}->{$Name} = $Desc;
        if ($Fuzzy) {
            $FuzzyNames{$Type}->{$Name} = $Name;
        }
    }
}


##
## Creates a new Table object.
##
## Args are key/value pairs:
##    In => Name         -- Name of "In" property to be associated with
##    Is => Name         -- Name of "Is" property to be associated with
##    Fuzzy => Boolean   -- True if name can be accessed "fuzzily"
##    Desc  => String    -- Description of the property
##
## No args are required.
##
sub Table::New
{
    my $class = shift;
    my %Args = @_;

    my $Table = bless [], $class;

    my $Fuzzy = delete $Args{Fuzzy};
    my $Desc  = delete $Args{Desc};

    for my $Type ('Is', 'In')
    {
        if (my $Name = delete $Args{$Type}) {
            New_Prop($Type => $Name, $Table, Desc => $Desc, Fuzzy => $Fuzzy);
        }
    }

    ## shouldn't have any left over
    if (%Args) {
        confess "$0: bad args to Table->New"
    }

    return $Table;
}

##
## Returns true if the Table has no code points
##
sub Table::IsEmpty
{
    my $Table = shift; #self
    return not @$Table;
}

##
## Returns true if the Table has code points
##
sub Table::NotEmpty
{
    my $Table = shift; #self
    return @$Table;
}

##
## Returns the maximum code point currently in the table.
##
sub Table::Max
{
    my $Table = shift; #self
    confess "oops" if $Table->IsEmpty; ## must have code points to have a max
    return $Table->[-1]->[RANGE_END];
}

##
## Replaces the codepoints in the Table with those in the Table given
## as an arg. (NOTE: this is not a "deep copy").
##
sub Table::Replace($$)
{
    my $Table = shift; #self
    my $New   = shift;

    @$Table = @$New;
}

##
## Given a new code point, make the last range of the Table extend to
## include the new (and all intervening) code points.
##
sub Table::Extend
{
    my $Table = shift; #self
    my $codepoint = shift;

    my $PrevMax = $Table->Max;

    confess "oops ($codepoint <= $PrevMax)" if $codepoint <= $PrevMax;

    $Table->[-1]->[RANGE_END] = $codepoint;
}

##
## Given a code point range start and end (and optional name), blindly
## append them to the list of ranges for the Table.
##
## NOTE: Code points must be added in strictly ascending numeric order.
##
sub Table::RawAppendRange
{
    my $Table = shift; #self
    my $start = shift;
    my $end   = shift;
    my $name  = shift;
    $name = "" if not defined $name; ## warning: $name can be "0"

    push @$Table, [ $start,    # RANGE_START
                    $end,      # RANGE_END
                    $name   ]; # RANGE_NAME
}

##
## Given a code point (and optional name), add it to the Table.
##
## NOTE: Code points must be added in strictly ascending numeric order.
##
sub Table::Append
{
    my $Table     = shift; #self
    my $codepoint = shift;
    my $name      = shift;
    $name = "" if not defined $name; ## warning: $name can be "0"

    ##
    ## If we've already got a range working, and this code point is the next
    ## one in line, and if the name is the same, just extend the current range.
    ##
    if ($Table->NotEmpty
        and
        $Table->Max == $codepoint - 1
        and
        $Table->[-1]->[RANGE_NAME] eq $name)
    {
        $Table->Extend($codepoint);
    }
    else
    {
        $Table->RawAppendRange($codepoint, $codepoint, $name);
    }
}

##
## Given a code point range starting value and ending value (and name),
## Add the range to teh Table.
##
## NOTE: Code points must be added in strictly ascending numeric order.
##
sub Table::AppendRange
{
    my $Table = shift; #self
    my $start = shift;
    my $end   = shift;
    my $name  = shift;
    $name = "" if not defined $name; ## warning: $name can be "0"

    $Table->Append($start, $name);
    $Table->Extend($end) if $end > $start;
}

##
## Return a new Table that represents all code points not in the Table.
##
sub Table::Invert
{
    my $Table = shift; #self

    my $New = Table->New();
    my $max = -1;
    for my $range (@$Table)
    {
        my $start = $range->[RANGE_START];
        my $end   = $range->[RANGE_END];
        if ($start-1 >= $max+1) {
            $New->AppendRange($max+1, $start-1, "");
        }
        $max = $end;
    }
    if ($max+1 < $LastUnicodeCodepoint) {
        $New->AppendRange($max+1, $LastUnicodeCodepoint);
    }
    return $New;
}

##
## Merges any number of other tables with $self, returning the new table.
## (existing tables are not modified)
##
##
## Args may be Tables, or individual code points (as integers).
##
## Can be called as either a constructor or a method.
##
sub Table::Merge
{
    shift(@_) if not ref $_[0]; ## if called as a constructor, lose the class
    my @Tables = @_;

    ## Accumulate all records from all tables
    my @Records;
    for my $Arg (@Tables)
    {
        if (ref $Arg) {
            ## arg is a table -- get its ranges
            push @Records, @$Arg;
        } else {
            ## arg is a codepoint, make a range
            push @Records, [ $Arg, $Arg ]
        }
    }

    ## sort by range start, with longer ranges coming first.
    my ($first, @Rest) = sort {
        ($a->[RANGE_START] <=> $b->[RANGE_START])
          or
        ($b->[RANGE_END]   <=> $b->[RANGE_END])
    } @Records;

    my $New = Table->New();

    ## Ensuring the first range is there makes the subsequent loop easier
    $New->AppendRange($first->[RANGE_START],
                      $first->[RANGE_END]);

    ## Fold in records so long as they add new information.
    for my $set (@Rest)
    {
        my $start = $set->[RANGE_START];
        my $end   = $set->[RANGE_END];
        if ($start > $New->Max) {
            $New->AppendRange($start, $end);
        } elsif ($end > $New->Max) {
            $New->Extend($end);
        }
    }

    return $New;
}

##
## Given a filename, write a representation of the Table to a file.
## May have an optional comment as a 2nd arg.
##
sub Table::Write
{
    my $Table    = shift; #self
    my $filename = shift;
    my $comment  = shift;

    print "$filename\n" if $Verbose;

    if (not open(OUT, ">$filename")) {
	die "$0: can't write $filename: $!\n";
    }

    print OUT $HEADER;
    if (defined $comment) {
        $comment =~ s/\s+\Z//;
        $comment =~ s/^/# /gm;
        print OUT "#\n$comment\n#\n";
    }
    print OUT "return <<'END';\n";

    for my $set (@$Table)
    {
        my $start = $set->[RANGE_START];
        my $end   = $set->[RANGE_END];
        my $name  = $set->[RANGE_NAME];

        if ($start == $end) {
            printf OUT "%04X\t\t%s\n", $start, $name;
        } else {
            printf OUT "%04X\t%04X\t%s\n", $start, $end, $name;
        }
    }

    print OUT "END\n";
    close OUT;
}

###########################################################################
###########################################################################
###########################################################################


##
## Called like:
##     New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 1);
##
## The args must be in that order, although the Fuzzy pair may be omitted.
##
## This creates 'IsAll' as an alias for 'IsAny'
##
sub New_Alias($$$@)
{
    my $Type   = shift; ## "Is" or "In"
    my $Alias  = shift;
    my $SameAs = shift; # expecting "SameAs" -- just ignored
    my $Name   = shift;

    ## remaining args are optional key/val
    my %Args = @_;

    my $Fuzzy = delete $Args{Fuzzy};

    ## sanity check a few args
    if (%Args or ($Type ne 'Is' and $Type ne 'In') or $SameAs ne 'SameAs') {
        confess "$0: bad args to New_Alias"
    }

    if (not $TableInfo{$Type}->{$Name}) {
        confess "$0: don't have orignial $Type => $Name to make alias"
    }
    if ($TableInfo{$Alias}) {
        confess "$0: already have original $Type => $Alias; can't make alias";
    }
    $AliasInfo{$Type}->{$Name} = $Alias;
    if ($Fuzzy) {
        $FuzzyNames{$Type}->{$Alias} = $Name;
    }

}


## All assigned code points
my $Assigned = Table->New(Is    => 'Assigned',
                          Desc  => "All assigned code points",
                          Fuzzy => 1);

my $Name     = Table->New(); ## all characters, individually by name
my $General  = Table->New(); ## all characters, grouped by category
my %General;
my %Cat;

##
## Process Unicode.txt (Categories, etc.)
##
sub Unicode_Txt()
{
    my $Bidi     = Table->New();
    my $Deco     = Table->New();
    my $Comb     = Table->New();
    my $Number   = Table->New();
    my $Mirrored = Table->New(Is    => 'Mirrored',
                              Desc  => "Mirrored in bidirectional text",
                              Fuzzy => 0);

    my %DC;
    my %Bidi;
    my %Deco;
    $Deco{Canon}   = Table->New(Is    => 'Canon',
                                Desc  => 'Decomposes to multiple characters',
                                Fuzzy => 0);
    $Deco{Compat}  = Table->New(Is    => 'Compat',
                                Desc  => 'Compatible with a more-basic character',
                                Fuzzy => 0);

    ## Initialize Perl-generated categories
    ## (Categories from Unicode.txt are auto-initialized in gencat)
    $Cat{Alnum}  = Table->New(Is => 'Alnum',  Desc => "[[:Alnum:]]",  Fuzzy => 0);
    $Cat{Alpha}  = Table->New(Is => 'Alpha',  Desc => "[[:Alpha:]]",  Fuzzy => 0);
    $Cat{ASCII}  = Table->New(Is => 'ASCII',  Desc => "[[:ASCII:]]",  Fuzzy => 0);
    $Cat{Blank}  = Table->New(Is => 'Blank',  Desc => "[[:Blank:]]",  Fuzzy => 0);
    $Cat{Cntrl}  = Table->New(Is => 'Cntrl',  Desc => "[[:Cntrl:]]",  Fuzzy => 0);
    $Cat{Digit}  = Table->New(Is => 'Digit',  Desc => "[[:Digit:]]",  Fuzzy => 0);
    $Cat{Graph}  = Table->New(Is => 'Graph',  Desc => "[[:Graph:]]",  Fuzzy => 0);
    $Cat{Lower}  = Table->New(Is => 'Lower',  Desc => "[[:Lower:]]",  Fuzzy => 0);
    $Cat{Print}  = Table->New(Is => 'Print',  Desc => "[[:Print:]]",  Fuzzy => 0);
    $Cat{Punct}  = Table->New(Is => 'Punct',  Desc => "[[:Punct:]]",  Fuzzy => 0);
    $Cat{Space}  = Table->New(Is => 'Space',  Desc => "[[:Space:]]",  Fuzzy => 0);
    $Cat{Title}  = Table->New(Is => 'Title',  Desc => "[[:Title:]]",  Fuzzy => 0);
    $Cat{Upper}  = Table->New(Is => 'Upper',  Desc => "[[:Upper:]]",  Fuzzy => 0);
    $Cat{XDigit} = Table->New(Is => 'XDigit', Desc => "[[:XDigit:]]", Fuzzy => 0);
    $Cat{Word}   = Table->New(Is => 'Word',   Desc => "[[:Word:]]",   Fuzzy => 0);
    $Cat{SpacePerl} = Table->New(Is => 'SpacePerl', Desc => '\s', Fuzzy => 0);

    my %To;
    $To{Upper} = Table->New();
    $To{Lower} = Table->New();
    $To{Title} = Table->New();
    $To{Digit} = Table->New();

    sub gencat($$$$)
    {
        my ($name, ## Name ("LATIN CAPITAL LETTER A")
            $cat,  ## Category ("Lu", "Zp", "Nd", etc.)
            $code, ## Code point (as an integer)
            $op) = @_;

        my $MajorCat = substr($cat, 0, 1); ## L, M, Z, S, etc

        $Assigned->$op($code);
        $Name->$op($code, $name);
        $General->$op($code, $cat);

        ## add to the sub category (e.g. "Lu", "Nd", "Cf", ..)
        $Cat{$cat}      ||= Table->New(Is   => $cat,
                                       Desc => "General Category '$cat'",
                                       Fuzzy => 0);
        $Cat{$cat}->$op($code);

        ## add to the major category (e.g. "L", "N", "C", ...)
        $Cat{$MajorCat} ||= Table->New(Is => $MajorCat,
                                       Desc => "Major Category '$MajorCat'",
                                       Fuzzy => 0);
        $Cat{$MajorCat}->$op($code);

        ($General{$name} ||= Table->New)->$op($code, $name);

        # 005F: SPACING UNDERSCORE
        $Cat{Word}->$op($code)  if $cat =~ /^[LMN]/ || $code == 0x005F;
        $Cat{Alnum}->$op($code) if $cat =~ /^[LMN]/;
        $Cat{Alpha}->$op($code) if $cat =~ /^[LM]/;



        $Cat{Space}->$op($code) if $cat  =~ /^Z/
                                || $code == 0x0009  # 0009: HORIZONTAL TAB
                                || $code == 0x000A  # 000A: LINE FEED
                                || $code == 0x000B  # 000B: VERTICAL TAB
                                || $code == 0x000C  # 000C: FORM FEED
                                || $code == 0x000D; # 000D: CARRIAGE RETURN


        $Cat{SpacePerl}->$op($code) if $cat =~ /^Z/
                                    || $code == 0x0009 # 0009: HORIZONTAL TAB
                                    || $code == 0x000A # 000A: LINE FEED
                                    || $code == 0x000C # 000C: FORM FEED
                                    || $code == 0x000D # 000D: CARRIAGE RETURN
                                    || $code == 0x0085 # 0085: <NEXT LINE>
                                    || $code == 0x2028 # 2028: LINE SEPARATOR
                                    || $code == 0x2029;# 2029: PARAGRAPH SEP.

        $Cat{Blank}->$op($code) if $cat  =~ /^Z[^lp]$/
                                || $code == 0x0009  # 0009: HORIZONTAL TAB
                                || $code == 0x0020; # 0020: SPACE

        $Cat{Digit}->$op($code) if $cat eq "Nd";
        $Cat{Upper}->$op($code) if $cat eq "Lu";
        $Cat{Lower}->$op($code) if $cat eq "Ll";
        $Cat{Title}->$op($code) if $cat eq "Lt";
        $Cat{ASCII}->$op($code) if $code <= 0x007F;
        $Cat{Cntrl}->$op($code) if $cat =~ /^C/;
        $Cat{Graph}->$op($code) if $cat =~ /^([LMNPS]|Co)/;
        $Cat{Print}->$op($code) if $cat =~ /^([LMNPS]|Co|Zs)/;
        $Cat{Punct}->$op($code) if $cat =~ /^P/;

        $Cat{XDigit}->$op($code) if ($code >= 0x30 && $code <= 0x39)  ## 0..9
                                 || ($code >= 0x41 && $code <= 0x46)  ## A..F
                                 || ($code >= 0x61 && $code <= 0x66); ## a..f
    }

    ## open ane read file.....
    if (not open IN, "Unicode.txt") {
        die "$0: Unicode.txt: $!\n";
    }

    ##
    ## For building \p{_CombAbove} and \p{_CanonDCIJ}
    ##
    my %_Above_HexCodes; ## Hexcodes for chars with $comb == 230 ("ABOVE")

    my %CodeToDeco;      ## Maps code to decomp. list for chars with first
                         ## decomp. char an "i" or "j" (for \p{_CanonDCIJ})

    ## This is filled in as we go....
    my $CombAbove = Table->New(Is   => '_CombAbove',
                               Desc  => '(for internal casefolding use)',
                               Fuzzy => 0);

    while (<IN>)
    {
        next unless /^[0-9A-Fa-f]+;/;
        s/\s+$//;

        my ($hexcode,   ## code point in hex (e.g. "0041")
            $name,      ## character name (e.g. "LATIN CAPITAL LETTER A")
            $cat,       ## category (e.g. "Lu")
            $comb,      ## Canonical combining class (e.t. "230")
            $bidi,      ## directional category (e.g. "L")
            $deco,      ## decomposition mapping
            $decimal,   ## decimal digit value
            $digit,     ## digit value
            $number,    ## numeric value
            $mirrored,  ## mirrored
            $unicode10, ## name in Unicode 1.0
            $comment,   ## comment field
            $upper,     ## uppercase mapping
            $lower,     ## lowercase mapping
            $title,     ## titlecase mapping
              ) = split(/\s*;\s*/);

        my $code = hex($hexcode);

        if ($comb and $comb == 230) {
            $CombAbove->Append($code);
            $_Above_HexCodes{$hexcode} = 1;
        }

        ## Used in building \p{_CanonDCIJ}
        if ($deco and $deco =~ m/^006[9A]\b/) {
            $CodeToDeco{$code} = $deco;
        }

        ##
        ## There are a few pairs of lines like:
        ##   AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
        ##   D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;
        ## that define ranges.
        ##
        if ($name =~ /^<(.+), (First|Last)>$/)
        {
            $name = $1;
            gencat($name, $cat, $code, $2 eq 'First' ? 'Append' : 'Extend');
            #New_Prop(In => $name, $General{$name}, Fuzzy => 1);
        }
        else
        {
            ## normal (single-character) lines
            gencat($name, $cat, $code, 'Append');

            # No Append() here since since several codes may map into one.
            $To{Upper}->RawAppendRange($code, $code, $upper) if $upper;
            $To{Lower}->RawAppendRange($code, $code, $lower) if $lower;
            $To{Title}->RawAppendRange($code, $code, $title) if $title;
            $To{Digit}->Append($code, $decimal) if length $decimal;

            $Bidi->Append($code, $bidi);
            $Comb->Append($code, $comb) if $comb;
            $Number->Append($code, $number) if length $number;

            $Mirrored->Append($code) if $mirrored eq "Y";

            $Bidi{$bidi} ||= Table->New(Is    => "Bidi$bidi",
                                        Desc  => "Bi-directional category '$bidi'",
                                        Fuzzy => 0);
            $Bidi{$bidi}->Append($code);

            if ($deco)
            {
                $Deco->Append($code, $deco);
                if ($deco =~/^<(\w+)>/)
                {
                    $Deco{Compat}->Append($code);

                    $DC{$1} ||= Table->New(Is => "DC$1",
                                           Desc  => "Compatible with '$1'",
                                           Fuzzy => 0);
                    $DC{$1}->Append($code);
                }
                else
                {
                    $Deco{Canon}->Append($code);
                }
            }
        }
    }
    close IN;

    ##
    ## Tidy up a few special cases....
    ##

    $Cat{Cn} = $Assigned->Invert; ## Cn is everything that doesn't exist
    New_Prop(Is => 'Cn',
             $Cat{Cn},
             Desc => "General Category 'Cn' [not functional in Perl]",
             Fuzzy => 0);

    ## Unassigned is the same as 'Cn'
    New_Alias(Is => 'Unassigned', SameAs => 'Cn', Fuzzy => 1);

    $Cat{C}->Replace($Cat{C}->Merge($Cat{Cn}));  ## Now merge in Cn into C


    # L& is Ll, Lu, and Lt.
    New_Prop(Is => 'L&',
             Table->Merge(@Cat{qw[Ll Lu Lt]}),
             Desc  => '[\p{Ll}\p{Lu}\p{Lt}]',
             Fuzzy => 0);

    ## Any and All are all code points.
    my $Any = Table->New(Is    => 'Any',
                         Desc  => sprintf("[\\x{0000}-\\x{%X}]",
                                          $LastUnicodeCodepoint),
                         Fuzzy => 1);
    $Any->RawAppendRange(0, $LastUnicodeCodepoint);

    New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 1);

    ##
    ## Build special properties for Perl's internal case-folding needs:
    ##    \p{_CaseIgnorable}
    ##    \p{_CanonDCIJ}
    ##    \p{_CombAbove}
    ## _CombAbove was built above. Others are built here....
    ##

    ## \p{_CaseIgnorable} is [\p{Mn}\0x00AD\x2010]
    New_Prop(Is => '_CaseIgnorable',
             Table->Merge($Cat{Mn},
                          0x00AD,    #SOFT HYPHEN
                          0x2010),   #HYPHEN
             Desc  => '(for internal casefolding use)',
             Fuzzy => 0);


    ## \p{_CanonDCIJ} is fairly complex...
    my $CanonCDIJ = Table->New(Is    => '_CanonDCIJ',
                               Desc  => '(for internal casefolding use)',
                               Fuzzy => 0);
    ## It contains the ASCII 'i' and 'j'....
    $CanonCDIJ->Append(0x0069); # ASCII ord("i")
    $CanonCDIJ->Append(0x006A); # ASCII ord("j")
    ## ...and any character with a decomposition that starts with either of
    ## those code points, but only if the decomposition does not have any
    ## combining character with the "ABOVE" canonical combining class.
    for my $code (sort { $a <=> $b} keys %CodeToDeco)
    {
        ## Need to ensure that all decomposition characters do not have
        ## a %HexCodeToComb in %AboveCombClasses.
        my $want = 1;
        for my $deco_hexcode (split / /, $CodeToDeco{$code})
        {
            if (exists $_Above_HexCodes{$deco_hexcode}) {
                ## one of the decmposition chars has an ABOVE combination
                ## class, so we're not interested in this one
                $want = 0;
                last;
            }
        }
        if ($want) {
            $CanonCDIJ->Append($code);
        }
    }



    ##
    ## Now dump the files.
    ##
    $Name->Write("Name.pl");
    $Bidi->Write("Bidirectional.pl");
    $Comb->Write("CombiningClass.pl");
    $Deco->Write("Decomposition.pl");
    $Number->Write("Number.pl");
    $General->Write("Category.pl");

    for my $to (sort keys %To) {
        $To{$to}->Write("To/$to.pl");
    }
}

##
## Process LineBrk.txt
##
sub LineBrk_Txt()
{
    if (not open IN, "LineBrk.txt") {
        die "$0: LineBrk.txt: $!\n";
    }

    my $Lbrk = Table->New();
    my %Lbrk;

    while (<IN>)
    {
        next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(\w+)/;

	my ($first, $last, $lbrk) = (hex($1), hex($2||""), $3);

	$Lbrk->Append($first, $lbrk);

        $Lbrk{$lbrk} ||= Table->New(Is    => "Lbrk$lbrk",
                                    Desc  => "Linebreak category '$lbrk'",
                                    Fuzzy => 0);
        $Lbrk{$lbrk}->Append($first);

	if ($last) {
	    $Lbrk->Extend($last);
	    $Lbrk{$lbrk}->Extend($last);
	}
    }
    close IN;

    $Lbrk->Write("Lbrk.pl");
}

##
## Process ArabShap.txt.
##
sub ArabShap_txt()
{
    if (not open IN, "ArabShap.txt") {
        die "$0: ArabShap.txt: $!\n";
    }

    my $ArabLink      = Table->New();
    my $ArabLinkGroup = Table->New();

    while (<IN>)
    {
	next unless /^[0-9A-Fa-f]+;/;
	s/\s+$//;

	my ($hexcode, $name, $link, $linkgroup) = split(/\s*;\s*/);
        my $code = hex($hexcode);
	$ArabLink->Append($code, $link);
	$ArabLinkGroup->Append($code, $linkgroup);
    }
    close IN;

    $ArabLink->Write("ArabLink.pl");
    $ArabLinkGroup->Write("ArabLnkGrp.pl");
}

##
## Process Jamo.txt.
##
sub Jamo_txt()
{
    if (not open IN, "Jamo.txt") {
        die "$0: Jamo.txt: $!\n";
    }
    my $Short = Table->New();

    while (<IN>)
    {
	next unless /^([0-9A-Fa-f]+)\s*;\s*(\w*)/;
	my ($code, $short) = (hex($1), $2);

	$Short->Append($code, $short);
    }
    close IN;
    $Short->Write("JamoShort.pl");
}

##
## Process Scripts.txt.
##
sub Scripts_txt()
{
    my @ScriptInfo;

    if (not open(IN, "Scripts.txt")) {
        die "$0: Scripts.txt: $!\n";
    }
    while (<IN>) {
        next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;

        # Wait until all the scripts have been read since
        # they are not listed in numeric order.
        push @ScriptInfo, [ hex($1), hex($2||""), $3 ];
    }
    close IN;

    # Now append the scripts properties in their code point order.

    my %Script;
    my $Scripts = Table->New();

    for my $script (sort { $a->[0] <=> $b->[0] } @ScriptInfo)
    {
        my ($first, $last, $name) = @$script;
        $Scripts->Append($first, $name);

        $Script{$name} ||= Table->New(Is    => $name,
                                      Desc  => "Script '$name'",
                                      Fuzzy => 1);
        $Script{$name}->Append($first, $name);

        if ($last) {
            $Scripts->Extend($last);
            $Script{$name}->Extend($last);
        }
    }

    $Scripts->Write("Scripts.pl");

    ## Common is everything not explicitly assigned to a Script
    ##
    ##    ***shouldn't this be intersected with \p{Assigned}? ******
    ##
    New_Prop(Is => 'Common',
             $Scripts->Invert,
             Desc  => 'Pseudo-Script of codepoints not in other Unicode scripts',
             Fuzzy => 1);
}

##
## Given a name like "Close Punctuation", return a regex (that when applied
## with /i) matches any valid form of that name (e.g. "ClosePunctuation",
## "Close-Punctuation", etc.)
##
## Accept any space, dash, or underbar where in the official name there is
## space or a dash (or underbar, but there never is).
##
##
sub NameToRegex($)
{
    my $Name = shift;
    $Name =~ s/[- _]/(?:[-_]|\\s+)?/g;
    return $Name;
}

##
## Process Blocks.txt.
##
sub Blocks_txt()
{
    my $Blocks = Table->New();
    my %Blocks;

    if (not open IN, "Blocks.txt") {
        die "$0: Blocks.txt: $!\n";
    }

    while (<IN>)
    {
        #next if not /Private Use$/;
	next if not /^([0-9A-Fa-f]+)\.\.([0-9A-Fa-f]+)\s*;\s*(.+?)\s*$/;

	my ($first, $last, $name) = (hex($1), hex($2), $3);

	$Blocks->Append($first, $name);

        $Blocks{$name} ||= Table->New(In    => $name,
                                      Desc  => "Block '$name'",
                                      Fuzzy => 1);
        $Blocks{$name}->Append($first, $name);

	if ($last and $last != $first) {
	    $Blocks->Extend($last);
	    $Blocks{$name}->Extend($last);
	}
    }
    close IN;

    $Blocks->Write("Blocks.pl");
}

##
## Read in the PropList.txt.  It contains extended properties not
## listed in the Unicode.txt, such as 'Other_Alphabetic':
## alphabetic but not of the general category L; many modifiers
## belong to this extended property category: while they are not
## alphabets, they are alphabetic in nature.
##
sub PropList_txt()
{
    my @PropInfo;

    if (not open IN, "PropList.txt") {
        die "$0: PropList.txt: $!\n";
    }

    while (<IN>)
    {
	next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;

	# Wait until all the extended properties have been read since
	# they are not listed in numeric order.
	push @PropInfo, [ hex($1), hex($2||""), $3 ];
    }
    close IN;

    # Now append the extended properties in their code point order.
    my $Props = Table->New();
    my %Prop;

    for my $prop (sort { $a->[0] <=> $b->[0] } @PropInfo)
    {
        my ($first, $last, $name) = @$prop;
        $Props->Append($first, $name);

        $Prop{$name} ||= Table->New(Is    => $name,
                                    Desc  => "Extended property '$name'",
                                    Fuzzy => 1);
        $Prop{$name}->Append($first, $name);

        if ($last) {
            $Props->Extend($last);
            $Prop{$name}->Extend($last);
        }
    }

    # Alphabetic is L and Other_Alphabetic.
    New_Prop(Is    => 'Alphabetic',
             Table->Merge($Cat{L}, $Prop{Other_Alphabetic}),
             Desc  => '[\p{L}\p{OtherAlphabetic}]', # use canonical names here
             Fuzzy => 1);

    # Lowercase is Ll and Other_Lowercase.
    New_Prop(Is    => 'Lowercase',
             Table->Merge($Cat{Ll}, $Prop{Other_Lowercase}),
             Desc  => '[\p{Ll}\p{OtherLowercase}]', # use canonical names here
             Fuzzy => 1);

    # Uppercase is Lu and Other_Uppercase.
    New_Prop(Is => 'Uppercase',
             Table->Merge($Cat{Lu}, $Prop{Other_Uppercase}),
             Desc  => '[\p{Lu}\p{Other_Uppercase}]', # use canonical names here
             Fuzzy => 1);

    # Math is Sm and Other_Math.
    New_Prop(Is => 'Math',
             Table->Merge($Cat{Sm}, $Prop{Other_Math}),
             Desc  => '[\p{Sm}\p{OtherMath}]', # use canonical names here
             Fuzzy => 1);

    # ID_Start is Ll, Lu, Lt, Lm, Lo, and Nl.
    New_Prop(Is => 'ID_Start',
             Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl]}),
             Desc  => '[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]',
             Fuzzy => 1);

    # ID_Continue is ID_Start, Mn, Mc, Nd, and Pc.
    New_Prop(Is => 'ID_Continue',
             Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl Mn Mc Nd Pc ]}),
             Desc  => '[\p{ID_Start}\p{Mn}\p{Mc}\p{Nd}\p{Pc}]',
             Fuzzy => 1);
}

sub Make_GC_Aliases()
{
    ##
    ## The mapping from General Category long forms to short forms is
    ## currently hardwired here since no simple data file in the UCD
    ## seems to do that.  Unicode 3.2 will assumedly correct this.
    ##
    my %Is = (
	'Letter'			=>	'L',
	'Uppercase_Letter'		=>	'Lu',
	'Lowercase_Letter'		=>	'Ll',
	'Titlecase_Letter'		=>	'Lt',
	'Modifier_Letter'		=>	'Lm',
	'Other_Letter'			=>	'Lo',

	'Mark'				=>	'M',
	'Non_Spacing_Mark'		=>	'Mn',
	'Spacing_Mark'			=>	'Mc',
	'Enclosing_Mark'		=>	'Me',

	'Separator'			=>	'Z',
	'Space_Separator'		=>	'Zs',
	'Line_Separator'		=>	'Zl',
	'Paragraph_Separator'		=>	'Zp',

	'Number'			=>	'N',
	'Decimal_Number'		=>	'Nd',
	'Letter_Number'			=>	'Nl',
	'Other_Number'			=>	'No',

	'Punctuation'			=>	'P',
	'Connector_Punctuation'		=>	'Pc',
	'Dash_Punctuation'		=>	'Pd',
	'Open_Punctuation'		=>	'Ps',
	'Close_Punctuation'		=>	'Pe',
	'Initial_Punctuation'		=>	'Pi',
	'Final_Punctuation'		=>	'Pf',
	'Other_Punctuation'		=>	'Po',

	'Symbol'			=>	'S',
	'Math_Symbol'			=>	'Sm',
	'Currency_Symbol'		=>	'Sc',
	'Modifier_Symbol'		=>	'Sk',
	'Other_Symbol'			=>	'So',

	'Other'				=>	'C',
	'Control'			=>	'Cc',
	'Format'			=>	'Cf',
	'Surrogate'			=>	'Cs',
	'Private Use'			=>	'Co',
	'Unassigned'			=>	'Cn',
    );

    ## make the aliases....
    while (my ($Alias, $Name) = each %Is) {
        New_Alias(Is => $Alias, SameAs => $Name, Fuzzy => 1);
    }
}

##
## Writes the info accumulated in
##
##       %TableInfo;
##       %FuzzyNames;
##       %AliasInfo;
##
##
sub WriteAllMappings()
{
    my @MAP;

    for my $Type ('In', 'Is')
    {
        my %Filenames;
        my %NameToFile;

        my %Exact; ## will become %utf8::Is    or %utf8::In
        my %Pat;   ## will become %utf8::IsPat or %utf8::InPat

        ##
        ## First write all the files to the $Type/ directory
        ##
        for my $Name (sort { length $a <=> length $b } keys %{$TableInfo{$Type}})
        {
            my $Table   = $TableInfo{$Type}->{$Name};

            ## Need an 8.3 safe filename (which means "an 8 safe" $filename)
            my $filename = $FuzzyNames{$Type}->{$Name} ? CanonicalName($Name): $Name;
            $filename =~ s/[^\w_]+/_/g; # "L&" -> "L_"
            substr($filename, 8) = '' if length($filename) > 8;

            ##
            ## Make sure the filename doesn't conflict with something we
            ## might have already written. If we have, say,
            ##     GreekExtended1
            ##     GreekExtended2
            ## they become
            ##     GreekExt
            ##     GreekEx2
            ##
            while (my $num = $Filenames{lc $filename}++)
            {
                $num++; ## so filenames with numbers start with '2', which
                        ## just looks more natural.
                ## Want to append $num, but if it'll make the filename longer
                ## than 8 characters, pre-truncate $filename so that the result
                ## is acceptable.
                my $delta = length($filename) + length($num) - 8;
                if ($delta > 0) {
                    substr($filename, -$delta) = $num;
                } else {
                    $filename .= $num;
                }
            }

            $Exact{$Name} = $filename;

            ##
            ## Construct a nice comment to add to the file, and build data
            ## for the "./Properties" file along the way.
            ##
            my $Comment;
            {
                my $Desc = $TableDesc{$Type}->{$Name} || "";
                ## get list of names this table is reference by
                my @Supported = $Name;
                while (my ($Orig, $Alias) = each %{ $AliasInfo{$Type} })
                {
                    if ($Orig eq $Name) {
                        push @Supported, $Alias;
                    }
                }

                my $TypeToShow = $Type eq 'Is' ? "" : $Type;
                my $OrigProp;

                $Comment = "This file supports:\n";
                for my $N (@Supported)
                {
                    my $IsFuzzy = $FuzzyNames{$Type}->{$N};
                    my $CName   = $IsFuzzy ? CanonicalName($N): $N;
                    my $Prop    = "\\p{$TypeToShow$CName}";
                    $OrigProp = $Prop if not $OrigProp; #cache for aliases
                    if ($IsFuzzy) {
                        $Comment .= "\t$Prop (and fuzzy permutations)\n";
                    } else {
                        $Comment .= "\t$Prop\n";
                    }
                    my $MyDesc = ($N eq $Name) ? $Desc : "Alias for $OrigProp ($Desc)";

                    push @MAP, sprintf("%s %-42s %s\n",
                                       $IsFuzzy ? '*' : ' ', $Prop, $MyDesc);
                }
                if ($Desc) {
                    $Comment .= "\nMeaning: $Desc\n";
                }

            }
            ##
            ## Okay, write the file...
            ##
            $Table->Write("$Type/$filename.pl", $Comment);
        }

        ##
        ## Write out the map
        ##
        if (not open MAP, ">Properties") {
            die "$0: can't write Properties: $!\n";
        }
        print MAP "##\n";
        print MAP "## This file created by $0\n";
        print MAP "## List of built-in \\p{...}/\\P{...} properties.\n";
        print MAP "##\n";
        print MAP "## '*' means name may be 'fuzzy'\n";
        print MAP "##\n";
        print MAP "\n";
        print MAP sort { substr($a,2) cmp substr($b, 2) } @MAP;
        close MAP;

        ##
        ## Build %Pat
        ##
        while (my ($Fuzzy, $Real) = each %{$FuzzyNames{$Type}})
        {
            my $File = $Exact{$Real};

            if (not $File) {
                die "$0: oops [$Real]";
            }

            ## The prefix length of 2 is enough spread,
            ## and besides, we have 'Yi' as an In category.
            my $Prefix = lc(substr($Fuzzy, 0, 2));
            my $Regex = NameToRegex($Fuzzy);

            if ($Pat{$Prefix}->{$Regex}) {
                warn "WHOA, conflict with /$Regex/: $Pat{$Prefix}->{$Regex} vs $File\n";
            }

            $Pat{$Prefix}->{$Regex} = $File;
        }

        ##
        ## Since the fuzzy method will provide for a way to match $Fuzzy,
        ## there's no need for $Fuzzy to be in %Exact as well.
        ## This can't be done in the loop above because there could be
        ## multiple $Fuzzys pointing at the same $Real, and we don't want
        ## the first to delete the exact mapping out from under the second.
        ##
        for my $Fuzzy (keys %{$FuzzyNames{$Type}})
        {
            delete $Exact{$Fuzzy};
        }



        ##
        ## Now write In.pl / Is.pl
        ##
        if (not open OUT, ">$Type.pl") {
            die "$0: $Type.pl: $!\n";
        }
        print OUT $HEADER;
        print OUT "##\n";
        print OUT "## Data in this file used by ../utf8_heavy.pl\n";
        print OUT "##\n";
        print OUT "\n";
        print OUT "## Mapping from name to filename in ./$Type\n";
        print OUT "%utf8::$Type = (\n";
        for my $Name (sort keys %Exact)
        {
            my $File = $Exact{$Name};
            printf OUT "  %-41s => %s,\n", "'$Name'", "'$File'";
        }
        print OUT ");\n\n";

        print OUT "## Mappings from regex to filename in ./$Type/\n";
        print OUT "%utf8::${Type}Pat = (\n";
        for my $Prefix (sort keys %Pat)
        {
            print OUT " '$Prefix' => {\n";
            while (my ($Regex, $File) = each %{ $Pat{$Prefix} }) {
                print OUT "\t'$Regex' => '$File',\n";
            }
            print OUT " },\n";
        }
        print OUT ");\n";

        close(OUT);
    }
}

sub SpecCase_txt()
{
    #
    # Read in the special cases.
    #

    my %CaseInfo;

    if (not open IN, "SpecCase.txt") {
        die "$0: SpecCase.txt: $!\n";
    }
    while (<IN>) {
        next unless /^[0-9A-Fa-f]+;/;
        s/\#.*//;
        s/\s+$//;

        my ($code, $lower, $title, $upper, $condition) = split(/\s*;\s*/);

        if ($condition) { # not implemented yet
            print "# SKIPPING $_\n" if $Verbose;
            next;
        }

        # Wait until all the special cases have been read since
        # they are not listed in numeric order.
        my $ix = hex($code);
        push @{$CaseInfo{Lower}}, [ $ix, $code, $lower ];
        push @{$CaseInfo{Title}}, [ $ix, $code, $title ];
        push @{$CaseInfo{Upper}}, [ $ix, $code, $upper ];
    }
    close IN;

    # Now write out the special cases properties in their code point order.
    # Prepend them to the To/{Upper,Lower,Title}.pl.

    for my $case (qw(Lower Title Upper))
    {
        my $NormalCase = do "To/$case.pl" || die "$0: $@\n";
        if (not open OUT, ">To/$case.pl") {
            die "$0: To/$case.txt: $!";
        }

        print OUT $HEADER, "\n";
        print OUT "%utf8::ToSpec$case =\n(\n";

        for my $prop (sort { $a->[0] <=> $b->[0] } @{$CaseInfo{$case}}) {
            my ($ix, $code, $to) = @$prop;
            my $tostr =
              join "", map { sprintf "\\x{%s}", $_ } split ' ', $to;
            printf OUT qq['%04X' => "$tostr",\n], $ix;
        }
        print OUT ");\n\n";
        print OUT "return <<'END';\n";
        print OUT $NormalCase;
        print OUT "END\n";
        close OUT;
    }
}

#
# Read in the case foldings.
#
# We will do full case folding, C + F + I (see CaseFold.txt).
#
sub CaseFold_txt()
{
    if (not open IN, "CaseFold.txt") {
	die "$0: To/Fold.pl: $!\n";
    }

    my $Fold = Table->New();
    my %Fold;

    while (<IN>) {
	# Skip status 'S', simple case folding
	next unless /^([0-9A-Fa-f]+)\s*;\s*([CFI])\s*;\s*([0-9A-Fa-f]+(?: [0-9A-Fa-f]+)*)\s*;/;

	my ($code, $status, $fold) = (hex($1), $2, $3);

	if ($status eq 'C') { # Common: one-to-one folding
	    # No append() since several codes may fold into one.
	    $Fold->RawAppendRange($code, $code, $fold);
	} else { # F: full, or I: dotted uppercase I -> dotless lowercase I
	    $Fold{$code} = $fold;
	}
    }
    close IN;

    $Fold->Write("To/Fold.pl");

    #
    # Prepend the special foldings to the common foldings.
    #

    my $CommonFold = do "To/Fold.pl" || die "$0: To/Fold.pl: $!\n";
    if (not open OUT, ">To/Fold.pl") {
        die "$0: To/Fold.pl: $!\n";
    }
    print OUT $HEADER, "\n";
    print OUT "%utf8::ToSpecFold =\n(\n";
    for my $code (sort { $a <=> $b } keys %Fold) {
        my $foldstr =
          join "", map { sprintf "\\x{%s}", $_ } split ' ', $Fold{$code};
        printf OUT qq['%04X' => "$foldstr",\n], $code;
    }
    print OUT ");\n\n";
    print OUT "return <<'END';\n";
    print OUT $CommonFold;
    print OUT "END\n";
    close OUT;
}

## Do it....

Unicode_Txt();
Make_GC_Aliases();
PropList_txt();

Scripts_txt();
Blocks_txt();

LineBrk_Txt();
ArabShap_txt();
Jamo_txt();
SpecCase_txt();

WriteAllMappings();

CaseFold_txt();

# That's all, folks!

__END__