#!/perl -w
# NAME: relinejs.pl
# AIM: Attempt to reline javescript files...
# 24/08/2011 - Review and improvements...
# 20/12/2009 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $perl_dir = 'C:\GTools\perl';
unshift(@INC, $perl_dir);
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $load_log = 0;
my $in_file = '';
#my $curr_tab = '   ';
my $curr_tab = ' ';
my $out_js = $perl_dir."\\tempjs.js";
my $new_line_on_and = 0;
my $new_line_on_or = 0;
my $new_line_on_comma = 1;
my $join_comments = 1;

# DEBUG
my $dbg_01 = 0; # prt("$lnn:$i2:$nlcnt: Stored [$accum]...\n") if ($dbg_01);

my $debug_on = 0;
my $def_file = 'def_file';
#my $in_file = "C:\\HOMEPAGE\\HOMnew\\test22\\swfobject.js";
#my $in_file = "C:\\DTEMP\\swfaddress-2.4\\js\\swfaddress.js";

### program variables
my @warnings = ();
my $cwd = cwd();
my $os = $^O;

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
       #### prt( "\nNo warnings issued.\n\n" );
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub process_file($) {
   my ($fil) = @_;
   my @newlines = ();
   if (open INF, "<$fil") {
      my @lns = <INF>;
      my $filcnt = scalar @lns;
      my ($line,$len,$lnn,$cc,$pc,$nc,$i,$incomment,$i2);
      my ($accum,$nlcnt,$indent,$indcnt,$j,$inquots);
      prt("Processing $filcnt lines, from $fil...\n");
      $lnn = 0;
      $cc = '';
      $incomment = 0;
      $accum = '';
      $indent = '';
      $indcnt = 0;
      $inquots = 0;
      foreach $line (@lns) {
         chomp $line;
         $lnn++;
         $len = length($line);
         prt("$lnn: $len chars...\n") if ($dbg_01);
         for ($i = 0; $i < $len; $i++) {
            $i2 = $i + 1;
            $pc = $cc;
            $cc = substr($line,$i,1);
            $nc = (($i + 1) < $len ? substr($line,$i+1,1) : '');
            if ($incomment) {
               # /* ... */
               if (($cc eq '/')&&($pc eq '*')) {
                  $incomment = 0;
                  $accum .= $cc;
                  push(@newlines,$accum);
                  $nlcnt = scalar @newlines;
                  prt("$lnn:$i2:$nlcnt: Exit    comment...\n") if ($dbg_01);
                  $accum = '';
                  next;
               }
            } else {
               if (($cc eq '/')&&($nc eq '*')) {
                  $incomment = 1;
                  push(@newlines,$accum) if (length($accum));
                  $nlcnt = scalar @newlines;
                  prt("$lnn:$i2:$nlcnt: Entered comment...\n") if ($dbg_01);
                  $accum = $cc;
                  next;
               }
            }

            # ****** BEFORE ADD CHARACTER ******
            if (($cc eq '}')&& !($nc eq ';')) {
               push(@newlines,$accum) if (length($accum) && !($accum =~ /^\s+$/));
               $indcnt-- if ($indcnt);
               $j = $indcnt;
               $indent = '';
               while ($j--) {
                  $indent .= $curr_tab;
               }
               $accum = $indent;
               push(@newlines,$accum.$cc);
               next;
            }
            $accum .= $cc; # add this character
            # ****** AFTER ADD CHARACTER ******
            if ($cc eq '"') {
               if ($inquots) {
                  $inquots = 0;
               } else {
                  $inquots = 1;
               }
            } elsif ($cc eq '{') {
               push(@newlines,$accum);
               $nlcnt = scalar @newlines;
               prt("$lnn:$i2:$nlcnt: Stored [$accum]...\n") if ($dbg_01);
               $indcnt++;
               $j = $indcnt;
               $indent = '';
               while ($j--) {
                  $indent .= $curr_tab;
               }
               $accum = $indent;
#            } elsif (($cc eq '}')&& !($nc eq ';')) {
#               push(@newlines,$accum);
#               $nlcnt = scalar @newlines;
#               prt("$lnn:$i2:$nlcnt: Stored [$accum]...\n") if ($dbg_01);
#               $indcnt-- if ($indcnt);
#               $j = $indcnt;
#               $indent = '';
#               while ($j--) {
#                  $indent .= $curr_tab;
#               }
#               $accum = $indent;
            } elsif (($cc eq '&')&&($pc eq '&')) {
                if ($new_line_on_and) {
                   push(@newlines,$accum);
                   $accum = $indent . $curr_tab;
                }
            } elsif (($cc eq '|')&&($pc eq '|')) {
                if ($new_line_on_or) {
                   push(@newlines,$accum);
                   $accum = $indent . $curr_tab;
                }
            } elsif (($cc eq ',')&& !$inquots) {
                if ($new_line_on_comma) {
                   push(@newlines,$accum);
                   $accum = $indent . $curr_tab;
                }
            } elsif (($cc eq ';') && !$inquots) {
                push(@newlines,$accum);
                $accum = $indent;
            }
         }  # process whole line
         next if ($incomment && $join_comments);
         if (length($accum) && !($accum =~ /^\s$/)) {
            push(@newlines,$accum);
            $nlcnt = scalar @newlines;
            prt("$lnn:$i2:$nlcnt:EOL: Stored [$accum]...\n") if ($dbg_01);
         }
         $accum = $indent;
      }  # process all the lines
      push(@newlines,$accum) if (length($accum));
      $accum = '';
      $nlcnt = scalar @newlines;
      prt("Got $nlcnt lines of output...\n");
   } else {
      prt("ERROR: Can not open file [$fil]!\n");
   }
   return \@newlines;
}

sub write_ref_arr($) {
   my ($ra) = @_;
   my $txt = join("\n",@{$ra});
   $txt .= "\n";
   write2file($txt,$out_js);
   prt("Written to file [$out_js]\n");
}

parse_args(@ARGV);
my $ref_arr = process_file($in_file);
write_ref_arr($ref_arr);
pgm_exit(0,"Normal end");

### ===================================

sub give_help {
    prt("$pgmname: version 0.0.1 2010-09-11\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help (-h or -?) = This help, and exit 0.\n");
}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if (! -f $in_file) {
        pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    }
}


### ===================================
# eof - relinejs.pl
