=head1 NAME

CFX5::Files::Def - module for handling def files

=head1 DESCRIPTION

The CFX5::Files::Def class provides def-file-specific code for
CFX5::AnyFile.

=cut

package CFX5::Files::Def;

use strict;

use CFX5::PkgLoader qw(cfx5_require);

# multiple inheritance.  Is this evil?  Probably.
use CFX5::Files::Any;
use CFX5::DefFile;
use vars qw(@ISA);
push @ISA, qw(CFX5::Files::Any CFX5::DefFile);

sub init {
  my $self=shift;

  $self->SUPER::init(@_)
    or return '';

  # CFX5::DefFile uses initialize rather than init, which is handy ...
  $self->initialize($self->file());

  1;
}

sub description {
  "ANSYS CFX Solver Input File";
}

=head2 DATASET STUFF

=head3 locate_dataset

  @dslist=$file->locate_dataset($what, $where, $when);

Returns a list of datasets in the file.  TODO: make this return a list
of IIIndex-like objects.

=cut

sub locate_dataset {
  my $self=shift;

  my $what=shift;
  my $where=shift;
  my $when=shift;

  # allow '*' in when
  if ($when eq '*') {
    $when=-1;
  }

  return $self->have_dataset(-what => $what, -where => $where, -when => $when);
}

=head2 CCL STUFF

=head3 getcclds

Returns the CFX5::DefFile::Dataset object representing the live CCL
dataset for this file.  Mostly for internal use.

=cut

sub getcclds {
  my $self=shift;
  my $dsName=shift; 
  
  unless (defined $dsName) {
    $dsName='G/COMMANDS';
  }
  
  #
  # get a list of CCL datasets in the file
  #
  my @cclds = $self->have_dataset(-WHAT => $dsName);
  if (@cclds == 0) {
    # no CCL data
    return 'No CFX Command Language dataset';
  }

  # do we have one at 0?
  my @cclzero = $self->have_dataset(-WHAT => $dsName,
                                    -WHEN => 0);
  if (@cclzero > 1) {
    internal_error("Found", scalar(@cclzero),
                   "$dsName datasets at WHEN=0:", 
                   join("\n",'',map { $_->short_name(); } @cclzero));
  }

  my $cclds;
  if (@cclzero) {
    # got one at zero
    $cclds=$cclzero[0];
  } else {
    # no, take the max
    my $max=0;
    for my $ds (@cclds) {
      if ($ds->[2] >= $max) {
        $cclds = $ds;
        $max = $ds->[2];
      }
    }
  }

  my $ds = $self->read_dataset(-WHAT  => $cclds->[0],
                               -WHERE => $cclds->[1],
                               -WHEN  => $cclds->[2]);

  return $ds;
}

=head3 extract_ccl

=cut

sub extract_ccl {
  my $self=shift;

  my $ds=$self->getcclds();

  unless (defined $ds) {
    _error("The", $self->description(), $self->file(), "does not contain any Command Language data.");
    return ();
  }

  my @ccl=$ds->data();
  return @ccl;
}


1;
