#!/perl -w
# NAME: relinejs.pl
# AIM: Attempt to reline javescript files...
# 05/05/2013 - Try to keep for(...;....;...) on ONE line
# 12/01/2013 - Try to keep 'function(a,b,c) {' on same line
# 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;
my $simple_only = 0;

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

my $debug_on = 0;
my $def_file = 'C:\FG\17\fgx-cf\test\js\jquery-1.8.3.min.js'; # OpenLayers.js';
#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);
}

my $g_indent = '';
my $g_indcnt = 0;
my $verbosity = 0;
my @g_braces = ();

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub set_indent() {
    my $j = scalar @g_braces;
    $g_indent = '';
    while ($j--) {
        $g_indent .= $curr_tab;
    }
}

sub reduce_indent() { set_indent(); }
sub increase_indent() { set_indent(); }

sub reduce_indent2() {
    $g_indcnt-- if ($g_indcnt);
    my $j = $g_indcnt;
    $g_indent = '';
    while ($j--) {
        $g_indent .= $curr_tab;
    }
}

sub increase_indent2() {
    $g_indcnt++;
    my $j = $g_indcnt;
    $g_indent = '';
    while ($j--) {
        $g_indent .= $curr_tab;
    }
}


sub get_func($$$) {
    my ($bal,$racc,$ri) = @_;
    my $len = length($bal);
    my $txt = '';
    my ($ch,$i);
    if ($bal =~ /^nction\s*\(/) {
        $bal = substr($bal,1);
        $len = length($bal);
        for ($i = 0; $i < $len; $i++) {
            $ch = substr($bal,$i,1);
            $txt .= $ch;
            last if ($ch eq '(');
        }
        if ($ch eq '(') {
            $i++;
            for (; $i < $len; $i++) {
                $ch = substr($bal,$i,1);
                $txt .= $ch;
                last if ($ch eq ')');
                last if ($ch eq '(');
            }
        } else {
            $ch = '';
        }
        if ($ch eq ')') {
            prt("Function $i chars [fun$txt]\n") if (VERB9());
            ${$racc} .= $txt;
            ${$ri} += $i + 1;
            return 1;
        }
    }
    return 0;
}

# like or(var b=this.img.data,c=this.header.zsize,d=this.header.ysize,e=this.header.xsize,g=8*e,f=0,h=512,i,j,l
#  ; f<c ;++f ) {
sub get_for($$$) {
    my ($bal,$racc,$ri) = @_;
    my $len = length($bal);
    my $txt = '';
    my ($ch,$i);
    if ($bal =~ /^or\s*\(/) {
        $bal = substr($bal,1);
        $len = length($bal);
        for ($i = 0; $i < $len; $i++) {
            $ch = substr($bal,$i,1);
            $txt .= $ch;
            last if ($ch eq '(');
            last if ($ch eq ')');
            last if ($ch eq ';');
        }
        if ($ch eq '(') {
            $i++;
            for (; $i < $len; $i++) {
                $ch = substr($bal,$i,1);
                $txt .= $ch;
                last if ($ch eq ';');
            }
        } else {
            $ch = '';
        }
        if ($ch eq ';') {
            $i++;
            for (; $i < $len; $i++) {
                $ch = substr($bal,$i,1);
                $txt .= $ch;
                last if ($ch eq ';');
            }
        } else {
            $ch = '';
        }
        if ($ch eq ';') {
            $i++;
            # final term
            my @br = ();
            for (; $i < $len; $i++) {
                $ch = substr($bal,$i,1);
                $txt .= $ch;
                if ($ch eq ')') {
                    if (@br) {
                        pop @br;
                    } else {
                        last;
                    }
                } elsif ($ch eq '(') {
                    push(@br,$ch);
                }
                last if ($ch eq ';');
            }
        } else {
            $ch = '';
        }
        if ($ch eq ')') {
            $i++;
            prt("For $i chars [fo$txt]\n") if (VERB9());
            ${$racc} .= $txt;
            ${$ri} += $i;
            return 1;
        }
    }
    return 0;
}

# Got begin of '['
sub get_square($$$) {
    my ($bal,$racc,$ri) = @_;
    my $len = length($bal);
    my $txt = '';
    my ($ch,$i);
    if ($bal =~ /^\[\s*\d+/) {
        $bal = substr($bal,1);
        $len = length($bal);
        for ($i = 0; $i < $len; $i++) {
            $ch = substr($bal,$i,1);
            $txt .= $ch;
            next if ($ch =~ /\s/);  # spaces ok
            next if ($ch eq ',');   # comma ok
            next if ($ch =~ /\d/);  # digit ok
            next if ($ch eq '.');   # full stop ok
            last;   # else all done
        }
        if ($ch eq ']') {
            prt("Block $i chars [$txt\n") if (VERB9());
            ${$racc} .= $txt;
            ${$ri} += $i + 1;
            return 1;
        }
    }
    return 0;
}

sub process_simple($) {
    my $fil = shift;
    my @newlines = ();
    if (! open INF, "<$fil") {
        prtw("WARNING: Unable to open file $fil!\n");
        return \@newlines;
    }
    my @lns = <INF>;
    close INF;
    my $filcnt = scalar @lns;
    prt("Processing $filcnt lines, from $fil...\n");
    my ($line,$lnn,$len,$i,$cc,$txt);
    $lnn = 0;
    $txt = '';
    foreach $line (@lns) {
        chomp $line;
        $lnn++;
        $len = length($line);
        for ($i = 0; $i < $len; $i++) {
            $cc = substr($line,$i,1);
            $txt .= $cc;
            if ($cc eq ';') {
                push(@newlines,$txt);
                $txt = '';
            }
        }
    }
    push(@newlines,$txt) if (length($txt));
    return \@newlines;
}

sub process_file($) {
   my ($fil) = @_;
   return process_simple($fil) if ($simple_only);
   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,$j,$inquots);
      my ($bal,$pc2);
      prt("Processing $filcnt lines, from $fil...\n");
      $lnn = 0;
      $cc = '';
      $pc = '';
      $pc2 = '';
      $incomment = 0;
      $accum = '';
      $g_indent = '';
      $g_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;
            $pc2 = $pc;
            $pc = $cc;
            $cc = substr($line,$i,1);
            $nc = ($i2 < $len ? substr($line,$i2,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;
               }
            }

            # not in a comment...
            if (!$inquots) {
                if ($cc eq '{') {
                    push(@g_braces,$cc);
                    set_indent();
                } elsif ($cc eq '}') {
                    pop @g_braces if (@g_braces);
                    set_indent();
                }
            }
            $bal = substr($line,$i);
            # ****** BEFORE ADD CHARACTER ******
            if (($cc eq '}')&& !($nc eq ';')) {
               push(@newlines,$accum) if (length($accum) && !($accum =~ /^\s+$/));
               reduce_indent();
               $accum = $g_indent.$cc;
               if ($nc eq ',') {
                   $accum .= $nc;
                   $i++;
               }
               push(@newlines,$accum);
               next;
            }
            $accum .= $cc; # add this character
            # ****** AFTER ADD CHARACTER ******
            if ($cc eq '"') {
               if ($inquots) {
                  $inquots = 0;
               } else {
                  $inquots = 1;
               }
            } elsif ($cc eq '[') {
                get_square($bal,\$accum,\$i);
            } elsif ($cc eq '{') {
                next if ($bal =~ /^{\s*}\s*;/);
               push(@newlines,$accum);
               $nlcnt = scalar @newlines;
               prt("$lnn:$i2:$nlcnt: Stored [$accum]...\n") if ($dbg_01);
               increase_indent();
               $accum = $g_indent;
            } elsif (($cc eq '}')&& !($nc eq ';')) {
               push(@newlines,$accum);
               $nlcnt = scalar @newlines;
               prt("$lnn:$i2:$nlcnt: Stored [$accum]...\n") if ($dbg_01);
               reduce_indent();
               $accum = $g_indent;
            } elsif (($cc eq '&')&&($pc eq '&')) {
                if ($new_line_on_and) {
                   push(@newlines,$accum);
                   $accum = $g_indent . $curr_tab;
                }
            } elsif (($cc eq '|')&&($pc eq '|')) {
                if ($new_line_on_or) {
                   push(@newlines,$accum);
                   $accum = $g_indent . $curr_tab;
                }
            } elsif (($cc eq ',')&& !$inquots) {
                if ($new_line_on_comma) {
                   push(@newlines,$accum);
                   $accum = $g_indent . $curr_tab;
                }
            } elsif (($cc eq ';') && !$inquots) {
                push(@newlines,$accum);
                if ($pc eq '}') {
                    reduce_indent();
                }
                $accum = $g_indent;
            } elsif (($pc2 =~ /\W/)&&($pc eq 'f')&&($cc eq 'o')&&($nc eq 'r')) {
                get_for($bal,\$accum,\$i);
                ###pgm_exit(1,"Got 'for' \nbal=$bal\n"); # \nline=$line\n");
            } elsif (($pc2 eq 'f')&&($pc eq 'u')&&($cc eq 'n')&&($nc eq 'c')) {
                get_func($bal,\$accum,\$i);
            }
         }  # process whole line
         $pc2 = $pc;
         $pc = $cc;
         $cc = "\n";
         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 = $g_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");
}

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

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");
    prt(" -o file           = Set the output file name.\n");
    prt(" -s                = Simple only changes. Only new line on ';'.\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)");
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_js = $sarg;
                prt("Set output file to [$out_js]\n");
            } elsif ($sarg =~ /^s/) {
                $simple_only = 1;
                prt("Set simple only parsing\n");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }

        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_file) ==  0) {
            $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
