#! /usr/bin/perl

# $Id: make-fusion-exons.pl,v 1.3 2009-11-10 22:42:21 waltsbm Exp $

# Modified by Victor Amin 2010-04-13 to make fusions strand independent and to
# correctly handle GFFs with comments and/or FASTA sections.

# Input GFF file containing "exon" feature types via STDIN. STDOUT is a table
# with the format FUSION_ID\tEXON_ID\tCHROM\tSTART\tEND. Fusion ids start with
# an "S" if they are singletons (contain only one exon). Fusion ids contianing
# multiple exons start with F and have one line for each exon.

use strict;
use warnings;

# Commented lines in the remainder of the script can be uncommented to make
# strand dependent fusions

my $fusion_number = 1;
my %chromosomes;
my %fusions;
my %fusionstarts;
my %fusionends;
my %fusionchrs;

while (<>) {
    if (/^##FASTA/) {last}
    if (/^##/) {next}
    chomp;
    my ($seq,
	$source,
	$featuretype,
	$start,
	$end,
	$f1,
	$strand,
	$f2,
	$idline) = split;

    next if ($featuretype ne "exon" || ($start < 0) || ($end < 0));

    my @idarr = split(/;/, $idline);
    my $id = $idarr[0];
    $id =~ s/ID=//;

    for (my $i = $start; $i <= $end; $i++) {
	#push(@{$chromosomes{$seq}{$strand}[$i]}, $id);
	push(@{$chromosomes{$seq}[$i]}, $id); # comment this out for strand dependent fusions
    }

}

foreach my $chromosome (keys(%chromosomes)) {
    #foreach my $strand (keys(%{$chromosomes{$chromosome}})) {
	#my @seq = @{$chromosomes{$chromosome}{$strand}};
	my @seq = @{$chromosomes{$chromosome}}; # comment this out for strand dependent fusions
	my $in_fusion = 0;
	my $i = 0;
	for ($i = 1; $i < @seq; $i++) {
	    if (defined($seq[$i])) {
			if ($in_fusion == 0) {
			    $fusionstarts{$fusion_number} = $i;
			    $fusionchrs{$fusion_number} = $chromosome;
			}
			$in_fusion = 1;
			foreach my $exon (@{$seq[$i]}) {
			    $fusions{$fusion_number}{$exon} = 1;
			}
	    } else {
			if ($in_fusion == 1) {
			    $fusionends{$fusion_number} = $i - 1;
			    $fusion_number++;
			}
			$in_fusion = 0;
	    }
	}
	if ($in_fusion == 1) {
	    $fusionends{$fusion_number} = $i - 1;
	    $fusion_number++;
	}
   #}
}

foreach my $fusionnum (keys(%fusions)) {
    my @exons = keys(%{$fusions{$fusionnum}});
    if (@exons == 1) {
		print "S${fusionnum}_SI\t$exons[0]\t$fusionchrs{$fusionnum}\t$fusionstarts{$fusionnum}\t$fusionends{$fusionnum}\n";
    } else {
		foreach my $exon (@exons) {
	    	print "F${fusionnum}_SI\t$exon\t$fusionchrs{$fusionnum}\t$fusionstarts{$fusionnum}\t$fusionends{$fusionnum}\n";
		}
    }
}
