=head1 NAME

  CFX5::Simulation::Util - misc utilities for CFX5::Simlulation

=head1 SYNOPSIS

  use CFX5::Simulation::Util qw(_check_defined);

=head1 DESCRIPTION

$Id$

=cut

package CFX5::Simulation::Util;

use base 'Exporter';
use vars '@EXPORT_OK';
push @EXPORT_OK, '_check_defined', 'GetDataSet';

use CFX5::Output qw(:all);

=head3 Misc Helpers

=head4 _check_defined

  _check_defined($workdir, "working directory") or return 0;

Does a quick check to see if the variable is defined, and gives an
error if not; the return code is TRUE or FALSE, as for "defined
$_[0]".  Replaces the slightly less wieldy code

  unless (defined $workdir) {
    _error("No working directory has been specified");
    return 0;
  }

since I expect to use this a lot.  It is necessary to do this check
separately, since the functions in L<CFX5::FileTests> give (rightly)
an internal error if they are passed an undefined value.

=cut

sub _check_defined {
  my ($var,$name)=@_;
  unless (defined $var) {
    _error("A $name is required for this run, but none is available.  Either there is a command-line argument missing, or a previous step in the run has failed.");
    return 0;
  }
  1;
}

sub GetDataSet {
  my $fName = shift ;
  my $what  = shift ;
  my $where = shift ;
  my $when  = shift ;

  $where = "EVERY" unless (defined $where) ;
  $when  = "-1"    unless (defined $when) ;
  
  my $getLatest = 0 ; 
  if ($when eq "-2") {
    $when = "-1" ;
    $getLatest = 1; 
  }

  my @strdata ;

  my $io = CFX5::DefFile->new($fName) ;
  unless (ref $io) {
    _error("GetDataSet: Could not open $fName");
    return undef;
  }
 
  my @dsList = $io->have_dataset(what  => $what,
                                 where => $where,
                                 when  => $when);
  # Let caller decide if this is an error
  unless (@dsList) {
    return undef;
  }
  
  if ($getLatest) {
    foreach my $ds (@dsList) {
      $when = $$ds[2] if ($$ds[2] > $when) ; 
    }
  }

  my $ds = $io->read_dataset(what  => $what,
                             where => $where,
                             when  => $when);
  unless (ref $ds) {
    return undef;
  }

  @strdata = $ds->data() ;
}

1;
