#!/usr/bin/perl

#use warnings;
#use strict;

my $filelist = '';
my $flist = 1;
if ((scalar(@ARGV) > 1) && ($ARGV[0] =~ /-list/))
{
    $filelist = $ARGV[1];
    $flist = 0;
}



my @list = ();
if (scalar(@ARGV) < 1)
{
    while (!eof(STDIN))
    {
	my $input = <STDIN>;
	chomp $input;
	push @list, $input;
    }
}
else
{
    if ($flist)
    {
	@list = @ARGV;
    }
    else
    {
	open LIST, "$filelist" or die "Could not open file list file $filelist!!\n";
	while (!eof(LIST))
	{
	    my $string = <LIST>;
	    chomp $string;
	    push @list, $string;
	}
	close(LIST);
    }
}




for (my $x = 0; $x < scalar(@list); $x++)
{
    my $file = $list[$x];
    $file =~ /([\w\.\/\\]+).\w+/;
    my $newfile = $1.'.i2b';
    if (-e($file))
    {
	open DATA, "$file" or die "could not open file $file!\n";
	open OUT, "> $newfile" or die "Could not open output file $newfile!\n";
	print OUT $newfile,"\n";
    }
    else
    {
	print "File $file does not exist!\n";
	exit 1;
    }
    my $string = <DATA>;
    $string = <DATA>;
    $string = <DATA>;
    $string = <DATA>;
    print OUT $string;
    $string = &convert_to_boucamp($string);
    print OUT $string ,"\n\n\n";
    while (($string !~ /^\d+\s*$/ ) && (!eof(DATA)))
    {
	$string = <DATA>;
    }
    print OUT $string;
    $string = <DATA>;
    while (!eof(DATA))
    {
	$string = <DATA>;
	if ($string =~ /^([\d\.\+\-E]+), \S+, \S+, \S+, ([\d\.\+\-E]+), ([\d\.\+\-E]+)/)
	{
	    my $freq = $1+0;
	    my $Z1 = $2+0;
	    my $Z2 = $3+0;
	    print OUT "$freq\t$Z1\t$Z2 \n";
	}
	else
	{
	    ### File format for version 1.1 ##
	    my @l = split(/[\s\t\,]+/,$string);
	    print OUT "$l[1]\t$l[5]\t$l[6]\n";
	}
    }
    close(OUT);
    close(DATA);
}

sub convert_to_boucamp($)
{
    my $string = $_[0];
    $string =~ /.* (\d+)-(\d+)-(\d+)\s+\w+:\s([\d\:]+)/;
    my $res = ':'.$3.':'.$1.':'.$2.':'.$4."\n";
    return $res;
}
