use strict;
use warnings;
use Roman;
use xmlInputForEqtlViewer;

my $filePath_eQTL_list='G:\back\Downloads\doc\yeastAug05\output\terms_in';
my $filePath_working='G:\back\Downloads\doc\yeastAug05\svg';
my $filePath_gff='G:\back\Downloads\doc\yeastAug05\sources\saccharomyces_cerevisiae.gff';



my $insertGene='insert8.gene';
my %insert=();
if($insertGene){
	load_insert($insertGene);
}


my %featureList=();
gff();


my %eQTL_list=();
load_qtl();

output(\%featureList,\%eQTL_list,getSetting(),0,'input.xml');

print "\a\a\a";

sub getSetting{
	my %r=(
		'urlPrefix'=>'http://db.yeastgenome.org/cgi-bin/locus.pl?locus=',
		'title'=>'Yeast eQTL Two Dimensional Plot');
	return \%r;
}


sub gff{
	
	
	unless (open (GFF,$filePath_gff)){die;}
	while (<GFF>) {
		if (/FASTA/) {last;
		}

		if (/ID.*Name/) {
			my ($chr,$pos)=();

			my @space=split/\t/;
		
			if ($space[3]=~/\d+/ and $space[4]=~/\d+/) {
				$pos=($space[3]+$space[4])/2;
			}
			else{
				next;
			}

			$space[0]=~/chr(\w+)/;
			if (isroman($1)) {
				$chr= arabic($1)
			}
			else{
				if ($1 ne "Mito") {
					print $_;
					die ;
				}
				next;
			}

			$space[8]=~/ID=([-\.\)\(\w]+);.*Name=([-\.\)\(\w]+);/;

			if ($1 ne $2) {
				print $_."\n";
				die "error in $_ \n $1 not equal to $2\n";
			}
			
			$featureList{$1}{chr}=$chr;
			$featureList{$1}{pos}=$pos;

			if (exists $insert{$1}) {
				foreach my $i (@{$insert{$1}}) {
					$featureList{$i}{chr}=$chr;
					$featureList{$i}{pos}=$pos+1;
				}
			}
		}
	}
	close(GFF);


	print "number of feature in gff:",scalar keys %featureList,"\n";

}

sub load_qtl{
	
	opendir THISDIR, $filePath_eQTL_list  or die "serious dainbramage: $!";
	my @allfiles = grep /Y[A-P][LR]\d/,readdir THISDIR;
	closedir THISDIR;
	
	foreach my $file (@allfiles) {
		if (length($file)<4) {
			die;
		}
		$file=~/(.*)_/ or die;
		my $eORF=$1;

		open(IN,$filePath_eQTL_list.'\\'.$file) or die;
	
		my @genes=();
		while (<IN>) {
			chomp;
			next unless ($_);
			push(@genes,$_) ;
		}

		close(IN);

		push(@{$eQTL_list{$eORF}},[sort(@genes)]);
	}

}


sub load_insert{
	open(IN,$filePath_working.'\\'.$insertGene) or die;
	while (<IN>) {
		if (/\#/) {
			next;
		}
		chomp;
		if (length($_)==0) {
			next;
		}
		
		my @s=split(/\s+/);
		my $group_id=shift(@s) ;
		foreach my $gene (@s) {
			push(@{$insert{$group_id}},$gene);
		}
	}
	close(IN);
}