#!/usr/local/bin/perl -I/home/users/dberansky/perl/lib
($PWD = $0 ) =~ s/[^\\]+$//;
use CGI;
use CGI::Carp qw(fatalsToBrowser);

$q = new CGI;
$e = new CGI( \%ENV );

print $q->header;

$script = $q->script_name();
$file = $q->path_info();
if( $file =~ /^$script\/(.*)/ )
{
   $file = $1;
}

$file = "thesis-utf8.html" unless $file;
$file = $PWD.$file;

open(FILE,"<$file") || die "can't open $file";
binmode FILE;
 
$prog = $PWD."cyrcode.pl";
#$dat = `$prog utf8 trans < $file` || die $!;
#print $dat;
#while(<FILE>)
#{
#   print $_;
#}

open(dat,$PWD.'cyrtab') || die "unable to open 'cyrtab'";
@names=&readnext;

$from="utf8";
$to=$q->param('charset');

for ($i=0; $i <= $#names; $i++) {
    $names[$i]=~ y/A-Z/a-z/;
    if (index($from,$names[$i]) >=0) {$from=$i;}
    if (index($to, $names[$i]) >=0) {$to=$i;};
}

if (($from == -1) || ($to == -1)) {
    print "unknown encoding table name \n";
    print "known table names:",join(', ',@names),"\n";
    exit;
}

for ($i = 0; $i < 256; $i++) {$decode[$i]=pack("cc",$i)};

while (!eof(dat)){
    @m=&readnext;

    if ($m[0] eq "") {last;}

    if( $m[$from] =~ /^0x/ )
    {
       $m[$from] = hex $m[$from];
    }

    if( $m[$to] =~ /^0x/ )
    {
       $m[$to] = hex $m[$to] 
    }

    if ($m[$from]=~ tr/a-z//){
        print "can not convert from ", $names[$from],"\n";
        exit;
    }
    if ($m[$to]=~tr/a-zA-Z\'\"//)
    {
       $decode{$m[$from]}=$m[$to];
    }
    else
    {  
       $decode{$m[$from]}=pack("c",$m[$to]);
    }
};


#actual convertion is here
while (!eof(FILE)){
   $code = getUTFChar();
   $ch = $decode{$code};
   print $ch if $ch;
   print sprintf "%c", $code unless $ch;
};

sub getUTFChar
{
   my($ch);
   my($i);
   my($numBytes);


   $ch = ord(getc FILE);
   $numBytes = getNumBytes($ch);
   $octets = ( ($ch << $numBytes) & hex("00FF") ) >> $numBytes;
   for( $i=1; $i<$numBytes; $i++ )
   {
      $ch = ord(getc FILE);
      $ch = ($ch << 2) & hex("00FF");
      $temp = sprintf "%x%02x",$octets,$ch; 
      $octets = (hex $temp) >> 2;
   }
 
   $temp = sprintf "%x", $octets;
   $temp =~ tr/a-f/A-F/; 

   return hex $temp;
}

sub isUSASCI
{
   my( $ch ) = @_;

   return (getNumBytes($ch) == 0 ) ;
}

sub getNumBytes($ch)
{
   my( $ch ) = @_;
   my( $counter, $hb ) = 0;

   $hb = getHiBit($ch);
   while( $hb == 1 )
   {
      $counter++;
      $ch = $ch << 1;
      $hb = getHiBit($ch);
   }

#   print " $counter bytes found \n";
   return $counter;
}

sub getHiBit
{
   my( $ch ) = @_;

#   print "   \&: ".($ch & 128)." ";

   return (($ch & 128) == 128);
}
exit 0;

# subprograms----------------------
sub readnext {
    local($str)='';
    while ((!eof(dat))&&($str eq '')){
        $str=<dat>;
        $str=~ s/\n//g;   #strips \n
        $str=~ s/^[\ \t]+//g;   #strips leading white space
        $str=~ s/#[\0-\377]+//g;  #strips comment
   }
    split(/[\ \t]+/,$str);
}
