#!/usr/bin/perl -s

$| = 1;

require 'libSeq.pl';
use MBGD;

if (!defined($main::text)) {
    print "content-type: text/html\n";
    print "\n";
    print "<HTML>\n";
    print "<PRE>\n";
}

$entnames = join(',', @ARGV);

#$dbname = $main::DBNAME_MBGD;
#print STDERR "DBNAME :: $dbname\n";
$db = MBGD::DB->new($dbname);
foreach $ent (@ARGV) {
	($sp,$name) = split(/:/,$ent);
	$name =~ s/\(\d*\)//;

	$sql = "select chrid,from1,to1,dir from gene where sp='$sp' and name='$name'";
print "SQL :: $sql\n" if ($main::DEBUG);
	$sth = $db->execute($sql);
	($chrid,$from,$to,$dir) = $sth->fetchrow_array;
	if ($up && $dir > 0) {
		$from -= $up;
	}
    elsif ($up && $dir < 0) {
		$to += $up;
	}
    if ($down && $dir < 0) {
		$from -= $down;
	}
    elsif ($down && $dir > 0) { 
		$to += $down;
	}
	$len = $to-$from+1;
	$sql = "select substring(s.seq,$from,$len) from dnaseq s, chromosome c where c.id='$chrid' and c.seq=s.id";
print STDERR "SQL :: $sql\n" if ($main::DEBUG);
	$sth = $db->execute($sql);
	($seq) = $sth->fetchrow_array;
	if ($dir < 0) {
		$seq = &reverse($seq);
	}
    if ($delimiter ne '') {
        if ($up) {
            substr($seq, $up, 0) = $delimiter;
        }
        if ($down) {
            substr($seq, -$down, 0) = $delimiter;
        }
    }
	print ">$ent $from $to $dir\n";
	&print_seq($seq);
}
