#
# $Date: 2006/10/31 13:51:01 $
# $Id: Result.pm,v 1.2 2006/10/31 13:51:01 gelpi Exp $
# $Revision: 1.2 $
#
package CMIP::Result;

=head1 NAME

CMIP::Result - Object to store CMIP calculation results

=head1 SYNOPSIS

use CMIP::Result;

$result=CMIP::Result->new($files);

=head1 METHODS

$hashref=$result->keywords;

$value=$result->getKeyword($key);

$string=$result->asString;

$string=$result->getFileName($key);

=cut
my $DEFAULT_FILES = {
 i => 'param',
 vdw => 'vdwprm',
 hs => 'hostpdb',
 epr => 'energies',
 grdin => 'gridin',
 o =>'output',
 grdout => 'gridout',
 output => 'outpdb',
 grdb => 'grdB',
 rst => 'restart',
 pr => 'probpdb',
 grad => 'gradient',
 gds =>  'gdesolv',
 srf => 'surface',
 eps => 'outeps',
 ats => 'ats',
 eps2 => 'outeps2',
 fr => 'outfrac',
 byat => 'byatom',
 atsgrd => 'atsgrd',
 l => 'log',
 cube => 'cube'};

1;
sub new {
	my ($class, $files) = @_;
	my $self={};
	$self->{files}=$files;
	$self->{output}= `cat $files->{o}` if ($files->{o});
	$self->{stdout}= `cat $files->{stdout}` if ($files->{stdout});
	$self->{stderr}= `cat $files->{stderr}` if ($files->{stderr});
	if (!$self->{stderr} && $files->{l}) {
		open (LOG, $files->{l});
		while (<LOG>) {
			chomp;
			my ($k, $v) = split /=/;
			next if (!$k);
			$k =~ s/ //g;
			$v =~ s/ //g;
			$self->{keywords}->{$k}=$v;
			if ($k =~ /title/) {
				$_=<LOG>;
				while (!/title/) {
					$self->{keywords}->{$k}.=$_;
					$_=<LOG>;
				}

				$self->{keywords}->{$k} =~ s/\n//g;
				$self->{keywords}->{$k} =~ s/ *$//g;
			}
		}
		close LOG;
	} else {
		$self->{errstr}=`tail -1 $files->{o}`;
	}
	bless $self;
};

sub keywords {
	my $self = shift;
	return $self->{keywords}
}

sub getKeyword {
	my ($self, $k) = @_;
	return $self->{keywords}->{$k}
}

sub getFileName {
	my ($self, $key) = @_;
	if ($self->{files}->{$key}) {
		return $self->{files}->{$key}
	} else {
		return $DEFAULT_FILES->{$key}
	}
}

sub getFileContents {
	my ($self, $key) = @_;
	return _getFile($self->{files}->{$key});
}

sub asString {
	my $self = shift;
	my $txt="";
	foreach my $k (sort keys %{$self->{keywords}}) {
		$txt .= "$k = ".$self->{keywords}->{$k}."\n";
	}
	return $txt
}

sub _getFile {
	my $fn =shift;
	open INPUT, $fn;
	print $fn;
	my $file;
	read INPUT, $file, (stat INPUT)[7];
	close INPUT;
	return $file
}
