#!/usr/bin/perl -w
# Make the setup table so that users can hand-tweak the replicates (ExpInfo-SubExpInfo relations),
# the chip assignments, the condition, the control and treatment descriptions, and the dye assignments

use strict;
use lib "../stat";
use Vector;

my $dir = shift @ARGV;
my $pubsFile = shift @ARGV;
my $exptSetFile = shift @ARGV;
my $exptsFile = shift @ARGV;
die "Usage: SMDSetupTable.pl dir pubsFile exptSetFile exptFile\n" if !defined $exptsFile;

my $pubs = Vector::readDelim($pubsFile,"Pub");
my $exptSets = Vector::readDelim($exptSetFile,"ExptSetNo");
my $expts = Vector::readDelim($exptsFile,"Exptid");

my %exptAttrs = (); # exptId -> attr -> value

foreach my $exptId (keys %{ $expts->{"Exptid"} }) {
    my $file = "$dir/$exptId.VIMSS";
    if (-e $file) {
	my $attrs = Vector::readXLSAttrs($file);
	$exptAttrs{$exptId} = $attrs;
    }
}

print join("\t", "Citation", "PubMedID",
	   "SMDExptSetNo",
	   "GroupUniq", # curate to group experiments into replicates
	   "Condition", # curate to e.g. "Heat" or "Peroxide"
	   "ControlInfo", # curate
	   "TreatmentInfo", # curate
	   "Comment", # curate
	   "Biological", # curate to group replicates into biological replicates
	   "Technical", # in case the curator wants to number technical replicates manually
	   "TreatmentChannel", # curate to Red or Green (Green = channel 1 = Cy3, Red = channel 2 = Cy5)
	   "SMDExptid", "Experiment Name", "Description",
	   "Channel 1 Description", "Channel 2 Description", # for aiding in assigning Treatment Channel
	   "ChipUniq", # curate to identify identical chips
	   "ChipType", # curate to cDNA (or CDNA) or Affymetrix
	   "ChipDescription", # curate
	   "ChipName",
	   "ChipSource" # optionally curate
	   ), "\n";

foreach my $exptId (sort {$a <=> $b} keys %exptAttrs) {
    my $exptSetId = $expts->{"ExptSetNo"}{$exptId};
    my $pubId = $exptSets->{"Pub"}{$exptSetId};
    die if (!defined $exptSetId) || (!defined $pubId) || $pubId eq "" || $exptSetId eq "";
    die if !exists $pubs->{"PubMedID"}{$pubId};
   
    print join("\t",
	       map { defined($_) ? $_ : "" } ( $pubs->{"Citation"}{$pubId},
					       $pubs->{"PubMedID"}{$pubId},
					       $exptSetId,
					       "?", "?", "?", "?", "?", "?", "?", "?",
					       $exptId, $exptAttrs{$exptId}{"Experiment Name"},
					       $exptAttrs{$exptId}{"Description"},
					       $exptAttrs{$exptId}{"Channel 1 Description"},
					       $exptAttrs{$exptId}{"Channel 2 Description"},
					       "?", "?", "?",
					       $exptAttrs{$exptId}{"Printname"},
					       $pubs->{"Citation"}{$pubId} ), ),"\n";
}
