#!/usr/bin/perl -w
# mz3 script for adding parent-children relationship to a gtf file and make it into gff

use strict;

# Control that input parameters are correct
unless (@ARGV > 0 ) {
        &USAGE;
}

# Make in and output files
my $in = shift;
my $out = $in;
$out =~s/gtf/gff/;

# Open infile and outfile
open (IN, "<$in") or die "Cant find infile $in\n" ;
if (-e "$out") {
    die "File $out already exists, cant overwrite\n";
}
else {
    print "outfile $out\n\n";
}
open (OUT, ">$out") or die "Cant find infile $out\n" ;

# Make global variables to store data in
my $current_ID = "";
my $last_ID = "";
my $counter = "0";
my @result = '';
my $ID_number = "0";
my %seen;

# Go through input file and reformat
while (<IN>) {
	chomp;
tr/=/ /;

	my @line = split (/\s+/, $_);
	my $name = $line[0];
	my $method = $line[1];
	my $tag = $line[2];
	my $start = $line[3];
	my $end = $line[4];
	my $score = $line[5];
	my $strand = $line[6];
	my $note = $line[9];
	$note =~ s/"//g;
	$note =~ s/;//;

# Reformat transcripts
if ($tag =~ /transcript/) {
	$ID_number ++;
	
    # check if that gene has been seen before - if it has, don't output it again
    unless (exists $seen{$note}) {
        my $newline = "$name\t$method\tgene\t$start\t$end\t.\t$strand\t.\tID=$name.$note\n";
    	push (@result, $newline);
        $seen{$note}=1;
        $ID_number=1;
    };
	my $newline2 = "$name\t$method\ttranscript\t$start\t$end\t.\t$strand\t.\tID=$name.$note.t$ID_number;Parent=$name.$note\n";
	push (@result, $newline2);
	$last_ID = $note;
	$counter = "0";
}
# and reformat exons
elsif ($tag =~ /exon/) {	
	$current_ID = $note;		
		if ($current_ID eq $last_ID) {
		$counter ++;
		}
	my $newline = "$name\t$method\tCDS\t$start\t$end\t.\t$strand\t.\tID=$name.$note.t$ID_number.Exon$counter;Parent=$name.$note.t$ID_number\n";
	push (@result, $newline);

}

else {
print "This line is not transcript or exon: $_";
}

}

# Print output
 print OUT @result;
 
# Close file handles
 close (OUT);
 close (OUT);


exit;


#######  SUBROUTINES  ################

sub USAGE {

die 'Usage: perl cufflinks2gff.pl <gtf-file> 

This script reformats the cufflinks gtf-file to a format which displays better in Artemis


'
}



__END__

