#!/usr/bin/perl
use strict;
use warnings;
use utf8;

my $src_file = "EastAsianWidth.txt";
my $fname_out = "unicode_asian_width.tbl";

open(FILE, $src_file) || die "Cannot open $src_file.";
open(my $fh_out, ">:crlf:utf8", $fname_out) || die "Cannot open $fname_out.";
print $fh_out "// this file was generated by get_asianwidth_table.pl\n";

my $v = <FILE>;
chop($v);
print $fh_out "// $v\n";
$v = <FILE>;
chop($v);
print $fh_out "// $v\n";

my $ostart = -1;
my $otype = "";
my $oend = 0;
my $type;
while(my $a = <FILE>) {
	my $start;
	my $end;
	if ($a =~ /^([0-9A-F]+)\.\.([0-9A-F]+);([A-Za-z]+)/) {
		$start = hex $1;
		$end = hex $2;
		$type = $3;
		if ($type eq "Na") {
			$type = "n";
		}
	}
	elsif ($a =~ /^([0-9A-F]+);([A-Za-z]+)/) {
		$start = hex $1;
		$end = hex $1;
		$type = $2;
		if ($type eq "Na") {
			$type = "n";
		}
	} else {
		next;
	}

#	printf("-{ 0x%06x, 0x%06x, $type },\n", $start, $end);

	if ($otype eq $type
		#&& $oend+1 == $start	# 未定義部を飛ばしてつなげる
		)
	{
		# 1つ前とつなげる
		$oend = $end;
	} elsif ($ostart == -1) {
		$ostart = $start;
		$oend = $end;
		$otype = $type;
	} else {
		if (($otype eq "W") || ($otype eq "F") || ($otype eq "A") ||
			($otype eq "N") || ($otype eq "n")) {
			printf($fh_out  "{ 0x%06x, 0x%06x, '$otype' },\n", $ostart, $oend);
		}
		$ostart = $start;
		$oend = $end;
		$otype = $type;
	}
}
printf($fh_out "{ 0x%06x, 0x%06x, '$type' },\n", $ostart, $oend);
