opy all valid datasets from primary to secondary
    if ($io->copy_all_to_secondaryfile())
    {
      _error("Error from IO module copying datasets.", $io->errstr());
      return '';
    }

    # Close files
    $io->close_primaryfile();
    $io->close_secondaryfile();

    # Move temporary file to existing file
    unless (move_file($tempfile,$self->{file}))
    {
      _error("Error moving temporary file $tempfile to $self->{file}");
      return '';
    }
    
  } else {
    internal_error("Can't purge deleted datsets using the iotool helper");
  }
  1;
}

=head3 delete_dataset

  my $ds=$def->delete_dataset(-what => 'G/COMMANDS');

Deletes the dataset(s) matching the pattern.

As ever, some checks and caching are done, so this function may not
correspond to the exact behaviour of the io library.  No discrepancies
are known, however.

=cut

sub delete_dataset {
  my $self=shift;
  my %args=normalize_arghash(@_);

  if ($self->use_io_base()) {
    my $what=$args{WHAT} || '*';
    my $where=$args{WHERE} || '*';
    my $when=$args{WHEN} || -1;

    _debug("Deleting datasets matching $what:$where:$when");

    $self->clear_caches();

    #
    # using CFX5::IO::Base and so on
    #
    my $io=CFX5::IO::Base->new();
    if ($io->open_primaryfile($self->{file})) {
      _error("Error from IO module while opening $self->{file}:\n",
	     $io->errstr());
      return '';
    }

    my $rv=$io->delete_dataset($what, $where, $when);

    $io->close_primaryfile();

    if ($rv) {
      _error("Error from IO module while reading $what:$where:$when:\n", $io->errstr());
      return '';
    }
  } else {
    internal_error("Can't just read the header using the iotool helper");
  }
  1;
}

=head2 ACCESS MODE

Calls to get and set the access mode used by a particular instance.
This should not normally be used, but is useful for testing the modes
against each other.  The mode should only be changed before any calls
which access the definition file.

=head3 mode

  my $mode=$def->mode();
  $def->mode('iotool-helper');

Gets/sets the mode in use by the object in question.  The available
modes are:

=over

=item cfx5-io-base

Using the CFX5::IO::Base object.  This is the default.

=item iotool-helper

Using the external IOtool helper program.

=back

=cut

sub mode {
  my $self=shift;
  my $old=$self->{mode};
  if (@_) {
    $self->{mode}=$_[0];
  }
  $old;
}

=head3 use_io_base

  if ($def->use_io_base()) {
    # ...
  }

=cut

sub use_io_base {
  $_[0]->{mode} eq 'cfx5-io-base' ? 1 : '';
}

=head2 MESSAGE HANDLING

Using the CFX5::IO::Base message handler, we set up a message handler
of our own to simply call _error.

=cut

#
# code to pull in the XS IO library access stuff.  How do we do this?
# Well, on NT, we need to pull this in at compile time, so it's linked
# correctly, but on UNIX, we can't pull it in until runtime, as we
# don't know CFX5LIBDIR when the scripts are executed.  What fun, joy
# and excitement all this causes!  Rather than checking for NT, or the
# compiler, we check whether we can find it at compile time; if we
# can, we pull it in then.  Otherwise, we will have to do it later.
#
use vars qw($HaveXSCode);
use lib;
if (exists $ENV{CFX5_PERL_MODDIR}) {
  # manual override
  init_xs($ENV{CFX5_PERL_MODDIR});
} elsif (exists $ENV{CFX5LIBDIR} and -d "$ENV{CFX5LIBDIR}/CFX5") {
  init_xs($ENV{CFX5LIBDIR});
} else {
  #warn "Unable to find ANSYS CFX libraries at compile-time, delaying load";
}

sub init_xs {
  return if $HaveXSCode;

  my $libdir=shift;
  if (!defined $libdir) {
    $libdir=$Config{CFX5LIBDIR};
  }

  unless (defined $libdir) {
    internal_error("Unable to locate library directory for compiled Perl modules");
  }

  # we use lib, as it adds lots of useful things based on this name,
  # rather than simply the directory name.
  #warn "Loading XS code ...";
  eval {
    import lib ($libdir);
    require CFX5::IO::Base;
    $HaveXSCode=1;

    if ($^C) {
      # strip dynaloader from @ISA, we don't need it any more, and it
      # confuses the compiler
      @CFX5::IO::Base::ISA = grep { $_ ne 'DynaLoader' } @CFX5::IO::Base::ISA;
    }
  };
  if ($@) {
    # failed
    _abort("Failed to load CFX5::IO::Base:\n  $@");
  }

  CFX5::IO::Base->add_message_handler(sub { _error("Error reported by IO module:", @_); });
}

=head2 DATASET COPYING

This code does copying of datasets from one definition file to
another.  It is a hack for the beta, and should be removed before
shipping.

=head3 copy_datasets

  CFX5::DefFile::copy_dataset('file1.def' => 'file2.def',
			      ['G/COMMANDS','*',0]);

  $defsrc->CFX5::DefFile::copy_dataset($defdest,
			      ['G/COMMANDS','*',0]);


