#!/bin/bash

#A shell program to separate varables for the tributary data;


# 0       1       2       3     4     5       6         7         8       9
#         BOD5W   CHLA    CLW   COD   DO      DOC      DON     FCOLI_M   FS
# FSS    HARDNESS NH4F    NO23F   NO2F  NO3F  PC      PH       PHEO      PN
# PO4F    PP     SALINITY SECCHI  SIF   SO4W  SPCOND  TALK     TCOLI_M   TDN
# TDP     TKNF   TKNW     TOC     TP     TS   TSS     TURB_FTU TURB_NTU  VSS
# WTEMP

#variables=" BOD5W CHLA    CLW   COD   DO      DOC      DON      FCOLI_M   FS     FSS
#            HARDNESS NH4F    NO23F   NO2F  NO3F  PC      PH       PHEO      PN     PO4F
#            PP     SALINITY SECCHI  SIF   SO4W  SPCOND  TALK     TCOLI_M   TDN    TDP 
#            TKNF   TKNW     TOC     TP     TS   TSS     TURB_FTU TURB_NTU  VSS    WTEMP"

variables="CHLA DO" 

stations="CB4.1E CB7.2 CB7.2E EE1.1 EE2.1 EE2.2 EE3.0 EE3.1 EE3.2 EE3.3 EE3.4 ET1.1 ET2.1
           ET2.3 ET4.2 ET5.2 ET6.2 LE1.1 LE1.2 LE1.3 LE1.4 LE2.2 LE2.3 LE3.1 LE3.2 LE3.3 LE3.4
           LE3.6 LE3.6N LE3.6S LE3.7 LE4.1 LE4.2 LE4.3 LE5.1 LE5.2 LE5.3 LE5.4 LE5.5 LE5.5-W 
	   LE5.6 RET1.1 RET2.4 RET3.1 RET3.2 RET4.2 RET4.3 RET5.2 TF1.7 TF2.1 TF3.3 TF5.6A 
	   WE4.1 WE4.2 WE4.2N WE4.2S WE4.3 WE4.4 WT2.1 WT5.1 WT6.1"

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

for varname  in $variables
do
 echo $varname

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

 for stn in $stations
 do
    echo $stn
   
    `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
     `sort -n -k 1,1 -k 2,2 -k 3,3 -k 4,4 -k 5,5 -k 6,6 tmp3.txt > tmp4.txt` #sort yyyy mm dd hh min depth
#---output "yyyy mm dd hh min depth value lat lon" 

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

 done

done

`rm tmp*.txt`   #remove the temporary files 

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

exit




