#!/usr/bin/perl -w
use strict;

#person in charge of this script
#this should be the person currently in charge of scripts for this project
my $script_maintainer='Teri Solow <tms45@cornell.edu>';


# given an input directory and a file format, parses out files submitted to 
# PGN into a format that can be used by our pipeline

# process arguments
@ARGV or print "No input parameters, proceeding with default.\n";
my @arg_pairs = split (/\-/, (join ' ', @ARGV));
my %args=();
foreach (@arg_pairs){
    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

my $new_dir=$args{'i'};
my $file_format=$args{'f'};
my $done_dir=$args{'d'};

#set defaults for io, script filename, etc
$done_dir ||= "/data/shared/pgn_data_processing/incoming_files/fgn/new_files";

# die if insufficient arguments have been given
$new_dir or die "You need to specify the input directory (-i flag).\n";
$file_format or die "You need to enter a the file format (-f flag).
\tThis should be a number that describes what the input files look like.
\tFor example:
\t\t(1) <library><plate_number>-<well>(-|_)<plate_desc>.<abi||e>
\t\t(2) <library>(-|_)<plate>(-|_)<well>.<abi|e>
\t\t(3) <library><plate><well><reaction>.scf (e.g., G0000200048F07F1.scf)
\t\t(4) <library><plate>_<well>_<reaction>.scf (e.g., 0089P0105Z_D11_T7.scf)
\t\t(5) <library><plate>.<reaction>_<well>.scf (e.g., 0089P0030Z.x0_F11.scf)

\n";


#main bmtdy of script
#####################

# get the list of files in $new_dir
opendir(FOLDER, $new_dir) or die "Cannot open ${new_dir}: $!\n";
my @files=readdir(FOLDER);
closedir(FOLDER);

# figure out how to parse these file names
my $match;
if ($file_format == 1) {
	# (1) <library><plate_number>-<well>(-|_)<plate_desc>.<extension>
	$match = '([A-Za-z]{3})0*([0-9]{1,2})-([A-Za-z]{1}[0-9]{2})[-_]{1}([A-Za-z0-9]{2,3})\.(e|ab1)';
}
elsif ($file_format == 2) {
	# (2) <library>(-|_)<plate>(-|_)<well>.<abi|e>
	$match = '([A-Za-z]+[0-9]*)[-_]{1}([A-Za-z0-9]+)[-_]{1}([A-Za-z]{1}[0-9]+)\.(e|ab1)';
}
elsif ($file_format == 3) {
	# (3) <library><plate><well><reaction>.scf (e.g., G0000200048F07F1.scf)
	$match = '([A-Za-z]{1}[0-9]{5})([0-9]{5})([A-Za-z]{1}[0-9]{2})([A-Za-z]{1}[0-9]{1})\.(scf)';
}
elsif ($file_format == 4) {
	# (4) <library><plate>_<well>_<reaction>.scf (e.g., 0089P0105Z_D11_T7.scf)
	$match = '([A-Za-z0-9]{6})([A-Za-z0-9]+)_([A-Za-z]{1}[0-9]+)_([A-Za-z]{1}[0-9])\.(scf)';
}
elsif ($file_format == 5) {
	# (5) <library><plate>.<reaction>_<well>.scf (e.g., 0089P0030Z.x0_F11.scf)
	$match = '([A-Za-z0-9]{6})([A-Za-z0-9]+)\.([A-Za-z]{1}[0-9]{1})_([A-Za-z]{1}[0-9]+)\.(scf)';
}
else {
	die "Unknown file format: $file_format\n";
}

my %libname=();
my %plates=();
my %files_exist=();

# create needed directories, moving files as required
foreach my $file (@files) {
	my ($lib, $plate, $well, $ext);
	if ($file =~ /$match/) {

		# extract info from each filename, depending on $file_format
		if ($file_format == 1) {
			# (1) <library><plate_number>-<well>(-|_)<plate_desc>.<extension>
			$lib = ucfirst $1;
			$plate = $2.$4;
			$well = $3;
			$ext = $5;
		}
		elsif ($file_format == 2) {
			# (2) <library>(-|_)<plate>(-|_)<well>.<abi|e>
			$lib = ucfirst $1;
			$plate = $2;
			$well = $3;
			$ext = $4;
		}
		elsif ($file_format == 3) {
			# (3) <library><plate><well><reaction>.scf (e.g., G0000200048F07F1.scf)
			$lib = ucfirst $1;		
			$plate = $2.$4;
			$well = $3;
			$ext = $5;
			$plate =~ s/^0{3}//;
		}
		elsif ($file_format == 4) {
			# (4) <library><plate>_<well>_<reaction>.scf (e.g., 0089P0105Z_D11_T7.scf)
			$lib = ucfirst $1;
			$plate = $2.$4;
			$well = $3;
			$ext = $5;
			$plate =~ s/^0?//;
		}
		elsif ($file_format == 5) {
			# (5) <library><plate>.<reaction>_<well>.scf (e.g., 0089P0030Z.x0_F11.scf)
			$lib = ucfirst $1;
			$plate = $2.$3;
			$well = $4;
			$ext = $5;
			$plate =~ s/^0?//;
		}
		else {
			die "Unknown file format: $file_format\n";
		}
		
		# make sure the library name is satisfactory
		if (!$libname{'$lib'}) {
			NEWLIB: print "The current library name is '$lib'.  If this is ok, simply press ENTER.  Otherwise, enter the new library name now:\n> ";
			my $newlib = <STDIN>;
			chop $newlib;
			$newlib ||= $lib;
			CONFIRM: print "'$newlib', is this ok? [yes/no] ";
			my $answer = <STDIN>;
			chop $answer;
			if ($answer eq 'yes') {
				$libname{'$lib'} = $newlib;
				$lib = $newlib;
			}
			elsif ($answer eq 'no') {
				goto NEWLIB;
			}
			else {
				print "That does not compute, foo!\n";
				goto CONFIRM;
			}
		}
		else {
			$lib = $libname{'$lib'};
		}

		# carry on
		my $platename = "$lib-$plate";
		my $filename = "$lib-$plate-$well.$ext";
		print "$file => \n";
		print "\t$platename\n\t$filename\n";
		$plates{$platename} = 1;
		my $mvcommand;
		if (!-e "${done_dir}/$filename") {
			$files_exist{$filename}++;
			$mvcommand = "mv ${new_dir}/$file ${done_dir}/$filename";
		}
		else {
			$files_exist{$filename}++;
			my $newfile = $filename;
			$newfile =~ s/([^.]+?)\.(e|ab1|scf)/$1mr$files_exist{$filename}.$2/;
			$mvcommand = "mv ${new_dir}/$file ${done_dir}/$newfile";
		 }
		system($mvcommand);
	}
	else {
		(($file ne ".") && ($file ne "..")) or next;
		print "$file doesn't match - not considered\n";
	}
}

# zip up the resulting directories
chdir $done_dir;
foreach my $plate (keys %plates) {
	print "\n\n========== Generating $plate.zip ==========\n";
	my $zipcommand = "zip $plate.zip $plate*";
	system($zipcommand);
	my $cleancommand = "rm $plate-*";
	system($cleancommand);
}

# print out a list of files which had the same name
foreach my $file_exists (keys %files_exist) {
	if ($files_exist{$file_exists} > 1) {
		print "$file_exists existed $files_exist{$file_exists} times\n";
	}
}