This function copies the named dataset(s) from the first file into the
second file.  If the named datasets do not exist, they are silently
skipped.  The return value is FALSE but not 0 if some error occurred,
or the count of datasets transferred (which may be 0).

The arguments may be either C<CFX5::DefFile> objects, or filenames.

=cut

sub copy_datasets {
  my $src=shift;
  my $dest=shift;

  my $srcf=$src;
  if ($src->isa('CFX5::DefFile')) {
    $srcf=$src->{file};
  }    
  my $destf=$dest;
  if ($dest->isa('CFX5::DefFile')) {
    $destf=$dest->{file};
  }
    
  init_xs();

  # first, open the files
  my $io=CFX5::IO::Base->new();
  return '' unless defined $io;
  if ($io->open_primaryfile($srcf)) {
    warn $io->errstr();
    return '';
  }
  if ($io->open_secondaryfile($destf)) {
    $io->close_primaryfile();
    warn $io->errstr();
    return '';
  }

  my $count;
  for my $dst (@_) {
    # we use the CFX5::IO::Base::iocntc routine 
    my ($what,$where,$when)=@$dst;
    $when=-1 if $when eq '*';

    # now expand any wildcards ...
    my @ds=$io->locate_primary_dataset($what,$where,$when);

    # ... and go through them one-by-one
    for my $ds (@ds) {
      _debug("Copying dataset", join(':',@$ds));
      unless ($io->copy_dataset_to_secondaryfile(@$ds)) {
	$count++;
      } else {
	# error
	_debug "Error!";
      }
    }
  }

  $io->close_secondaryfile();
  $io->close_primaryfile();

  $count;
}

=head2 BACKWARDS COMPATIBILITY

This section contains various routines used to enable
backwards-compatibility for definition files.

=head3 create_namemap_53

  @namemap=$def53->create_namemap_53();

This call generates the contents for a C<G/NAMEMAP> dataset from the
data in a 5.3 definition file.  If it cannot do this, it will signal
an error with _error and return an empty list.

=cut

# get a map entry for the only zone
sub create_namemap_53 {
  my $deffile=shift;

  #
  # read the boundary conditions
  #
  my @bcmap;
  {
    unless ($deffile->have_dataset(what => 'G/BCS')) {
      _error("Error creating namemap: G/BCS missing");
      return ();
    }
    my @bcs=$deffile->read_dataset(what => 'G/BCS')->data();

    for my $bc (@bcs) {
      unless ($deffile->have_dataset(what => "G/$bc")) {
	_error("Error creating namemap: Missing information for $bc");
	return ();
      }
      my $ds=$deffile->read_dataset(what => "G/$bc");

      my $uname=$ds->header('USERNAME');
      (my $nbc = $bc) =~ s!BC!BCP!;
      push @bcmap, [ $uname, $nbc, 'BOUNDARY', 'BCP' ];
    }
  }

  #
  # read the subdomain information
  #
  my @vpmap;
  if ($deffile->have_dataset(what => 'G/VPS')) {
    # it is not an error if this dataset is missing
    my @vps=$deffile->read_dataset(what => 'G/VPS')->data();

    for my $vp (@vps) {
      unless ($deffile->have_dataset(what => "G/$vp")) {
	_error("Error creating namemap: Missing information for $vp");
	return ();
      }
      my $ds=$deffile->read_dataset(what => "G/$vp");
      
      my $uname=$ds->header('USERNAME');
      push @vpmap, [ $uname, $vp, 'SUBDOMAIN', 'VP' ];
    }
  }

  #
  # now, we try to work out the name of the domain.  This is,
  # surprisingly, the hardest part.
  #
  my @znmap;
  {
    unless ($deffile->have_dataset(what => "G/CLBVL", where => 'ZN1')) {
      _error "Error creating namemap: G/CLBVL missing";
      return ();
    }
    my $ds=$deffile->read_dataset(what => "G/CLBVL", where => 'ZN1');

    # this dataset contains all subdomain names, and the overall domain
    # name.  I reckon the domain name is probably the final one in the
    # list, but to play safe, let's get rid of the names of any
    # subdomains.
    my @vls=$ds->data();
    my $name;
    if (@vpmap) {
      my @subs=map { $_->[0] } @vpmap;
      my %all=map { $_ => 1 } @vls;
      for my $s (@subs) {
	delete $all{$s};
      }
      my @name=keys %all;
      if (@name > 1) {
	_error "Error creating namemap: unable to find unique domain name from", join("; ", @name);
	return ();
      } elsif (!@name) {
	# we removed this one too; just put back the last one as a
	# guess!
	push @name, $vls[$#vls];
      }
      $name=$name[0];
    } else {
      # no subdomains, it should be easy
      if (@vls > 1) {
	_error("Error creating namemap: multiple volume names with no subdomain");
	return ();
      }
      $name=$vls[0];
    }
    push @znmap, [ $name, 'ZN1', 'DOMAIN', 'ZN' ];
  }

  my @namemap = map { 
    # translate any 5.3 names into 5.4 style, in the same way that
    # Build does
    $_->[0] =~ s![^A-Za-z0-9]! !g;
    # and flatten out the list
    @$_;
  } (@znmap, @bcmap, @vpmap);

  @namemap;
}

1;
