#! /usr/bin/perl
use strict;
use Getopt::Std;

  die "usage:novel_prop.pl genomelist fasta  psl_file ncid2spe_file" if (@ARGV<4); 	
  
  my $genomelist=shift;
  my $fasta=shift;
  my $pslfile=shift;

  my $blat="blat $genomelist $fasta $pslfile";
  system( "$blat" );

  my %ncid2spe;
  while (<>) {
  	chomp;
	my @gg=split;
	$ncid2spe{ $gg[0] } =$gg[1];
  }

  my $results;
  my $perfect;
  my $match;
  my $mismatch;
  my $length;
  my $count;
  $results = ReadBlat( $pslfile );
  foreach my $q ( keys %{$results}) {
    my $prefix=$ncid2spe{ $results->{$q}[13] };
    $count->{$prefix}++;
    $match->{$prefix} += $results->{$q}[0];
    $perfect->{$prefix} +=  $results->{$q}[10]== $results->{$q}[0];
    $mismatch->{$prefix} += $results->{$q}[1];
    $length->{$prefix} += $results->{$q}[10];
  }

foreach my $spe (keys %{$count}) {
    print join("\t", $spe, $count->{$spe}, $match->{$spe}), "\n";

}
  


sub ReadBlat {
    my ( $file ) = @_;
    my $mat;
    open(DENOVO,$file) || die "Could not open $file\n";
    while(<DENOVO>) {
	chomp;
	my @a = split;
	if ( $a[0] > 0 ) {
	    my ( $match, $mismatch, $rep, $N, $QgapC, $lenN,$TgapC, $TgapN, $strand, $QName, $Qsize, $Qstart, $Qend,$TName ) = @a;
	    $mat->{$QName} = [$match, $mismatch, $rep, $N, $QgapC, $lenN,$TgapC, $TgapN, $strand, $QName, $Qsize, $Qstart, $Qend,$TName] if ( $mat->{$QName}[0] < $a[0] );
	}
    }
    return $mat;
}
