#! /usr/local/bin/perl
# $Id: encodeconv.pl,v 1.7 2018-03-13 19:30:57+09 shige Exp $
# encodeconv.pl (based eucconv.pl) for 3.X jp patch
# Currently only for MS-Windows.
#
use Encode;

binmode(STDIN, ":encoding(euc-jp)");

if ( $#ARGV >= 0 && $ARGV[0] =~ /utf/i ) {
    binmode(STDOUT, ":utf8");
    $tocode = "UTF-8";
    $useencoding = "use utf8;";
    $setopenencoding = 'use open IO => ":encoding(utf8)";';
    $setstdoutencoding = 'binmode(STDOUT, ":encoding(shiftjis)");';
    $setstderrencoding = 'binmode(STDERR, ":encoding(shiftjis)");';
} elsif ( $#ARGV >= 0 && $ARGV[0] =~ /sjis/i ) {
    binmode(STDOUT, ":encoding(shiftjis)");
    $tocode = "Shift_JIS";
    $useencoding = 'use encoding "shiftjis";';
    $setopenencoding = 'use open IO => ":encoding(shiftjis)";';
    $setstdoutencoding = '';
    $setstderrencoding = 'binmode(STDERR, ":encoding(shiftjis)");';
} else {
    print STDERR "No option or unsupported option specified.\n";
    exit;
}

while ( <STDIN> ) {
    s/\@CHARSET\@/$tocode/g;
    s/\@USEENCODING\@/$useencoding/g;
    s/\@SETOPENENCODING\@/$setopenencoding/g;
    s/\@SETSTDOUTENCODING\@/$setstdoutencoding/g;
    s/\@SETSTDERRENCODING\@/$setstderrencoding/g;
    print;
} 
