#!/bin/csh -f

# Wrapper script to interface between Cerius2 MesoDyn interface
# script and the MesoDynRun script.

# This version for SGI machines.

unalias rm
unalias mv
unalias cat
unalias mkdir

set JOB_NAME = $1
set JOB_TYPE = $2

source $3
setenv LM_LICENSE_FILE $4

# Job type can be "Run", "Restart" or "Collect"

set PARAMETER_FILE = "$1.MesoDyn_par"
set CONTROL_FILE = "$1.MesoDyn_con"
set OUTPUT_FILE = "$1.MesoDyn_out"
if ( $JOB_TYPE == "Collect" )  set OUTPUT_FILE = "$1.MesoDyn_coll"
set STAT_FILE = "$1.MesoDyn_stat"
set STAT_SAVE = "$1.MesoDyn_stat_save"
set RESTART_FILE = "$1.MesoDyn_rst"
set MASK_FILE = "$1.mask.MesoDyn_ascii"
set LOG_FILE = "$1.MesoDyn_log"
set THER_FILE = "$1.MesoDyn_ther"
set ANI_FILE = "$1.MesoDyn_ani"

if  ( -r $PARAMETER_FILE ) then
else
  echo "Can not open parameter file "$PARAMETER_FILE
  exit 1
endif

# Loop through the topology file.

set TOPO=`awk '/topology_file/ {printf $2}' $PARAMETER_FILE`

if ( -r $TOPO ) then
  set FIRST = 1
  set noglob
  foreach  Line ( `cat $TOPO |awk  '{print $4"="$5}' ` ) 

# On SGI systems, the node will not be named, but we don't actually
# need the name.

    set noglob
    set Node = `echo $Line | cut -d'=' -f1`
    set Path = `echo $Line | cut -d'=' -f2`

# Ensure that directories do exist for each of the nodes.

    if ( $JOB_TYPE == "Run" )  then
      unset noglob
      if ( -e $Path )  then
        rm -rf $Path/$JOB_NAME.* >&! /dev/null
      else
        mkdir $Path
      endif
      set noglob
    endif

# Ensure that the mask file exists in the output directory for the
# first node.

    if ( $FIRST )  then
      if ( -e $MASK_FILE )  then
        cp $MASK_FILE $Path/$MASK_FILE
      endif
      set FIRST = 0
    endif
  end

  if ( $JOB_TYPE == "Run" )  then

# Clear out any possible old versions of various output files.

    foreach File ( $OUTPUT_FILE $STAT_FILE $RESTART_FILE $LOG_FILE $THER_FILE $ANI_FILE)
      if ( -e $File )  rm $File
    end
  endif

# Start the real MesoDyn run script.

  /bin/sh $MESODYN_HOME/MesoDynRun $PARAMETER_FILE $CONTROL_FILE >>&!  $OUTPUT_FILE

  if ( $JOB_TYPE == "Restart" )  then

# Append the new restart data to the saved version, and move it back.

    cat $STAT_FILE >>! $STAT_SAVE
    mv $STAT_SAVE $STAT_FILE
  endif

else
  echo "Topology file specified not found"
  exit 1
endif
