#!/home/fxing/localperl/bin/perl-static 

eval 'exec /home/fxing/localperl/bin/perl-static  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use warnings;
use strict;
use FindBin;
use lib "$FindBin::Bin/../lib";
use lib "$FindBin::Bin/../perl/lib";

use Getopt::Long;
use File::Temp;
use vars qw($JB $RS);

BEGIN{
    my $loc = `which flatfile-to-json.pl 2> /dev/null`;
    chomp $loc;
    if ($loc =~ /^no flatfile-to-json.pl/ || ! $loc) {
	$loc = `which ./bin/flatfile-to-json.pl 2> /dev/null`;
	chomp $loc;
    }

    if ($loc =~ /^no flatfile-to-json.pl/ || ! $loc) {
	die "FATAL: Can not find flatfile-to-json.pl\n".
	    "Make sure JBrowse is installed and the executables are in your PATH.\n";

    }
    else {
	$JB = [split("\n", $loc)]->[-1];
    }

    $loc = `which prepare-refseqs.pl 2> /dev/null`;
    chomp $loc;
    if ($loc =~ /^no prepare-refseqs.pl/ || ! $loc) {
	$loc = `which ./bin/prepare-refseqs.pl 2> /dev/null`;
	chomp $loc;
    }
    if ($loc =~ /^no prepare-refseqs.pl/ || ! $loc) {
	die "FATAL: Can not find prepare-refseqs.pl\n".
	    "Make sure JBrowse is installed and the executables are in your PATH.\n";

    }
    else {
	$RS = [split("\n", $loc)]->[-1];
    }
}

my $usage = '
USAGE:
     maker2jbrowse [OPTION] <gff3file1> <gff3file2> ...
     maker2jbrowse [OPTION] -d <datastore_index>

     This script takes MAKER produced GFF3 files and dumps them into a
     JBrowse for you using pre-configured JSON tracks.

OPTIONS:
     ds_index|d  <file>  Provide MAKER produced datastore index

     help|?              Displays this usage statement

';

my $dstore;

GetOptions("ds_index|d=s" => \$dstore,
	   "help|?" => sub {print $usage; exit()}
	   );

my @files;

die "ERROR: The file ds_index\'$dstore\' does not exist\n" if ($dstore && ! -e $dstore);

if($dstore){
    my $base = $dstore;
    $base =~ s/(\/?)[^\/]+$/$1/;
    open(IN, "< $dstore");

    #uniq the entries
    my %seen;
    while(my $e = <IN>){
        next unless ($e =~ /FINISHED/);
        next if $seen{$e};
        $seen{$e}++;
        chomp $e;
        my ($id, $dir, $status) = split("\t", $e);
        $dir =~ s/\/$//;
        push(@files, $dir);
    }

    foreach my $file (@files){
        $file =~ /([^\/]+)$/;
        $file = ($base) ? "$base/$file/$1.gff" : "$file/$1.gff";
    }
}
else{
    @files = @ARGV;
    undef @ARGV;
}

if(!@files){
    print $usage;
    exit();
}

my $error;

foreach my $file (@files){
    if (! -f $file){
	$error .= "ERROR: The GFF3 file \'$file\' does not exist\n";
    }
}

die $error if $error;

#--build command lines
my %commands;

#MAKER anotations
$commands{gene}           = ' --tracklabel "Genes" --key "Genes" --getType --getLabel --autocomplete label --cssclass feature5 --type gene';
$commands{maker}          = ' --tracklabel "Transcripts" --key "Transcripts" --getType --getSubs --getLabel --autocomplete label --cssclass transcript --subfeatureClasses \'{"exon": "transcript-exon", "CDS": "transcript-CDS", "UTR": "transcript-UTR"}\' --arrowheadClass transcript-arrowhead --type mRNA';

