# Name: avx2ave.pl
#
# Script to convert an AVX-Extension (ESRI ArcView 3.x Extension File) to
# single AVE-Scripts. Invoke with: perl avx2ave.pl <myext.avx>
#
# (c) 2006 by Alexander von Lünen, avl1@gmx.de
# Code is in the public domain, use and modify it as you please. Credits would be nice, though.

# Define module to use
require 5.004;


# Define global variables
$numArgs = $#ARGV + 1;
$s = 0;
$debug = false;

### Main routine

# initial checking
if($numArgs < 1) {
   die "No command line arguments given!\n";
}
elsif($numArgs > 1) {
   print "Too many arguments specified, all but the first ignored.\n";
   print "Run with '-h' as first argument to see the correct format!\n";
}

if($ARGV[0] eq "-h") {
   print "Call: perl avx2ave.pl <filename>\nWhere '<filename>' is the name of the ArcView Extension file.\n";
   die;
}

# open the file and parse it
open(AVXFILE, "< $ARGV[0]") or die "Could not open " . $ARGV[0] . "\n";

while(not eof(AVXFILE)) {
   $tmp = readline(AVXFILE);
   
   if($tmp =~ /Script\./ && $s == 0) { # found a script
      $s = 1;
   }
   elsif($tmp eq ")\n" && $s == 2) { # end of script
      close(OUTFILE);
      $s = 0;
   }
   elsif($s == 1) { # extract name of script, open file for output
      if($tmp =~ /Name:/) {
         $ind = index($tmp, "\"");
         if($ind == -1 && $debug == true) {
            print "no match!\n";
         }
         $name = substr($tmp, $ind+1, -2) . ".ave";
         print $name . "\n";
         
         open(OUTFILE, ">$name") or die "Could not open " . $name . "\n";
         $s = 2;
      }
   }
   elsif($s == 2) { # extract actual script, convert special characters
      if($tmp =~ /SourceCode:/) {
         $ind = index($tmp, "\"");
         $tmp = substr($tmp, $ind+1, -1);
      }
      
      # filter out special characters
      $tmp =~ s/\n//g;
      $tmp =~ s/\r//g;
      $tmp =~ s/\\n/\n/g;
      $tmp =~ s/\\\"/\"/g;
      $tmp =~ s/\"$//;
      
      print OUTFILE $tmp;
      $| = 1; # Flush line to file
   }
}

close(AVXFILE);