#!/usr/bin/perl -w
use strict;
use DB_File;

if (!$ARGV[0] or $ARGV[0] eq "help") {
  print <<EOF;

  This program extracts a single chromatogram from a Berkeley Database file
  and outputs it in as a tempfile to a path specified on the command line.

  Usage: <berkeley dbfile> <chromatogram name> <output path>

  NOTE: Output filename will be the chromatogram name. If path is not 
        specified, will dump in the current directory. This program never
        overwrites existing files.

EOF
exit(-1);
}

my ($dbfile, $cgram_id, $outdir) = @ARGV;

if ( ! -f $dbfile ) {
  print "Can't find database file \"$dbfile\"";
  exit(-1);
}

my %cgrams = ();
my $database = tie %cgrams, 'DB_File', "$dbfile", O_RDONLY, 0666, $DB_HASH
  or die "Failed bind database file \"$dbfile\" ($!)";

if (! defined($cgrams{$cgram_id})) {
  print "Unable to find chromatogram \"$cgram_id\" in database file ";
  print "\"$dbfile\"\n";
  exit(-1);
}

my $outfile;
if (defined($outdir)) {
  $outfile = "$outdir/$cgram_id";
} else {
  $outfile = "$cgram_id";
}

if ( -f "$outfile") {
  print "A file named \"$outfile\" already exists. This program will not";
  print " overwrite it.\n";
  exit(-1);
}

open OUT, "| bzip2 -dc - > $outfile"
  or die "Failed to open pipe to bzip2 for output file \"$outfile\" ($!)";

syswrite OUT,$cgrams{$cgram_id};

close OUT;

undef $database;
untie %cgrams;

