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

=head1 NAME

CMIP::InputParams - Object to run prepare input parameters for CMIP jobs

=head1 SYNOPSIS

$inputP = CMIP::InputParams->new($title, $grid, [$grid0]);

=head1 METHODS

$hashref=$inputP->keywords;

$string=$inputP->asParamString;

$inputP->addKeyword (key1=>value1, key2=>value2, ....);

$inputP->delKeyword (key);

$inputP->grid($grid);

$inputP->grid0($grid);

=cut
use CMIP::Grid;
use strict;
1;

sub new {
	my ($class, $title, $gr, $gr0) = @_;
	my $self = {
		title => $title, 
		grid => $gr, 
		keywords => {}
		};
	if ($gr0) {
		$self->{grid0} = $gr0;
		$self->{keywords}->{PBFOCUS} = 1;
	}	
	$self->{keywords}->{WRITELOG} = 1;
	bless $self
}

sub loadFromInput { ## provisional
	my ($class, $fname) = @_;
	open INPUT, $fname || die "file $fname not found";
	my %KEYS;
	my $title =<INPUT>;
	while (<INPUT>) {
		chomp;
		next if /&/;
		foreach my $prm (split / *, */) {
			my ($k, $v) = split / *= */,$prm;
			$k=~s/ //g;
			$KEYS{uc($k)}=$v;
		}
	}
	close INPUT;
	my $grid= CMIP::Grid->new();
	my $grid0= CMIP::Grid->new();
	$grid->readGrid($KEYS{READGRID}) if $KEYS{READGRID};
	$grid->int($KEYS{INTX},$KEYS{INTY},$KEYS{INTZ});
	$grid->cen($KEYS{CENX},$KEYS{CENY},$KEYS{CENZ});	
	$grid->dim($KEYS{DIMX},$KEYS{DIMY},$KEYS{DIMZ});
	if ($KEYS{PBFOCUS}) {
		$grid0->readGrid($KEYS{READGRID0}) if $KEYS{READGRID0};
		$grid0->int($KEYS{INTX0},$KEYS{INTY0},$KEYS{INTZ0});
		$grid0->cen($KEYS{CENX0},$KEYS{CENY0},$KEYS{CENZ0});	
		$grid0->dim($KEYS{DIMX0},$KEYS{DIMY0},$KEYS{DIMZ0});
	}
	my $inp = CMIP::InputParams->new($title,$grid,$grid0);
	foreach my $k (keys(%KEYS)) {
		$inp->addKeyword($k, $KEYS{$k});
	}
	return $inp
}


sub grid {
	my ($self, $gr) = @_;
	$self->{grid} = $gr if $gr;
	return $self->{grid}
}

sub grid0 {
	my ($self, $gr) = @_;
	$self->{grid0} = $gr if $gr;
	$self->{keywords}->{PBFOCUS} = 1;	
	return $self->{grid0}
}

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

sub asParamString {
	my $self = shift;
	my $out = 
"$self->{title}
 &cntrl
";
	$out .= "  $_ = $self->{keywords}->{$_}, \n" for keys(%{$self->keywords});
	$out .= $self->{grid0}->asParamString(1)."\n" if $self->keywords->{PBFOCUS};
	$out .= $self->{grid}->asParamString;
 	$out .= "&end\n";
	return $out
}

sub addKeyword {
	my ($self, %KEYW) = @_;
	foreach my $k (keys %KEYW) {
		$self ->{keywords}->{$k} = $KEYW{$k};
	}
	return $self
}

sub delKeyword {
	my ($self, $key) = @_;
	undef $self->{$key};
	return $self
}

