#!/bin/sh

rm -f mplotr/vkmh.print
rm -f mplotr/S111std.print
rm -f mplotr/S112std.print
rm -f mplotr/S121std.print
rm -f mplotr/S122std.print

if [ ! -f mplotf/print_vkmh_bobo.mplotf ]; then
echo "
 * warning * In Script `basename $0`
             File \"mplotf/print_vkmh_bobo.mplotf\" is missing
             Shall script `basename $0` create the file for you (y/n)?
"
read input
 if [ "$input" = "y" ]; then
  mkdir -p mplotf
echo "
##
##      Input data for program MPLOT
##
  ilaser= 6 iscren= 0

  filt std  100  S111  S111std  lsa_111.pn
  filt std  100  S112  S112std  lsa_112.pn
  filt std  100  S121  S121std  lsa_121.pn
  filt std  100  S122  S122std  lsa_122.pn

##
## Write sliding std-values to files
## ---------------------------------

  pryfil \"mplotr/vkmh.print\"
  print variable vkmh

  pryfil \"mplotr/S111std.print\"
  print variable S111std

  pryfil \"mplotr/S112std.print\"
  print variable S112std

  pryfil \"mplotr/S121std.print\"
  print variable S121std

  pryfil \"mplotr/S122std.print\"
  print variable S122std" > mplotf/print_vkmh_bobo.mplotf
 else
  exit 1
 fi
fi

mplot -no_addarg -no_interactive -use_MPfile  mplotf/print_vkmh_bobo.mplotf  $1 > /dev/null
if [ $? -ne 0 ]; then
echo "
 ***ERROR*** In Script `basename $0`
             Exit status from program MPLOT not equal 0'
             Please open file `basename $0` and remove
             the redirection of standard output to /dev/null
"
 exit 1
fi

nlines=`awk 'END {print NR}' mplotr/S111std.print`
if [ $? -ne 0 ]; then nlines=0; fi

if [ $nlines -lt 15 ]; then
 echo "$1	no results was found"
 exit 1
fi

# echo -n "$1	"
exec octave -q <<+

load mplotr/vkmh.print;         % vkmh  (:,1)= time;       vkmh  (:,2)= speed
load mplotr/S111std.print       % S11std(:,1)= lsa_11.pn;  S11std(:,2)= S11std
load mplotr/S112std.print       % S12std(:,1)= lsa_12.pn;  S12std(:,2)= S12std
load mplotr/S121std.print       % S11std(:,1)= lsa_11.pn;  S11std(:,2)= S11std
load mplotr/S122std.print       % S12std(:,1)= lsa_12.pn;  S12std(:,2)= S12std


for i= length(vkmh):-1:1
 if (S111std(i,2) > 2.5e3 ); break; end
 if (i <= 1); error('Cannot find level 2.5[kN]'); end
end
S111crit= vkmh(i,2);

for i= length(vkmh):-1:1
 if (S112std(i,2) > 2.5e3 ); break; end
 if (i <= 1); error('Cannot find level 2.5[kN]'); end
end
S112crit= vkmh(i,2);

for i= length(vkmh):-1:1
 if (S121std(i,2) > 2.5e3 ); break; end
 if (i <= 1); error('Cannot find level 2.5[kN]'); end
end
S121crit= vkmh(i,2);

for i= length(vkmh):-1:1
 if (S122std(i,2) > 2.5e3 ); break; end
 if (i <= 1); error('Cannot find level 2.5[kN]'); end
end
S122crit= vkmh(i,2);


%printf('%f %f %f %f\n', S111crit,S112crit,S121crit,S122crit)
printf('%f\n', min( [S111crit,S112crit,S121crit,S122crit] ))
+
