#!/usr/bin/perl -s

use DBI;

$format = 'tab';
if ($f) {
	$format = 'fasta-aa';
} elsif ($n) {
	$format = 'fasta-nt';
}
$dbname = 'mbgd' if (! $dbname);
if ($ENV{'HOST'}) {
	$hostname = $ENV{'HOST'};
} else {
	$hostname = `hostname`; chomp $hostname;
}

$DBS .= "dbi:mysql:database=$dbname";
if (!defined($user) || !defined($pass)) {
	if ($ENV{'RECOG_HOME'}) {
		$DBS .= ";mysql_read_default_file=$ENV{'RECOG_HOME'}/etc/my.cnf";
	} else {
		$DBS .= ";mysql_read_default_file=$ENV{'HOME'}/.my.cnf";
	}
}
$db = DBI->connect($DBS, $user, $pass);

if ($format eq 'tab') {
	$cmd = "select * from gene where sp=?";
	$cmd .= " and name=?" if (! $sp);
	$cmd .= " order by from1";
} elsif ($format eq 'fasta-aa') {
	$cmd = "select g.sp,g.name,g.gene,g.descr,p.seq " .
		"from gene g, proteinseq p where g.aaseq=p.id and g.sp=?";
	$cmd .= " and g.name=?" if (! $sp);
	$cmd .= " and  g.type='CDS'" if (!$sp);
	$cmd .= " order by from1";
} elsif ($format eq 'fasta-nt') {
	$cmd= "select g.sp,g.name,g.gene,g.descr,p.seq" .
		" from gene g, geneseq p where g.ntseq=p.id and g.sp=? ";
	$cmd .= "and g.name=?" if (! $sp);
	$cmd .= " order by from1";
}
$sth=$db->prepare($cmd);

foreach $name (@ARGV) {
	($spec,$name) = split(/:/, $name);
	if ($sp){
		$sth->execute($spec);
	} else {
		$sth->execute($spec,$name);
	}
	while ($a = $sth->fetchrow_hashref) {
		if ($format eq 'tab'){
			print join("\t", $a->{sp}, $a->{name},$a->{gene},$a->{descr});
			print "\n";
		} elsif($format =~ /^fasta/) {
			print ">", $a->{sp}, ":", $a->{name};
			print " (", $a->{gene},") " if ($a->{gene});
			print " $a->{descr}\n";
			&print_fasta($a->{seq});
##			print "$a->{seq}\n";
		}
	}
}

sub print_fasta {
	my($seq) = @_;
	my $LINELEN = 60;
	my($seqlen) = length($seq);
	for (my $i= 0; $i < $seqlen; $i+= $LINELEN) {
		print substr($seq, $i, $LINELEN);
		print "\n";
	} 
}
