#!/usr/bin/perl
# Name: uniprotParse.pl
# Authour: Jack Min
# Date:  Dec 14, 2009
# This tool is to extract subcellusr location from uniprot-sp and trembl database
# 

if($#ARGV != 1)
{
    print "uniprotRetriSubLocation.pl input output\n";
	print "Note: change status to 'unreviewed' for trembl dataset\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;
	$fungalFlag = 0;
	foreach $item (@recordA) #foreach start
	{
		chomp ($item);
     	if ($item =~ /^AC/)
		{
			#@tmp = split (/\s+/, $item);
         	#	$id = $tmp[1];
			#@tmp2 = split(/\;/, $id);
			#$id = $tmp2[0];
			$id = substr($item, 5);
			@tmp2 = split(/\;/, $id);
			$count = scalar(@tmp2);
			
			$status = "reviewed";
			$subFlag = 0;
	 	}
		elsif ($item =~ /^OS/)
		{
			@tmp = split (/\s+/,$item);
         	$species = substr($item, 5);
			$species =~ s/\.//;
	 	}
		elsif ($item =~ /^OC/ && $item =~ /Eukaryota;/)
		{
			$fungalFlag = 1; push (@spA, $id."\n"); #all fungal proteins
			if ($count > 1)
			{
				push (@oA2, $id."\n");
			}
        }
		elsif (($item=~/^CC/) && ($item =~ /-!- SUBCELLULAR LOCATION:/))
         	{
			@tmp = split(/LOCATION:/, $item); $subFlag = 1;
			$subText = $tmp[1];
			$lNum = 1;
		}
		
		elsif ($item=~/^CC/ && $item =~ /-!-/  && $subFlag == 1)
		{
			push (@outA, $id."\t".$status."\t".$subText."\n");
			if ($fungalFlag == 1)
			{
				push (@outA2, $id."\t".$species."\t".$status."\t".$subText."\n");
			}
			last;
		}
		elsif ($item=~/^CC/ && $item =~ /----------/  && $subFlag == 1)
		{
			push (@outA, $id."\t".$status."\t".$subText."\n");
			if ($fungalFlag == 1)
			{
				push (@outA2, $id."\t".$species."\t".$status."\t".$subText."\n");
			}
			last;
		}
		elsif (($item=~/^CC/) && ($subFlag == 1))
		{		
			@tmp = split(/      /, $item);
			$subText .= $tmp[1];
		}
	}
	#if ($subFlag == 1)
	#{
	#	$status = "Reviewed"; # Unreviewed
	#	push (@outA, $id."\t".$subText."\t".$status."\n");
	#}
	$offSet = tell(INPUT);
}#end of while
close (INPUT);
###########

open(OUT, ">$outF");
print OUT @outA2; #fungal sub location
close(OUT);

$F3 = "multip.ids";
open(OUT, ">$F3");
print OUT @oA2;
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;
}


