#!/usr/bin/perl -w
##### Program description #######
#
# Title: search.pl
#
# Author(s): Mattias Ohlsson
#
# Description:
#
# List of subroutines:
#
# Overall procedure:
#
# Usage: ./search.pl {table-file} {key-file} {swissprot-file}
#
##################################
use strict;

#### The main program ####
unless ( @ARGV == 3 ) {
    die "You must have three files as argument";
}

# Read the key file
my $keyref = readKey($ARGV[1]);

# Open the table that we should complete
open my $tableFH, '<', $ARGV[0] or die "Cannot open table file $ARGV[0]";
while ( my $line = <$tableFH> ) {
    next if ( $line =~ /^PDB/ );
    chomp $line;
    my $pdbID = $line;
    $pdbID =~ s/\s*$//;
    my $swissID = $keyref->{$pdbID};
    my ($os, $seq) = searchSwiss($swissID, $ARGV[2]);

    print "$pdbID\t$os\n";
}
close $tableFH;

#### End of main program #####


sub readKey {
    my ($keyFile) = @_;

    open my $kFH, '<', $keyFile or die "Cannot open file $keyFile";
    
    my %ptos;
    while ( my $line = <$kFH> ) {
	next if ( $line =~ /^code/ );

	# Each line contains 3 items, we are only interested in the first two
	my ($pdb, $sid) = split ' ', $line;

	# Store in a hash
	$ptos{$pdb} = $sid;
    }
    close $kFH;

    return \%ptos;

} # End of readKey


sub searchSwiss {
    my ($swissID, $swissFile) = @_;
    
    open my $sFH, '<', $swissFile or die "Cannot open file $swissFile";
    
    my $os = '';
    my $seq = '';
    while ( my $line = <$sFH> ) {

	# Check for the correct ID line
	next unless ( $line =~ /^ID\s+$swissID\s+/ );

	# Now scan for OS and SQ
	my $read = 0;
	while ( my $line = <$sFH> ) {
	    
	    # Stop if we hit the last of entry code
	    last if ( $line =~ m|^//| );

	    # Collect the OS line
	    if ( $line =~ /^OS\s+(.+)$/ ) {
		$os .= $1 . ' ';
	    }

	    # Collect the sequence
	    if( $read ) {
		$seq .= $line;
	    } elsif ( $line =~ /^SQ/ ) {
		$read = 1;
	    }
	    
	}
	last;
    }
    close $sFH;

    $seq =~ s/\n//g;
    $seq =~ s/\s//g;

    return ($os, $seq);
    
} # End of searchSwiss
