#!/bin/sh
########################################################
# This shell prepares the files 'fort.80' and 'fort.13'
# required by the "spec.job" arguments.
# (see readme-spectr)
########################################################
# The required argument to this program is the name of
# a parameter file (an example is spec.job) 
# This parameter file should be in a working directory, 
# where the required files are copied.
########################################################

# Verify the argument: a file with arguments
if test -z "$1" ; then
    echo "Usage: $0 spec_job_file"
    exit 1
fi
file="$1"
if test -r $file ; then
    nl=`wc -l < $file`	# Number of lines
else
    echo "****Bad file: $file"
    exit 1
fi
work_dir=`dirname $file`
job=`basename $file`

if test "$dir" = "."; then
    echo "++++parameter file should be in a working directory"
    echo "    (e.g. /tmp/BT2/$job)"
    exit 1
fi

# Find the files required in "fort.13"
# This awk script finds the limits wsmin and wsmax
#

ls [0-9]*  | gawk -F, 'BEGIN{fe = "/dev/stderr";
 while(getline < "'$file'"){
  for(i=1; i<=NF; i++){ gsub(/ /, "", $i);
   if(split($i, a, "=")==2) p[a[1]]=a[2]+0}}
  print "#====wsmin,wsmax:",p["wsmin"] "," p["wsmax"] > fe;
 }
 {split($0,a,"-"); wmin = a[1]+0; wmax = a[2]+0;
  #print "#....wmin,wmax:",wmin "," wmax > fe;
  if(p["wsmax"]<wmin) next; if(p["wsmin"]>wmax) next; print}' \
> $work_dir/files.lis
files=`cat $work_dir/files.lis`
f13=`gawk -F- 'NR==1{p1=$1}{p2=$2}END{print p1 "-" p2}' $work_dir/files.lis`
f13="$f13-BT2.txt"
echo "....Transition files required: $files"
echo "....Final transition file   => $f13"

# Remove the soft links
test -h $work_dir/fort.80 && rm -f $work_dir/fort.80
test -h $work_dir/fort.13 && rm -f $work_dir/fort.13
test -h $work_dir/spec.job && rm -f $work_dir/spec.job

# Copy the required files -- however only if not yet there
if test -r $work_dir/levels.dat ; then
    echo "....File $work_dir/levels.dat already there:"
    ls -l $work_dir/levels.dat
else
    echo "....Copying levels.dat"
    bzcat levels.dat.bz2 > $work_dir/levels.dat 
fi
if test -r $work_dir/$f13; then
    echo "....File $work_dir/$f13 already there:"
    ls -l $work_dir/$f13
else
    echo "....Creating $work_dir/$f13"
    touch $work_dir/$f13
    for f in $files ; do echo ....$f; bzcat $f >> $work_dir/$f13; done
fi

# Create soft links for the fort.xx files.
test "$file" = "$work_dir/spec.job" || (cd $work_dir; ln -s "$job" spec.job)
(cd $work_dir; ln -s levels.dat fort.80; ln -s $f13 fort.13 )

# Now just run the program there
echo "====Files now ready in $work_dir"
ls -l $work_dir
