#!/usr/bin/perl
# figencode - re-encode fig file to the current locale
# 2010-09-19, T.Sato

use POSIX qw(locale_h);
use File::Temp;
use Encode;
use Encode::Guess qw/euc-jp/;

die "Usage: figencode filenames...\n" if ($#ARGV < 0);

$locale = setlocale(LC_CTYPE);
$locale = 'utf-8' if $locale =~ /utf-?8/i;

for ($i = 0; $i <= $#ARGV; $i++) {
    $modified = 0;
    open(IN, "< $ARGV[$i]") || die "Can't open: $ARGV[$i]: $!\n";
    ($out, $out_filename) = mkstemp("figencodeXXXX");
    while (<IN>) {
	$str = $_;
	@fields = split(/ /, $str);
	if ($fields[0] == 4 && ($fields[5] == 0 || $fields[5] == 2)) {
	    $str =~ s/\\([0-7]{3})/pack( 'C', oct($1) )/eg;
	    $str =~ s/\001/\\001/;
	    $encoding = guess_encoding($str);
	    ref($encoding) || die "Couldn't identify encoding in $ARGV[$i]: $encoding";
	    $str = encode($locale, decode($encoding->name, $str));

	    $modified = 1 if $str ne $_;
	}
	print $out $str;
    }
    close($out);
    close(IN);

    if ($modified) {
	rename($ARGV[$i], $ARGV[$i] . ".bak");
	rename($out_filename, $ARGV[$i]);
    } else {
	unlink($out_filename);
    }

    print $ARGV[$i], "... ", $modified ? "converted" : "skipped", "\n";
}
