#!/usr/bin/perl

use strict;

use lib '/app/tools/common/lib';
use Common::Util;

unless (@ARGV) {
    die <<END;
Usage: $0 /path/to/file [header line num] [sample size]

    file should be in tsv format, either use xls2tsv or csv2tsv (both in /app/tools/common/bin)
    [header line num] is either 'none' if no header
                      or an integer to indicate which line number
                      the header is on (default is 1)

    [sample size]   The number of lines to sample (default is 3)

END
}

my $headerLineNum = $ARGV[1] eq 'none' ? 0 : $ARGV[1] ? $ARGV[1] : 1;
my $sample_size = $ARGV[2] || 3;

open( F, '<', $ARGV[0] ) or die "Could not open $ARGV[0]: $!";

my $delimiter = Common::Util::GetDelimiter(*F);
die "Can't determine delimiter\n" unless $delimiter;

my @lines = <F>;
my $rows  = [];

if ($headerLineNum) {
    for ( my $i = $headerLineNum - 1 ; $i < $headerLineNum + $sample_size ; $i++ ) {
        push( @$rows, [ Common::Util::trimquotes( _cleanup( split( $delimiter, $lines[$i] ) ) ) ] );
    }

    my $i         = 0;
    my $maxLength = 0;
    my %map;

    my $headers = shift @$rows;

    #print "'" . join("', '", @$headers) . "'\n\n";
    map { print length $_ ? "'$_', " : 'undef, ' } @$headers;
    print "\n";

    foreach my $head (@$headers) {

        #last if (length($head) == 0);
        $head = 'blank-' . $i if ( length($head) == 0 );
        $head .= '-dup-' . $i if ( exists $map{$head} );

        $maxLength = length($head) if ( length($head) > $maxLength );

        map { $map{$head} .= $_->[$i] . ' , '; } @$rows;
        $map{$head} =~ s/,\s$//;
        $i++;
    }

    $i = 0;
    $a = 'A';
    map { printf( "%${maxLength}s [%s %d] %s\n", $_, $a++, $i++, $map{$_} ) } @$headers;
} else {

    # need to dump without headers
}

sub _cleanup {
    my @data = @_;

    for (@data) {
        s/[\n\r\t]+/ /g;    # strip tabs and linebreaks
        s/^\s+//;
        s/\s+$//;
    }

    return wantarray ? @data : $data[0];
}

