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

=head1 NAME

CMIP::Run - Object to run CMIP jobs

=head1 SYNOPSIS

use CMIP::Run;
use CMIP::InputParameters;

$cmipRun = CMIP::Run->new($inputParameters);

=head1 METHODS

$value=$cmipRun->type('direct'|'batch');

$cmipRun->addFile(id1=>file1, id2=>file2,...);

$cmipRun->delFile(id); 

$hashref = $cmipRun->files;

$resultref = $cmipRun->execute($queue);

$cmipRun->rmTmpDir;

=cut

use CMIP::Local;
use CMIP::Result;
use strict;
1;

sub new {
	my ($class, $inputP) = @_;
	my $workdir=`pwd`;
	chomp $workdir;
	my $self = {
		workdir => $workdir,
		param => $inputP,
		type => 'direct',
		files => {'vdw' => $CMIP::Local::VDWPRM},
		queue => '',
		exefile => ''
		};
	bless $self;
}

sub rmTmpDir {
	my $self = shift;
	`rm -rf $self->{tmpdir}`;
}
	
sub type {
	my ($self, $type) = @_;
	$self->{type} = $type if $type;
	return $self->{type}
}

sub exeFile {
	my ($self, $file) = @_;
	$self->{'exefile'} = $file if $file;
	return $self->{'exefile'}
}

sub addFile {
	my ($self, %FILES)  = @_;
	foreach my $k (keys %FILES ) {
		$self->{files}->{$k} = $FILES{$k};
	}
	return $self;
}

sub delFile {
	my ($self, $file) = @_;
	undef $self->{files}->{$file};
	return $self;
}

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

sub execute {
	my ($self, $queue) = @_;
	my $job = CMIP::Local::createTMP;
	my $tmpdir = $CMIP::Local::TMPDIR."/$job";
	$self->{tmpdir}=$tmpdir;
	if (!$self->{files}->{i}) {
		open TMPPAR, ">$tmpdir/param" || die "Error: open $tmpdir/param";
#		print "$tmpdir/param";
		print TMPPAR $self->{param}->asParamString;
		close TMPPAR;
		if ($self->{exefile}) {
			$self->{cmd} = "$self->{exefile} -i $tmpdir/param";
		} else {
			$self->{cmd} = "$CMIP::Local::CMIP -i $tmpdir/param";
		}
	}
	$self->addFile ("o"=> $tmpdir."/cmip.out") if !$self->files->{o};
	$self->addFile ("l" => $tmpdir."/cmip.log") if !$self->files->{l};
	if ($self->{type} eq 'direct') {
		$self->addFile ("stderr" => $tmpdir."/stderr.log");
		$self->addFile ("stdout" => $tmpdir."/stdout.log");
	}
	$self->{cmd} .= " -$_ ".$self->files->{$_} for keys %{$self->files};

	open CSH, ">$tmpdir/run.csh" || die "Error open $tmpdir/run.csh";
	print CSH qq(
#!/bin/tcsh -f
hostname
cd $self->{workdir}
$self->{cmd}
#rm -rf $tmpdir
);
	close CSH;
	if ($self->{type} eq 'batch') {
		my $QUEUE;
		($QUEUE = $self->{queue}) || ($QUEUE = $CMIP::Local::QUEUEDEFAULT);
		return `$CMIP::Local::QSUB -q $QUEUE $tmpdir/run.csh`;
	} else {
		system("/bin/csh $tmpdir/run.csh 1>".$self->{files}->{stdout}." 2>".$self->{files}->{stderr});
		return CMIP::Result->new ($self->{files});
	}
}
		
