#! perl -w

=head1 NAME

cfx5mondata - run CFX Monitor Data Exporter

=cut

#!/bin/sh
#==============================================================================
# @(#) $Id$
#-------------------------------------------------------------------------------
##
#H Name:
##
## cfx5mondata
##
#H Purpose:
##
## Run the CFX Monitor Data Exporter.  Monitor data will be output in 
## Excel-compatible CSV (comma-separated values) format
##
#H Synopsis:
##
## cfx5mondata -res <file> | -dir <directory> | -mon <file>
##         [-showvars] [-nocoeffloops] [-lastvalueonly]
##         [-varlist <variables>] [-varrule <rule>]
##         [-out <file>] [-help] [-v]
##
## []  denotes an optional argument.
## |   separates mutually exclusive arguments.
## ... following an argument indicates that it may be repeated.
## <>  denotes that substitution of a suitable value is required. All other
##     arguments are keywords, some of which have a short form.
##
#H Arguments:
##
#A -def <file>
#A -res <file>
##     Retrieve solver monitor data from CFX Solver Results file <file>.
##
#A -dir <directory>
##     Retrieve solver monitor data from CFX Solver run directory <directory>.
##
#A -mon <file>
##     Retrieve solver monitor data from a monitor data text file <file>.
##
#A -output <file>
#A -out <file>
##     Send output to <file>.  If you omit this argument, output will be sent 
##     to the console.
##
#A -showvars
##     Instead of extracting variable data, simply output all monitor variables
##     found in the results file.
##
#A -firsttimestep <time step>
##     Allows monitor data to be output for a specific range of time steps
##     starting from the specified time step. The default is the first
##     timestep available in the monitor data.
##
#A -lasttimestep <time step>
##     Allows monitor data to be output for a specific range of time steps
##     ending at the specified time step. The default is the last
##     timestep available in the monitor data.
##
#A -lastvaluesonly
##     Instead of extracting variable data per timestep, locate the last valid
##     value for each variable and output in CSV format.
##
#A -nocoeffloops
##     Coefficient loop data, if present, should be omitted.  Only the last value
##     per timestep will be output.
##
#A -varlist <variable list>
##     Lists variables by name that should be selected for export.  If neither 
##     -varlist nor -varrule are specified, all variables will be selected.
##     Multiple variables should be separated by semi-colon, and quoted to allow for
##     shell parsing, ie:
##        -varlist "RESIDUAL,RMS,U-Mom;RESIDUAL,RMS,V-Mom"
##
#A -varrule <variable rule>
##     Selects variables that match Monitor Variable rule <variable rule>.  If 
##     neither -varlist nor -varrule are specified, all variables will be 
##     selected.
##     See $CFX5ROOT/etc/workspace-basic.mst for examples of Monitor Variable 
##     rules.  Example:
##        -varrule "CATEGORY = USER POINT"
##
#A -help
#A -h
##     Print this message.
##
#A -verbose
#A -v
##     Specifying this option may result in additional output being sent to 
##     the UNIX standard output file (normally the screen).
##
#U ****************************************************************************
#U *                                                                          *
#U *     The following features are supported only within CFX and are not     *
#U *     shown by the -help option when the command is run elsewhere.         *
#U *                                                                          *
#U ****************************************************************************
#U
#U -local
#U     Rather than using the central version of CFX-Post, assume that
#U     the current directory is the root of a locally-built version
#U     and run from that.
#U
#U -local-root <dir>
#U     Rather than using the central version of CFX-Post, assume that
#U     the specified directory <dir> is the root of a locally-built
#U     version and run from that.
#U
#U -noheader
#U     Omits header containing variable names from the output.
#U
#U -plotinfo
#U     If specified, the output is an XML file containing details of the
#U     default plots that would be produced by the CFX-Solver Manager for the 
#U     given monitor variables.
#U
#U -varinfo
#U     If specified, the output is an XML file containing details of the
#U     monitor variables, including names, display names and tree paths for
#U     for display.
#U
#
# before we do anything else which might use it, restore TMPDIR if it
# was changed by cfx5build.
#
if (exists $ENV{CFX_BUILD_ORIG_TMPDIR}) {
  if ($ENV{CFX_BUILD_ORIG_TMPDIR} eq "TMPDIR was not set") {
    delete $ENV{TMPDIR};
  } else {
    $ENV{TMPDIR}=$ENV{CFX_BUILD_ORIG_TMPDIR};
  }
  delete $ENV{CFX_BUILD_ORIG_TMPDIR};
}

