#!/bin/bash
#
# addlevel
# - add a level to an uvspec atmosphere_file or mol_file at the given altitude 
# - usage: addlevel.sh < atmosphere_file | mol_file > < z[km] >

if test -z "$2"; then
    echo Usage: addlevel \<atmosphere_file\|mol_file\> \<z1[km]\> \<z2[km]\> \<...\>
    exit
fi

# test if file is mol_file or atmosphere_file
if [ `gawk '!/#/' $1 | head -n 1 | gawk '{print NF}'` -eq 2 ]; then
  file_type="mol"
else
  file_type="atm"
fi

# write command line arguments to temporary file
echo "$@" > tmp00005.dat

#echo ... saving header
gawk '/#/' $1 > tmp00000.dat

#echo ... sorting file
if [ "${file_type}" == "mol" ]; then
  gawk '!/#/' $1 | gawk '{printf("%11.3f %.6e\n",$1,$2)}' | sort -n > tmp00001.dat
else
  gawk '!/#/' $1 | gawk '{printf("%11.3f%12.5f%12.3f %.6e %.6e %.6e %.6e %.6e %.6e\n",$1,$2,$3,$4,$5,$6,$7,$8,$9)}' | sort -n > tmp00001.dat
fi

#echo ... generating new altitudes
gawk '!/#/{print $1}' $1 > tmp00002.dat
gawk '{for (i=2;i<=NF;i++) print $i}' tmp00005.dat >> tmp00002.dat
cat tmp00002.dat | gawk '{n[$1+0]++};END{for (i in n) printf "%11.3f\n", i}' | sort -nr > tmp00003.dat

#echo ... interpolating $1 to new altitudes
if [ "${file_type}" == "mol" ]; then 
  ../bin/spline -x tmp00003.dat -l -q tmp00001.dat | gawk '{printf("%11.3f %.6e\n",$1,$2)}' > tmp00004.dat
else 
  ../bin/spline -x tmp00003.dat -l -q tmp00001.dat | gawk '{printf("%11.3f%12.5f%12.3f %.6e %.6e %.6e %.6e %.6e %.6e\n",$1,$2,$3,$4,$5,$6,$7,$8,$9)}' > tmp00004.dat
fi

cat tmp00000.dat tmp00004.dat

# echo ... clean up
#rm -f tmp00000.dat tmp00001.dat tmp00002.dat tmp00003.dat tmp00004.dat tmp00005.dat 
