#!/usr/bin/perl 

use Data::Dumper;
use Getopt::Long;

## External paths:
my $PATH_UID = "/home/miguel/projects/def_microarrays/data/UID_to_FBgn_31Aug05.txt";
my $PATH_FB  = "/home/miguel/projects/def_microarrays/prov/fbgns/erase/FBgn_Sym_CG_4-0.txt";
my $PATH_RL  = "/home/miguel/db/D.melanogaster/v4/annotations/refLink.txt";

## Leemos opciones ##
my $uids_file;
my $out_type = "r";
my $help = 0;
my $verbose = 0;
my $type_ok = 0;
my $options = GetOptions ("list=s"       => \$uids_file,
			  "uids:s"       => \$PATH_UID,
			  "fb:s"         => \$PATH_FB,
			  "rl:s"         => \$PATH_RL,
			  "out=s"        => \$out_type,
			  "verbose"      => \$verbose,
			  "help"         => \$help);

if ($out_type eq "r" || $out_type eq "f" || $out_type eq "n"){ $type_ok = 1}
if (($help) || (!defined ($uids_file)) || (!$type_ok)){
         print <<EOF;

synonyms.pl --list <file> [options]
Currently available options:
	--uids <path_to_file>    : File containing the correspondencies UID<->FBgns (tab sep)
	--fb   <path_to_file>    : File containing the correspondencies FBGns<->Names<->CGs (tab sep)
	--rl   <path_to_file>    : RefLink.txt
	--out  <f,n,r>           : Codes to retrive (f:FBgns, n:Names, r:RefSeqs) (default:r)
	--verbose                : Verbose mode
	--help                   : Displays this document

EOF
 exit(0);
}

####

my @lista_de_uids;
open L, $uids_file or die $!;
while (<L>){
#    print $_;
    chomp;
    $_ =~ s/\r//o;
    push @lista_de_uids, $_ if (!&isin_array (\@lista_de_uids, $_));
}


## UIDS vs FBgns ##
# print STDERR "Cargando archivo UID vs FBgn... " if ($verbose);
# open U, $PATH_UID or die $!;
# my %uids;
# while (my $uid_line=<U>){
#     chomp $uid_line;
#     ($uid, $ff) = split "\t", $uid_line;
#     $uids{$uid} = $ff;
# }
# close (U);
# print STDERR "Done\n" if ($verbose);

## FBgns VS NAMES ##
print STDERR "Cargando archivo de asociaciÃ³n... " if ($verbose);
open F, $PATH_FB or die $!;
my %asoc;
while (<F>){
    my $assoc_line;
    ($assoc_line = $_) =~ s/\r//o;;
    chomp ($assoc_line);
    ($fb,$name,$cg) = split /\s+/o, $assoc_line;
    $asoc{$fb}=$name;
}
close (F);
print STDERR "Done\n" if ($verbose);

#  $msg = Dumper (\%asoc);
#  print $msg;
#  exit();

## NAMES vs REFSEQ ##
print STDERR "Cargando refLink.txt... " if ($verbose);
open R, $PATH_RL or die $!;
my %reflink;
while (my $reflink_line=<R>){
    chomp $reflink_line;
    ($nn, $cc, $refseq, @rest) = split "\t", $reflink_line;
    $reflink{$nn} = $refseq;
}
close (R);
print STDERR "Done\n" if ($verbose);


##############
foreach my $f (@lista_de_uids){
 #   $f = $uids{$u};
    $n = $asoc{$f};
    $r = $reflink{$n};

#    print "$f\n" if ($out_type eq "f");
    print "$n\n" if ($out_type eq "n");
    print "$r\n" if ($out_type eq "r");
    print "$u -> $fb -> $n -> $r\n" if ($verbose);
}

sub isin_array
{
    my ($array_ref, $item);

    foreach my $arritem (@{$array_ref}){
	return 1 if ($arritem eq $item);
    }
    return 0;
}
