#!/bin/bash

#A shell program to separate varables for the main stem data:

# 0    1     2     3         4       5      6      7     8      9  
#     CHLA   DO    DOC      DON     NH4F    NO23F  NO2F  NO3F   PC
# PH  PHEO   PN    PO4F     PP    SALINITY  SECCHI SIF   SPCOND TDN
# TDP TKNF TKNW TOC   TP    TSS      VSS     WTEMP

#variables="       CHLA   DO    DOC   DON     NH4F    NO23F  NO2F  NO3F
#              PC  PH     PHEO PN  PO4F   PP    SALINITY SECCHI  SIF    SPCOND
#              TDN  TDP    TKNF TKNW TOC   TP    TSS      VSS     WTEMP"

variables="SALINITY WTEMP" 

stations="CB1.1 CB2.1 CB2.2 CB3.1 CB3.2 CB3.3C CB3.3E CB3.3W CB4.1C CB4.1W CB4.2C
         CB4.2E CB4.2W CB4.3C CB4.3E CB4.3W CB4.4 CB5.1 CB5.1W CB5.2 CB5.3 CB5.4 CB5.4W
         CB5.5 CB6.1 CB6.2 CB6.3 CB6.4 CB7.1 CB7.1N CB7.1S CB7.2 CB7.2E CB7.3 CB7.3E CB7.4
         CB7.4N CB8.1 CB8.1E EE3.5"

# To uncompress data file, activate following line.
 gzip -d ../1original/cbpWQstem1990_2006.txt.gz

for varname  in $variables
do
 echo $varname

`awk -v vnam="$varname" '{ if( $12 == vnam && $13+0==$13){ print $0 }}' ../1original/cbpWQstem1990_2006.txt > tmp.txt` 

#
# the $13+0==$13 in the upper line is to make sure that $13 has a numerical number instead of emptry or strings
#

 for stn in $stations
 do                                                 #5     6     7    12   NF-1    NF
    echo $stn                                       #date time depth value lat lon

   `cat   tmp.txt | tr \< " " > tmp1.txt`
 
   `awk -v stnam="$stn" '{ if ($5 == stnam ) {print $6,  $7,   $8,  $13, $(NF-1),$NF}}' tmp1.txt > tmp2.txt`

    `cat tmp2.txt | tr / " "   | tr : " " | \
      awk '{print $3, $1,  $2,  $4, $5 , $6   ,  $7 ,   $8,  $9}'  > tmp3.txt`
#                  yyy mm   dd  hh min  depth   value  lat   lon                
#                   1   2    3   4   5    6        7    8      9    
#
# sort acording to date-time, depth
#
     filesize=`sum tmp3.txt | awk '{print $1}'`

     if [ $filesize -ne 0 ] 
     then
     `cat tmp3.txt | sort -n -k 1,1 -k 2,2 -k 3,3 -k 4,4 -k 5,5 -k 6,6  > tmp4.txt`  #sort by yyyy mm dd hh min depth  (+0 -6 means sort from number 1 to number 6 fields)   

#---output

     `cp tmp4.txt "$varname"_"$stn"_1990_2006.txt` 
     fi       

 done

done

`rm tmp*.txt` 

 gzip -9  ../1original/cbpWQstem1990_2006.txt


exit




