#!/usr/bin/perl

use strict;
use warnings;

my $numSplitLines=1000000;
my $filePrefix="split";
my $fileSuffix=0;
my $fileSuffixStr=undef;
my $fileCompression=undef;
my $fileExt='';
my $verbose=0;

if (@ARGV == 0) { helpText(); }

foreach my $arg (@ARGV) {
    # solo args
    if ($arg =~ /^-+h(elp)?$/)            { helpText(); }
    if ($arg =~ /^-+v(erbose)?$/)         { $verbose = 1; }

    # numeric args
    if ($arg =~ /^-+l(ines)?=(\d+)$/)     { $numSplitLines = $2; }

    # string args
    if ($arg =~ /^-+p(refix)?=(.+)$/)    { $filePrefix = $2; }
    if ($arg =~ /^-+e(xt)?=(.+)$/)       { $fileExt = ".$2"; }
    if ($arg =~ /^-+c(ompress)?=(.+)$/)  { $fileCompression = $2; }
}

if ($verbose) { print "numSplitLines=$numSplitLines ; filePrefix=$filePrefix ; fileExt=$fileExt ; fileCompression=$fileCompression\n"; }

my $inLine;
my $linesTilSplit = 0;
open (OFILE, "> /dev/null");
while ($inLine = ) {
    if ($linesTilSplit == 0) {
        $linesTilSplit = $numSplitLines;
        $fileSuffix++;
        close OFILE;
        $fileSuffixStr=sprintf("%08d", $fileSuffix);
        if (defined $fileCompression) {
            open (OFILE, "| $fileCompression > $filePrefix-$fileSuffixStr$fileExt");
        } else {
            open (OFILE, "> $filePrefix-$fileSuffixStr$fileExt");
        }
    }
    $linesTilSplit--;
    print OFILE $inLine;
}

close OFILE;


sub helpText {
    print "usage: cat INPUTFILE | $0 [OPTIONS]\n";
    print "  -v              verbose\n";
    print "  -l[ines]=L      lines to split per file\n";
    print "  -p[refix]=PRE   file prefix\n";
    print "  -e[xt]=EXT      file extension\n";
    print "  -c[ompress]=PRG program to use to compress, eg 'bzip2 -z --fast -c'\n";
    print "  \n";
    exit 0;
}