# get the standard CFX-5 library directory
BEGIN {
  if ($0 =~ m!^([a-z]:)?[\\/]!i) {
    # it's an absolute path, use it as-is
    (my $nd=$0) =~ s!(perllib[\\/])?[^\\/]*$!!i;
    unshift @INC, "$nd/perllib";
  } else {
    # wrap this in an eval, and if it fails, pray ... for example,
    # this can fail on Windows if we're running off a share.
    eval {
      require FindBin;
      FindBin->import();
      unshift @INC, "$FindBin::Bin/perllib";
      my $dummy=$FindBin::Bin; # kill used only once warning
    };
    warn $@ if $@;
  }
  if (defined $ENV{CFX_LOCAL_PERLLIB}) {
     unshift @INC, $ENV{CFX_LOCAL_PERLLIB};
  }

}

use CFX5::Init;
CFX5::Init::init();

use vars qw($CVSVersion);
sub BEGIN {
  $CVSVersion='@(#) $Id$\n';
}

use strict;

use CFX5::Output qw(:all);
use CFX5::Config qw(%Config export_conf append_to_libpath prepend_to_libpath append_to_execpath prepend_to_execpath setconf);
use CFX5::PrintConfig;

use CFX5::CmdLine qw(:util parse_cmdline);

use CFX5::Help;

use CFX5::PathManip qw(join_file split_file fullpath basename dirname);
use CFX5::FileTests;
#use CFX5::FileOps qw(link_files copy_file_for_read move_file move_file_to_backup glob_suffix create_empty_file);
#use File::Path qw(rmtree);

use CFX5::ExitRoutines qw(:tidyup);

use CFX5::System qw(assert_can_window);

use CFX5::FrameServ;

use CFX5::Commands qw(do_cmd do_cmd_quiet handle_rv parse_rv get_cmd_output);

use CFX5::CCLI qw(export_parser_conf);
use CFX5::CUEI;
use CFX5::LIST;

CFX5::Config::read_config();

use vars qw($resfile $mondir $textfile $outfile $nocoeffloops $lastvaluesonly 
            $showvars $firsttimestep $lasttimestep $noheader $plotinfo $varinfo
            $varlist $varrule);

my @nonopt = parse_cmdline
  (
   \@ARGV,
   'ALLOW_NON_OPTION',
   'INCLUDE_STD',
   '-def+' => '-res',
   '-dir+' => sub {
     conf_datadir( \$mondir, "CFX Solver Run Directory %%", @_);
   },
   '-firsttimestep+' => \$firsttimestep,
   '-lasttimestep+' => \$lasttimestep,
   '-lastvaluesonly' => \$lastvaluesonly,
   '-local' => \$Config{CUE_ISLOCAL},
   '-local-root+' => sub {
     $Config{CUE_ISLOCAL}=1;
     conf_datadir(\$Config{CUE_ROOT}, "Local CUE root directory %%", @_);
   },
   '-mon+' => sub {
     conf_datafile( \$textfile, "Monitor Data text file %%", @_);
   },
   '-nocoeffloops' => \$nocoeffloops,
   '-noheader'=> \$noheader,
   '-output+'=> '-out',
   '-out+'=> \$outfile,
   '-res+' => sub {
     conf_datafile( \$resfile, "CFX-5 Results file %%", @_);
   },
   '-showvars' => \$showvars,
   '-plotinfo' => \$plotinfo,
   '-varinfo'  => \$varinfo,
   '-varlist+' => \$varlist,
   '-varrule+' => \$varrule,
  );

