#!/usr/bin/perl
#< trim.pl - 20131025 - trim a file
# 20/02/2014 - Copy to linux
# 31/10/2013 - Add --strip <col> to strip col count from left of line
use strict;
use warnings;

my $VERS = "0.0.2 2013-10-31";
##my $VERS = "0.0.2 2013-10-31";
##my $VERS = "0.0.1 2013-10-25";
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $col_cnt = 0;
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}

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

sub prt($) { print shift; }

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


sub trim_leading($) {
    my ($ln) = shift;
	$ln = substr($ln,1) while ($ln =~ /^\s/); # remove all LEADING space
    return $ln;
}

sub trim_tailing($) {
    my ($ln) = shift;
	$ln = substr($ln,0, length($ln) - 1) while ($ln =~ /\s$/g); # remove all TRAILING space
    return $ln;
}

sub trim_ends($) {
    my ($ln) = shift;
    $ln = trim_tailing($ln); # remove all TRAINING space
	$ln = trim_leading($ln); # remove all LEADING space
    return $ln;
}

sub trim_all {
	my ($ln) = shift;
	$ln =~ s/\n/ /gm;	# replace CR (\n)
	$ln =~ s/\r/ /gm;	# replace LF (\r)
	$ln =~ s/\t/ /g;	# TAB(s) to a SPACE
    $ln = trim_ends($ln);
	$ln =~ s/\s{2}/ /g while ($ln =~ /\s{2}/);	# all double space to SINGLE
	return $ln;
}

sub write2file {
	my ($txt,$fil) = @_;
	open WOF, ">$fil" or pgm_exit(3,"ERROR: Unable to open $fil! $!\n");
	print WOF $txt;
	close WOF;
}

sub process_file($) {
    my $fil = shift;
    my @olines = ();
    if (open(FIL, "<$fil")) {
        my @lines = <FIL>;
        close FIL;
        my ($line,$len);
        foreach $line (@lines) {
            chomp $line;
            $len = length($line);
            if ($col_cnt > 0) {
                if ($len > $col_cnt) {
                    $line = substr($line,$col_cnt);
                } else {
                    next;   # line too short to be included
                }
            }
            $line = trim_all($line);
            $len = length($line);
            next if ($len == 0);
            push(@olines,$line);
            ###prt("$line\n");
        }
        if (@olines) {
            $line = join("\n",@olines)."\n";
            if (length($out_file)) {
                write2file($line,$out_file);
                prt("Written to out file $out_file\n"); # if (VERB1());
            } else {
                prt("$line");
            }
        }
    } else {
        prt("ERROR: Can NOT open file [$fil]\n");
        exit 3;
    }
}


###################################################
parse_args(@ARGV);
process_file($in_file);
exit 0;
###################################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(3,"ERROR: [$arg] must have a 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(2,"");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } elsif ($sarg =~ /^s/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                if ($sarg =~ /^\d+$/) {
                    $col_cnt = $sarg;
                    prt("Strip $col_cnt from left of line.\n") if (VERB1());
                } else {
                    pgm_exit(1,"ERROR: Only an integer value can follow -s!\n");
                }
            } else {
                pgm_exit(3,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if (length($in_file) ==  0) {
        pgm_exit(3,"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");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 2.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
    prt(" --strip <col> (-s) = Strip column count from left of lines.\n");
}
