#!/usr/bin/perl -s

use MBGD;
use FlatTab;
use File::Copy;

$dbname = "dbi:mysql:mbgd_accum";
if (! $current) {
	$dbname2 = "dbi:mysql:mbgd_work";
} else {
	$dbname2 = "dbi:mysql:mbgd";
}

$EDITOR = $ENV{EDITOR};
$EDITOR = "vi" if (! $EDITOR);
$separator = "##\t";

@spec = @ARGV;

$tmpfile = "/tmp/mbgdedit.$$";

$db = MBGD::DB->new("$dbname");
if ($dbname2) {
	$db2 = MBGD::DB->new("$dbname2");
}

$TYPE = 'Genome' if (! $TYPE);
$Class = "MBGD::$TYPE";

@data = $Class->get($db, \@spec);
$class = lc($TYPE);

$ftab = MBGD::FlatTab->new($class, {outfile=>$tmpfile, outsep=>$separator});
foreach $g (@data) {
	$g->print_flattab($ftab);
}
$ftab->close;

copy($tmpfile, "${tmpfile}_orig");
system("$EDITOR $tmpfile");

system("cmp $tmpfile ${tmpfile}_orig >/dev/null");
if (! $FORCE && $? == 0) {
	print STDERR "File unchanged\n"; 
} else {
	print STDERR "Save? [y/N]:";
	$ans = <STDIN>;
	if ($ans =~ /^[Yy]/) {
		$ftab = MBGD::FlatTab->new($class, {infile=>$tmpfile, sep=>$separator});
		while ($ftab->readData){
			$g = $Class->new($db, $ftab->getHash);
			$g->{id} = '';
			$g->store;
			if ($db2) {
			  $g = $Class->new($db2, $ftab->getHash);
			  $g->{id} = '';
			  $g->store;
			}
		}
	}
}

unlink($tmpfile);
unlink("${tmpfile}_orig");