#ab initio gene predictions
$commands{snap}           = ' --tracklabel "SNAP" --key "SNAP" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon2"}\' --arrowheadClass transcript-arrowhead --type match:snap';
$commands{snap_masked}    = ' --tracklabel "SNAP" --key "SNAP" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon2"}\' --arrowheadClass transcript-arrowhead --type match:snap_masked';
$commands{augustus}       = ' --tracklabel "Augustus" --key "Augustus" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon3"}\' --arrowheadClass transcript-arrowhead --type match:augustus';
$commands{augustus_masked} = ' --tracklabel "Augustus" --key "Augustus" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon3"}\' --arrowheadClass transcript-arrowhead --type match:augustus_masked';
$commands{genemark}       = ' --tracklabel "GeneMark" --key "GeneMark" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon4"}\' --arrowheadClass transcript-arrowhead --type match:genemark';
$commands{genemark_masked} = ' --tracklabel "GeneMark" --key "GeneMark" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon4"}\' --arrowheadClass transcript-arrowhead --type match:genemark_masked';
$commands{fgenesh}        = ' --tracklabel "FGENESH" --key "FGENESH" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon5"}\' --arrowheadClass transcript-arrowhead --type match:fgenesh';
$commands{fgenesh_masked} = ' --tracklabel "FGENESH" --key "FGENESH" --getType --getSubs --getLabel --cssclass transcript --subfeatureClasses \'{"match_part": "transcript-exon5"}\' --arrowheadClass transcript-arrowhead --type match:fgenesh_masked';

#evidence alignments
$commands{blastn}         = ' --tracklabel "BLASTN" --key "BLASTN" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part4"}\' --type expressed_sequence_match:blastn';
$commands{blastx}         = ' --tracklabel "BLASTX" --key "BLASTX" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part5"}\' --type protein_match:blastx';
$commands{tblastx}        = ' --tracklabel "TBLASTX" --key "TBLASTX" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part6"}\' --type expressed_sequence_match:tblastx';
$commands{est2genome}     = ' --tracklabel "est2genome" --key "est2genome" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part3"}\' --type expressed_sequence_match:est2genome';
$commands{protein2genome} = ' --tracklabel "protein2genome" --key "protein2genome" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part2"}\' --type protein_match:protein2genome';
$commands{iprscan} = ' --tracklabel "InterPro" --key "InterPro" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part7"}\' --type match:iprscan';

#repeats
$commands{repeatmasker}   = ' --tracklabel "RepeatMasker" --key "RepeatMasker" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part7"}\' --type match:repeatmasker';
$commands{'blastx:repeatmask'}  = ' --tracklabel "RepeatRunner" --key "RepeatRunner" --getType --getSubs --cssclass generic_parent --subfeatureClasses \'{"match_part": "match_part7"}\' --type protein_match:blastx:repeatmask';


foreach my $file (@files){
    my $gff;
    my $fasta;
    my %tracks;

    open(IN, "< $file");
    my $ff; #fasta flag
    while(defined(my $line = <IN>)){
	if($ff){
	    $fasta .= $line;
	    next;
	}
	elsif($line =~ /^\#\#FASTA/){
	    $ff = 1;
	    next;
	}
	elsif($line =~ /[^\t]*\t[^\t]*\tcontig\t/){
	    next; #skip contig line
	}
	else{
	    if($line !~ /^\#/ && $line =~ /[^\t]*\t([^\t]*)\t/){
		$tracks{$1}++;
		$tracks{gene}++ if($1 eq 'maker'); #add gene locus track
	    }

	    $gff .= $line;
	    next;
	}
    }
    close(IN);

    if($fasta){
	my ($fh, $fname) = File::Temp::tempfile();
	print $fh $fasta;
	close($fh);

	my $command = $RS;
	$command .= " --fasta $fname";

	system ($command);
	unlink($fname);
    }

    if($gff){
	my ($fh, $fname) = File::Temp::tempfile();
	print $fh $gff;
	close($fh);

	while(my $track = each %tracks){
	    my $command = $JB;

	    if(! exists $commands{$track}){
		warn "ERROR: No track information for source \'$track\'\n\n";
		next;
	    }

	    $command .= $commands{$track};
	    $command .= " --gff $fname";

	    system ($command);
	}

	unlink($fname);
    }
}