exit_if_error();

if (@nonopt) {
  for my $f ( @nonopt ) {
    CFX5::FileTests::datafile($f, "CFX-5 Results file $f")
        and $resfile = $f;
  }
}

exit_if_error();

#
# argument consistency checks
#
my $defcount = 0;

if( defined $resfile ) {
  $defcount++;
}
if( defined $textfile ) {
  $defcount++;
}
if( defined $mondir ) {
  $defcount++;
}

if( $defcount ne 1 ) {
  _error("You must supply a single results file, run directory or monitor data text file." 
      . CFX5::Help::usage_msg_once());
}

if ($lastvaluesonly and ($firsttimestep or $lasttimestep)) {
  _error("Incompatible options specified: Neither -firsttimestep nor -lasttimestep option can be used with -lastvaluesonly");
}

my $varOutputOptionsSet = ( $firsttimestep or $lasttimestep or $lastvaluesonly or $nocoeffloops or $varlist or $varrule or $noheader );

if ( $plotinfo and ($showvars or $varOutputOptionsSet) ) {
  _error("Incompatible options specified: The -plotinfo option is not compatible with any options relating to variable selection, or the -showvars option.");
}

if ( $varinfo and ($showvars or $varOutputOptionsSet) ) {
  _error("Incompatible options specified: The -varinfo option is not compatible with any options relating to variable selection, or the -showvars option.");
}

if ( $varinfo and $plotinfo ) {
  _error("Incompatible options specified: The -varinfo option is not compatible with the -plotinfo option.");
} 

exit_if_error();

#
# export configuration
#
CFX5::CUEI::export_post_conf();

export_conf(qw(CFX_DATA_DIR CFX5ROOT CFX_CMD_DIR
               CFX_TOOLS_ROOT CFX_OS CFX5OS
               LM_LICENSE_FILE CFX_LICENSE_FILE
               CUE_DIR CFX5PERL
              ));

exit_if_error();

CFX5::PrintConfig::show_vars_by_verbosity();

#
# Create command line
#
my @args;

if( defined $resfile ) {
  push @args, '-res' => $resfile;
}
if( defined $mondir ) {
  push @args, '-dir' => $mondir;
}
if( defined $textfile ) {
  push @args, '-mon' => $textfile;
}
if (defined $outfile) {
  push @args, '-out' => $outfile;
}
if (defined $showvars) {
  push @args, '-showvars';
}
if (defined $plotinfo) {
  push @args, '-plotinfo';
}
if (defined $varinfo) {
  push @args, '-varinfo';
}
if( defined $lastvaluesonly ) {
  push @args, '-lastvaluesonly';
}
if( defined $firsttimestep ) {
  push @args, '-firsttimestep' => $firsttimestep;
}
if( defined $lasttimestep ) {
  push @args, '-lasttimestep' => $lasttimestep;
}
if( defined $nocoeffloops) {
  push @args, '-nocoeffloops';
}
if( defined $noheader) {
  push @args, '-noheader';
}
if( defined $varlist ) {
  push @args, -varlist => $varlist;
}
if (defined $varrule) {
  push @args, -varrule => $varrule;
}

CFX5::FileTests::execfile($Config{"CUE_MONDATA_EXE"},
                          "Monitor Data Exporter executable ".$Config{"CUE_MONDATA_EXE"});

exit_if_error();

# Windows: Process arguments for use with the command shell
if ($Config{windows_nt})
{
  @args = map CFX5::Commands::escape_argument($_), @args;
}

my @runwith;
if (defined $Config{CFX_RUN_WITH}) {
  @runwith = $Config{CFX_RUN_WITH};
}

my $rv=handle_rv(do_cmd(@runwith, $Config{"CUE_MONDATA_EXE"}, @args));
_warn($Config{"CUE_MONDATA_EXE"} . " exited with return code $rv")
  if ($rv);
exit($rv);

