#!/usr/local/bin/perl5.8.0 -w
use strict;

use TraceServer;
use Cwd;

die "Usage unmv_awol.pl <plate1.suffix> <plate2.suffix> <...>\n" unless scalar @ARGV >= 1;

# Arg parsing
my (@plate) = ();
foreach (@ARGV) {
	my ($plate,$suf) = split /\./,$_;
	push @plate,($plate,$suf);
}

if(!-e "phd_dir") {
    print "error: no phd_dir, is this a project dir?\n";
    exit(0);
}

# Assume project is the directory we are in.
my $this_project = getcwd();
$this_project =~ s:.*/::;

# Make a connection to the trace server DB and find/create the AWOL group
my $ts = TraceServer->new();

mv_plate_reads_repos(".");
mv_plate_reads_repos("./Failures");
mv_plate_reads_repos("./phd_dir");

mv_plate_reads_trsrv($ts, $this_project, "PASS", "AWOP");
mv_plate_reads_trsrv($ts, $this_project, "FAIL", "AWOF");

# Repository based moving.
sub mv_plate_reads_repos {
    my ($dir) = @_;
    my ($adir) = "awol/$dir";
    return (0) if(! -e $adir);

    opendir DIR, $adir or die "Can't open $adir directory: $!\n";
    while (defined(my $name = readdir DIR)) {
	my ($i);
	for($i=0;$i<@plate;$i+=2) {
	    if($name =~ /^($plate[$i])[a-p]\d\d?/
	       && ($name =~ /\.$plate[$i+1]$/
		   || $name =~ /\.$plate[$i+1].phd.1$/
		   || $name =~ /\.$plate[$i+1]SCF$/)) {
		rename("$adir/$name","$dir/$name");
	    }
	}
    }
    close DIR;
}

# Trace Server based moving.
# Removes from group $gname/$gtype
sub mv_plate_reads_trsrv {
    my ($ts, $gname, $pgtype, $gtype) = @_;

    # Get the original (PASS/FAIL) group and awol (AWOP/AWOF) group
    my $group = $ts->get_group($gname, $pgtype);
    return unless defined($group);

    my $awoz = $ts->get_group($gname, $gtype);
    if (!defined($awoz)) {
	warn "No group $gname/$gtype - aborting";
	return;
    }

    # Now move all members in awoz matching our query back to the
    # passed/failed group.
    my $grit = $awoz->get_iterator();
    while ($_ = $grit->next) {
	my $read = $ts->get_read_by_seq_id($_);
	my $name = $read->get_name();

	for(my $i=0;$i<@plate;$i+=2) {
	    if($name =~ /^($plate[$i])[a-p]\d\d?\./
	       && ($name =~ /\.$plate[$i+1]$/
		   || $name =~ /\.$plate[$i+1].phd.1$/
		   || $name =~ /\.$plate[$i+1]SCF$/)) {

		my $nseqs = $read->get_num_sequences();
		# print $awoz->get_name . "/" . $awoz->get_type . " -> "
		#     . $group->get_name . "/" . $group->get_type . "\n";
		for (my $s = 0; $s < $nseqs; $s++) {
		    my $seq = $read->get_sequence_by_index($s);
		    $awoz->move_sequence($seq, $group);
		}
	    }
	}
    }
}

exit(0);

 # $Log: unmv_awol.pl,v $
 # Revision 1.4  2006/08/29  09:22:47  jkb
 # Updates for Internal Trace Server.
 #
 # Revision 1.3  2002/11/20 13:48:19  rmd
 # Changed to handle 384 well plates.
 #
 # Revision 1.2  2000/08/30  14:37:28  rmd
 # Fixed problem where regexp matched more plates than it should.
 #
