#!/usr/bin/perl
# $Id: xlatcfg.pl,v 1.5 2005/12/17 18:27:09 stas_degteff Exp $
# xlatcfg.pl
# Generate xlatcharset directives for the config of Golded+
# using Golded+ charset conversion modules in text form (*.chs).
#
# Format:
# XLATCHARSET  RUS         IBMPC       RUS_IBM.CHS

if($#ARGV<1){
   die "Need two parameters: directory witn *.chs (1) and output file name (2)\n";
}

if( -f $ARGV[1] ){
   die "File '$ARGV[1]' is exists, exiting\n";
}

if( ! -d $ARGV[0] ){
   die "Directory '$ARGV[1]' is not exists, exiting\n";
}
my $dir=$ARGV[0], $out=$ARGV[1];

my @files=<$dir/*.chs>;

if( $#files < 0 ){
 die "$dir/ don't contains files like *.chs, exit\n";
}
open OUT, ">$out" || die "Can't open/create file '$out': $!\n";
print OUT <<HEAD;
// Character translation definitions
// (include file for Golded+ config)
//
//  Generated by 'xlatcfg.pl' script written by Stas Degteff 2:5080/102\@fidonet
//
HEAD

print "Found " . ($#files+1) . " *.CHS files in $dir\n";

foreach my $f (@files) {
  if( ! open( IN, "$f" ) ){ print STDERR "Can't open file '$f': $!\n"; next; }
  print "Proceed $f\n";
  my $count=1, $fromchs, $tochs;
  $f =~ s%.*/%%g;
  while( <IN> ) {
     next if( /^;/ ); # comment
     next if( m%^//% ); # comment
     next if( m%^#% ); # comment
     chomp;
     next if( m%^$% ); # empty line
     if( m%^([^\s]+)% ) {
       if($count==4){ $fromchs=uc($1); }
       elsif($count==5){
         $tochs=uc($1);
         printf OUT "XLATCHARSET %-12s %-12s %s\n", $fromchs, $tochs, $f;
         if($fromchs =~ /-/) {
           ( my $temp = $fromchs ) =~ s/-//g ;
           printf OUT "XLATCHARSET %-12s %-12s %s\n", $temp, $tochs, $f;
         }
         if($tochs =~ /-/) {
           ( my $temp = $tochs ) =~ s/-//g ;
           printf OUT "XLATCHARSET %-12s %-12s %s\n", $fromchs, $temp, $f;
         }
         if( ($tochs =~ /-/) && ($fromchs =~ /-/) ) {
           ( my $temp1 = $fromchs ) =~ s/-//g ;
           ( my $temp2 = $tochs ) =~ s/-//g ;
           printf OUT "XLATCHARSET %-12s %-12s %s\n", $temp1, $temp2, $f;
         }
       }
       $count++;
     }
  }
  close IN;
}

close OUT;
