# -*-Perl-*- 
# 
# $Id: ExecTools.pm,v 1.4 1997/04/24 10:06:21 dn1 Exp $
#
# $Log: ExecTools.pm,v $
# Revision 1.4  1997/04/24  10:06:21  dn1
# Added copyrightt
#
# Revision 1.3  1996/04/09  16:07:19  dmh
# Removed timings from backticks.
#
# Revision 1.2  1996/04/03  17:53:01  badger
# Minor changes and fiddles
#
# Revision 1.1  1996/04/03  16:59:26  dmh
# Initial revision
#
#
#
#######################################################################
# This software has been created by Genome Research Limited (GRL).    # 
# GRL hereby grants permission to use, copy, modify and distribute    # 
# this software and its documentation for non-commercial purposes     # 
# without fee at the user's own risk on the basis set out below.      #
# GRL neither undertakes nor accepts any duty whether contractual or  # 
# otherwise in connection with the software, its use or the use of    # 
# any derivative, and makes no representations or warranties, express #
# or implied, concerning the software, its suitability, fitness for   #
# a particular purpose or non-infringement.                           #
# In no event shall the authors of the software or GRL be responsible # 
# or liable for any loss or damage whatsoever arising in any way      # 
# directly or indirectly out of the use of this software or its       # 
# derivatives, even if advised of the possibility of such damage.     #
# Our software can be freely distributed under the conditions set out # 
# above, and must contain this copyright notice.                      #
#######################################################################

package ExecTools;

##########################################
#
# Construct...
#
##########################################

sub new { 

    my $type=shift;

    my $self={};
    $type->setDefaults($self);

    my %args = @_;
    my $realopt;
    foreach (keys%args) {
	($realopt=$_)=~s/^\-//;
        $self->{$realopt} = $args{$_};
    }

    # If logfile specified in construction
    # log messages get send to the file only.
    if (defined($self->{'logfile'}) && ! defined($self->{'echo'})) {
        $self->{'echo'} = 2;
    }

    bless $self, $type;

}

sub setDefaults {

    my ($type, $param_ref)=@_;

    $param_ref->{'echo'} = 4;         

}


##########################################
#
# Methods
#
##########################################


####################################
# 
# $err = &logEntry ($text, $logfile, $echo)
#
# Log event/error messages.
# Save to file if required.
# Display text according to code:
#
#  0 - No output
#  1 - To file and STDOUT
#  2 - Just to file 
#  4 - Just to STDOUT
#
#
# Returns non-zero on exit.
#
####################################
sub logEntry {

    my $type =shift;
    my %args=@_;

    my $logfile=$args{'-file'} || $type->{'logfile'};
    my $echo=$args{'-echo'} || $type->{'echo'};
    my $text=$args{'-text'} || return 1;

    chomp($text);

    # Check for OK file name
    if ( ! defined($logfile) && ($echo == 1 || $echo == 2)) {
	warn "No filename specified: Echo to stdout only";
	$echo = 4;
    }

    # Check display code
    if ($echo !~ /^\d$/) {
	warn "No display(echo) code supplied";
	$echo = 1;
    }

    # Return if no output set
    if ($echo == 0) {
	return;
    }

    # Open log file
    if ( $echo == 1 || $echo == 2 ) {

	if ( -e "$logfile" ) {
	    open (LOG, ">>$logfile")
		|| warn "&logEntry in gapAssemble couldn't create log file"
		    && return 1;
	} else {
	    open (LOG, ">$logfile")
		|| warn "&logEntry in gapAssemble couldn't create log file"
		    && return 1;
	}

	print LOG scalar(localtime), ":  $text\n";
	close (LOG);
    }
	

    # Print to STDOUT
    if ($echo == 1 || $echo == 4 ) {
	print STDOUT "$text\n";
    }

    0;

}




############################################
#  $err = execute(-command => $exec, 
# 		-check => \@files, 
# 		-output => \$output_str, 
# 		-messages => \$messages);
#  
# Execute $exec. 
# Put the output in $$output_str
# Check that all @$files were found afterwards
# Log all messages to $$messages_ref
# Return error code 1 = Fail, 0 = Success
# 
############################################
sub execute {

    my $type =shift;
    my %args=@_;

    my $exec=$args{'-command'} || return 1;
    my $files_ref=$args{'-check'};
    my $output_ref=$args{'-output'};
    my $messages_ref=$args{'-messages'};
    my $log=$args{'-log'};


    my $messages = "Running: $exec\n";
    my $err = 0;
    
    # Run command
    my $output = `$exec 2>&1`;
	
    # Check OK exit
    if ($?!=0) {
	$messages .= "Execution failed: \"$exec\": fatal exit code\n";
	$$messages_ref = $messages;
	$err++;
    } else {
	$messages .= "Execution sucessful.";
    }

    # Check for required files
    if (defined($files_ref)) {
        foreach (@{$files_ref}) {
	    unless (-s "$_") {
		$messages .= "Output file: \"$_\": not found\n";
		$err++;
	    }
	}
    } 

    # Log the messages
    if ($log) {
	$type->logEntry(-file => $type->{'logfile'},
			-text => "$messages\n$output");
    }

    # Pass back messages if asked for
    if (defined($messages_ref)) { 
	$$messages_ref=$messages;
    }

    # Pass back command output if asked for
    if (defined($output_ref)) { 
	$$output_ref=$output;
    }

    $err;

}

1;
