#!perl
# gen-vi : auxiliary script for Vietnamese
#
# output files
#
#   t-vi.txt (a main part of data/vi.txt)
#   t-vi.t   (a main part of t/loc_vi.t)
#
use strict;
use warnings;

use Unicode::Normalize;
require 'dumpstr';

my @base = qw( 61 41 103 102 E2 C2 65 45 EA CA 69 49 6F 4F
	       F4 D4 1A1 1A0 75 55 1B0 1AF 79 59 );
my @tone = qw( 300 340 309 303 301 341 323 );

open my $textf, ">t-vi.txt" or die "t-vi.txt";
binmode $textf;
my $text1 = "#equivalent sequences\n";
my $text2 = '';

open my $testf, ">t-vi.t" or die "t-vi.t";
binmode $testf;
my $test0 = '';
my $test1 = '';
my $test2 = '';
my $test3 = '';

my %data;

for my $b (@base) {
    my $bc = pack 'U', hex $b;
    for my $t (@tone) {
	my $tc = pack 'U', hex $t;
	my $cat = $bc.$tc;
	my $com = NFC($bc.$tc);
	my $dec = NFD($bc).$tc;

	my $scat = string($cat);
	my $scom = string($com);
	my $sdec = string($dec);
	$test0 .= qq|ok(\$objVi->eq($sdec, $scom));\n|;

	next if length $dec < 3;
	$test3 .= qq|ok(\$objVi->eq($sdec, $scat));\n|;

	my @d = split //, $dec;
	my $rule = sprintf "<%s><%s>", unidump($bc), unidump($tc);

	my $rv2 = NFC($d[0].$d[2]).$d[1];
	if ($com eq NFC $rv2) {
	    my $srv2 = string($rv2);
	    $test1 .= qq|ok(\$objVi->eq($sdec, $srv2));\n|;
	    my $d = element($rv2);
	    $text1 .= "$d;$rule\n" unless $data{$d}++;
	}

	my $rev = $d[0].$d[2].$d[1];
	if ($com eq NFC $rev) {
	    my $srev = string($rev);
	    $test2 .= qq|ok(\$objVi->eq($sdec, $srev));\n|;
	    my $d = element($rev);
	    $text2 .= "$d;$rule\n" unless $data{$d}++;
	}
    }
}

print $textf "$text1$text2";
close $textf or die '$textf';

#------

my $count0 = $test0 =~ s/->eq/->eq/g;
my $count1 = $test1 =~ s/->eq/->eq/g;
my $count2 = $test2 =~ s/->eq/->eq/g;
my $count3 = $test3 =~ s/->eq/->eq/g;

my $test_count = 74;
print $testf "\n# $test_count\n\n";

print $testf $test0;
$test_count += $count0;
print $testf "\n# $test_count\n\n";

print $testf $test1;
$test_count += $count1;
print $testf "\n# $test_count\n\n";

print $testf $test2;
$test_count += $count2;
print $testf "\n# $test_count\n\n";

print $testf $test3;
$test_count += $count3;
print $testf "\n# $test_count\n\n";

close $testf or die '$testf';
