## Active Perl 5.8.8
use utf8;
use warnings;
use strict;
binmode STDOUT,'encoding(cp932)';

open CSV, '<:utf8', 'temp/npcname-j.txt'  or die $!;
my $mtime = (stat CSV)[9];

open SQL, '>:utf8', 'npcname_ja.sql'  or die $!;
print SQL "--
-- from 'npcname-j.dat'
--
DROP TABLE IF EXISTS npcname_ja;
CREATE TABLE npcname_ja (
	 id INTEGER NOT NULL
	,name VARCHAR(200) DEFAULT ''
	,title VARCHAR(45) DEFAULT ''
	,PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

";

my $count = 0;
my $delim = ' ';
<CSV>; # skip header
while (not eof CSV) {
	my $buf = <CSV>;
	chomp $buf;
	my @field = split /\t/, $buf;
	foreach (@field) {s/^[ua],//; s/\\0//}
	my ($id,$name,$title) = ($field[0],$field[1],$field[2]);
	$name =~ s/'/''/g;
	$title =~ s/'/''/g;
	print "$id\r";

	if (++$count > 500) {
		print SQL ";\n";
		$count = 1;
	}
	if ($count == 1) {
		print SQL "INSERT INTO npcname_ja (id,name,title) VALUES\n";
		$delim = ' ';
	}
	print SQL $delim,"($id,'$name','$title')\n";
	$delim = ',';
}
print SQL ";\n";
print SQL "
-- Update for Japanese.
UPDATE npc,npcname_ja SET
  npc.name = npcname_ja.name
 ,npc.title = npcname_ja.title
 WHERE npc.id = npcname_ja.id;

-- DROP TABLE npcname_ja;
";
close SQL;
utime $mtime,$mtime,'npcname_ja.sql';

close CSV;
print "\n";
