#
# iconv.pl - do charset conversion without system iconv() support
#
use strict;
require "iconv-chinese.pl";
require "iconv-japan.pl";

use vars qw(%charset_convlist %charset_localname);

# convertable list of WWW charset, the definition is:
# charset in the left can be converted from the charsets in right list
%charset_convlist=
   (
   'big5'          => [ 'gb2312' ],
   'gb2312'        => [ 'big5' ],
   'euc-jp'        => [ 'shift_jis' ],
   'iso-2022-jp'   => [ 'shift_jis' ],
   'shift_jis'     => [ 'iso-2022-jp', 'euc-jp' ],
   );

sub is_convertable {
   my ($from, $to)=@_;
   $from=lc($from); $to=lc($to);

   return 1 if ($from eq 'big5' && $to eq 'gb2312');
   return 1 if ($from eq 'gb2312' && $to eq 'big5');
   return 1 if ($from eq 'shift_jis' && $to eq 'iso-2022-jp');
   return 1 if ($from eq 'iso-2022-jp' && $to eq 'shift_jis');
   return 1 if ($from eq 'shift_jis' && $to eq 'euc-jp');
   return 1 if ($from eq 'euc-jp' && $to eq 'shift_jis');

   return 0;
}

sub iconv {
   my ($from, $to, @text)=@_;
   $from=lc($from); $to=lc($to);

   my @result;

   for (my $i=0; $i<=$#text; $i++) {
      if ($text[$i]!~/[^\s]/) {
         $result[$i]=$text[$i]; next;
      }
      # since g2b, b2g in openwebmail is quite complete, we prefer it than iconv
      if ($from  eq 'big5' && $to eq 'gb2312' ) {
         $result[$i]=b2g($text[$i]); next;
      } elsif ($from eq 'gb2312' && $to eq 'big5' ) {
         $result[$i]=g2b($text[$i]); next;
      } elsif ($from eq 'shift_jis' && $to eq 'iso-2022-jp' ) {
         $result[$i]=$text[$i]; sjis2jis(\$result[$i]); next;
      } elsif ($from eq 'iso-2022-jp' && $to eq 'shift_jis' ) {
         $result[$i]=$text[$i]; jis2sjis(\$result[$i]); next;
      } elsif ($from eq 'shift_jis' && $to eq 'euc-jp' ) {
         $result[$i]=$text[$i]; sjis2euc(\$result[$i]); next;
      } elsif ($from eq 'euc-jp' && $to eq 'shift_jis' ) {
         $result[$i]=$text[$i]; euc2sjis(\$result[$i]); next;
      } else {
         $result[$i]=$text[$i];
      }
   }
   return (@result);
}

1;
