#!/bin/tcsh

# Solution for BTM Lab 09, exercise 2
# author: Ronni Grapenthin

# We start with the bonus exercise: test for the existence of an argument, i.e. give an
# error if no argument is given (or too many
if($# < 1 || $# > 2) then
   # echo the usage string, basename strips all possible pathname information
   # and hence makes the usage string look nicer. The name under which a script
   # has been called is always $0.
   echo "USAGE: `basename $0` FILE.pfiles [output-directory]"

   # exit the script since there was an error.
   exit
endif

## PREPARING OUTPUT REDIRECTION TO STATION_NAME.llh:
#----------------------------------------------------

# save the input file to a local variable so we know what we're 
# working with ($1, $2 are easily mixed up). 
set file=$1

# the format of a pfiles file is STATION_NAME.pfiles; we can get the station name
# using basename in a subshell; we will use this later to create the output file.
set sta_name=`basename $file .pfiles`

# The output file should end up in the same directory as the input file. You can 
# extract the path or directory name of the input file using dirname. 
set sta_path=`dirname $file`

# create the output file ${sta_path}/${sta_name}.llh
set output = ${sta_path}/${sta_name}.llh

# If I want to allow for a different output directory this is how I could do this.
# I define that an alternate output directory can be given as 2nd command line argument
# and is therefore referenced using $2. All we have to change from the above assignment
# for 'output' is replace ${sta_path} by $2 ... one line of code adds a lot of 
# functionality and comfort to this script.
if ($# == 2 )  set output="$2/${sta_name}.llh"

# Now we're giving some output to the user, mainly for them to check 
# whether everything works as they assumed it would.
echo "Station:  $sta_name"
echo "In file:  $file"
echo "Out file: $output"

# Finally we're doing the actual work; selecting time, lon,lat,height from the .pfiles
# file using awk and redirecting the output into STA_NAME.llh which might be anywhere
# on the file system.
awk '{print $1,$4,$5,$6}' $file > $output

# indeed.
echo "done."
