#!/usr/bin/perl
# Name: uniprotParse_plant.pl
# Authour: Jack Min
# Date:  Dec 14, 2009
#
# Modified: Gengkon Lum January 6, 2011
# Modified: Gengkon Lum September 9, 2011
#
# This tool is to extract subcellular location from uniprot-sp and trembl database
# This version uses UniProt Accession number, needed to modify to get only the 
# primary accession number and not secondary ones (if any).
# 
######   NOTE!! Even though plant is in the name of the file, this script does not
######          differentiate between plants and non-plants
######   EDIT NOTE!! This version pulls out only Viridiplantae (or others if changed)
#

if($#ARGV != 1)
{
    print "uniprotRetriSubLocation.pl input output\n";
    exit;
    }

print "it is running ...\n";

 # initialize all variables

  my $input = $ARGV[0];
  my $outF = $ARGV[1];

$int = 0;
open(INPUT, $input) || die("Cannot open file $input!");
$offSet = tell(INPUT);
while ($record = get_next_record(INPUT))
{ #foreachloop #1
	@recordA = split(/\n/, $record);
     	$int++;
	print $int."\n";
	$subFlag = 0;
	$ac_flag = 0;
	$ViridiplantaeFlag = 0;
	foreach $item (@recordA) #foreach start
	{
		chomp ($item);
     		if ($item =~ /^ID/)
		{
			@tmp = split (/\s+/,$item);
         		# $id = $tmp[1]; # We want Accession instead
			@tmp2 = split(/\;/, $tmp[2]);
			$status = $tmp2[0];
	 	}
		elsif (($item=~/^AC/) && ($ac_flag == 0))
		{
			@tmp = split (/\s+/,$item);
			@tmp2 = split(/\;/, $tmp[1]);
			$id = $tmp2[0]; # UniProt Accession (primary)
			$ac_flag = 1;
	 	}
		elsif (($item=~/^AC/) && ($ac_flag == 1))
		{
			next; # Skip any secondary accession numbers
		}
		elsif (($item =~ /^OC/) && ($item=~ /Eukaryota/)) # Keywords to search in taxonomy
	        {
			if ($item =~ /Viridiplantae/) # for Fungi: replace Viridiplantae with "Fungi"  for animals/human "Metazoa"
			{
				$ViridiplantaeFlag = 1;
			}
		}
		elsif (($item=~/^CC/) && ($item =~ /-!- SUBCELLULAR LOCATION:/))
         	{
			@tmp = split(/LOCATION:/, $item);
			$subFlag = 1;
			$subText = $tmp[1];
			$lNum = 1;
		}
		elsif ($item=~/^CC/ && $item =~ /-!-/  && $subFlag == 1 && $ViridiplantaeFlag == 1)
		{
			push (@outA, $id."\t".$status."\t".$subText."\n");
			last;
		}
		elsif ($item=~/^CC/ && $item =~ /----------/  && $subFlag == 1 && $ViridiplantaeFlag == 1)
		{
			push (@outA, $id."\t".$status."\t".$subText."\n");
			last;
		}
		elsif (($item=~/^CC/) && ($subFlag == 1) && ($ViridiplantaeFlag == 1))
		{		
			@tmp = split(/      /, $item);
			$subText .= $tmp[1];
		}
               else
		{
			next;
		}
	}
	$offSet = tell(INPUT);
} #end of while
close (INPUT);
###########

open(OUT, ">$outF");
print OUT @outA;
close(OUT);


print "The work is done!!!\n";
exit;

sub get_next_record
{
        my($fh) = @_;
        use strict;
        my($offSet);
        my($record);
        my($seperator) = $/;
        $/ = "//\n";
        $record =<$fh>;
        $/ =$seperator;
        return $record;
}
