#!/usr/bin/perl -w

#
# tasuke_cuffdifftoGFF.pl
# http://tasuke.dna.affrc.go.jp/
#
# Author: Ryutaro Itoh
#
# Copyright (c) 2013 National Institute of Agrobiological Sciences   
#

use strict;
use Getopt::Long;

my $OUTFILE = "";
my $FILE = "";

################################################################
# Checking parameters and database connection
################################################################
GetOptions( 
            'o|outfile=s'     => \$OUTFILE,
            'i|infile=s'      => \$FILE     
);

if ($OUTFILE eq "" || $FILE eq "") {
  _error_method();  
  exit;
}

open IN, '<', $FILE or die "file open error: $!";
my $columns    =0;
    while (<IN>) {
        chomp;
        my @line = split(/\t/, $_);
        $columns = @line;
        last;
    }
close(IN);
if($columns !=14){
    print "The Input file is probably not Cuffdiff results.\n\n";
    exit;
}

###########################################################
# Creating TSV files 
###########################################################

_print_time(" Begin converting... ");
_createGFF($FILE, $OUTFILE);
_print_time(" Complete!");

###########################################################
# samtools depth
###########################################################
sub _createGFF{
    my $FILE = shift;
    my $OUTFILE = shift;
    
    open IN, '<', $FILE or die "file open error: $!";
    open OUT, '>', $OUTFILE or die "file open error: $!";
    while (<IN>) {
        chomp;
        my @line = split(/\t/, $_);
        if($line[13] eq "yes"){
            my @locus = split(/:/, $line[3]);
            my @pos = split(/-/, $locus[1]);
            my $str = "$locus[0]\tDE\tDE\t$pos[0]\t$pos[1]\t.\t.\t.\tID=$line[0]\;Name=$line[0];Note=differential expression;";
            print OUT $str."\n";
        }
    }
    close(IN);
    close(OUT);
}

#### time #######################################
sub _print_time {
  my ($str) = @_;
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
  $year += 1900;
  $mon += 1;
  my $datetime = sprintf "%04d-%02d-%02d %02d:%02d:%02d", $year, $mon, $mday, $hour, $min, $sec;
  print "$str : $datetime\n";
}

#### print usage #######################################
sub _error_method {
  print "\nConvert Cuffdiff result file to GFF3 file.\n";
  print "tasuke_cuffdifftoGFF.pl -i [Cuffdiff result] -o [output_file]  \n\n";
}
