#!/usr/bin/perl
#
# yapkf - Yet Another Perl Knaji filter
#
# License: GPL
# Author: Tatsuki Sugiura <sugi@nemui.org>
#

use strict;
use Jcode;
use Jcode::Unicode;
use Getopt::Long;
Getopt::Long::Configure qw( no_ignore_case );

### init
my $VERSION = 0.4;
$0 =~ m|([^/]+)$|;
my $MYNAME = $1;

my %eol = ( 'unix' => "\x0A", 'dos' => "\x0D\x0A", 'mac' => "\x0D");

### option handling
my %opt;
my $getopt_result = GetOptions(\%opt, 'help|h', 'version|V', 'no-bufferd|nb',
			       'jis|j',  'euc|e', 'sjis|s', 'utf8|u',
			       'in-euc|E', 'in-jis|J', 'in-sjis|S', 'in-utf8|U',
			       'z2h', 'h2z', 'no-mime-decode|nm', 'eol=s'
			       );

if ( exists $opt{eol} && ! exists $eol{$opt{eol}} ) {
    $getopt_result = 0;
    print "Option -eol accept only 'unix', 'dos' or 'mac'\n";
}
if ( !$getopt_result || $opt{help} ){ &usage; exit(1); } 
if ( $opt{version} ) {
    print "$MYNAME version $VERSION\n";
    exit(0);
}

$| = ! exists $opt{'un-bufferd'};

my ($out, $in, $zhconv) = ('euc');
foreach ('jis', 'sjis', 'utf8', 'euc') {
    $in = $_ if defined $opt{"in_$_"};
    $out = $_ if defined $opt{$_};
}
foreach ('z2h', 'h2z') {
    $zhconv = $_ if defined $opt{$_};
}

### main
binmode STDOUT;
my $str = Jcode->new;
while (<>) {
    s/\x0D\x0A|\x0A|\x0D/$eol{$opt{eol}}/og if exists $opt{eol};
    $str->set($_, $in);
    $str = $str->$zhconv if $zhconv;
    print $str->$out;
}

exit(0);

######### End of main ############

sub usage {
    print <<EOU;
Usage:
  $MYNAME <option> <file>...
0ptions:
  -h,  --help            show this message.
  -V,  --version         show version
  -nb, --no-bufferd      unbufferd output
  -j,  --jis             convert to jis
  -e,  --euc             convert to euc
  -s,  --sjis            convert to sjis
  -u,  --utf8            convert to utf8
  -E,  --in-euc          assume input code is euc
  -J,  --in-jis          assume input code is jis
  -S,  --in-sjis         assume input code is sjis
  -U,  --in-utf8         assume input code is utf8
       --h2z             convert 1-byte (hankaku) kana to 2-byte (zenkaku) kana
       --z2h             convert 2-byte (zenkaku) kana to 1-byte (hankaku) kana
  -nm, --no-mime-decode  output without mime decode
  -eol <unix|mac|dos>    convert end of line to \\n, \\r, \\r\\n
EOU
}
