%%START_PERL%%
my $VERSION = '$Id: cv-check.pl.in,v 1.2.2.1 2001/01/15 18:52:04 jes Exp $ ';

use strict;
use blib;
use Carp;
use Getopt::Long;
use File::Basename;
%%GENEX_EXTRALIBS%%

use XML::DOM;

use Bio::Genex;
use Bio::Genex::DBUtils qw(create_select_sql);

my $dbh = Bio::Genex::current_connection();
foreach my $infile (@ARGV) {
  print STDERR "Checking $infile\n";

  my $PARSER = XML::DOM::Parser->new();
  my $DOC = $PARSER->parsefile($infile);
  my ($cv_node) = $DOC->getElementsByTagName('controlled_vocabulary');
  error ($dbh,"Couldn't find controlled_vocabulary element") 
    unless defined $cv_node;

  my $db_table = $cv_node->getAttribute('db_table');
  error ($dbh,"db_table attribute not defined for file: $infile")
    unless $db_table ne '';

  my $db_column = $cv_node->getAttribute('db_column');
  error ($dbh,"db_column attribute not defined for file: $infile")
    unless $db_column ne '';

  print STDERR "Handling column $db_column in table $db_table\n";
  my @term_list = $DOC->getElementsByTagName('term');
  die "no terms found"  unless scalar @term_list;

  @term_list = map {$_->getAttribute('name')} @term_list;
  my $sql = create_select_sql($dbh,
			      FROM=>[$db_table],
			      COLUMNS=>[$db_column],
			      DISTINCT=>1,
			     );

  my $result_ref = $dbh->selectall_arrayref($sql);
  die "SQL=<$sql>, DBI=<$DBI::errstr>" if $dbh->err;

  foreach my $term (@{$result_ref}) {
    warn("  Bad vocab term in DB: $term->[0]\n")
      unless grep {$term->[0] eq $_} @term_list;
  }
}

$dbh->disconnect();
exit(0);

sub error {
  my ($dbh,$msg,$sth) = @_;
  $dbh->disconnect();
  $sth->finish() if defined $sth;
  die $msg;
}
