#!/bin/csh -f

# will need to re-run this over the reprocessed data for the final dataset
set topdir = /users/rsg/observatory/sunphotometer/skyrad.pack.V4/V4.2
set PARdir = $topdir/Par
set outfname = tau_SSA_RI_POM_Jan2021-Dec2023.txt

set HEADER = `echo "YYYY,MM,DD,HH.HH,Zen,Tau1(400nm),Tau2(400nm),SSA(400nm),RRI(400nm),IRI(400nm),Tau1(500nm),Tau2(500nm),SSA(500nm),RRI(500nm),IRI(500nm),Tau1(675nm),Tau2(675nm),SSA(675nm),RRI(675nm),IRI(675nm),Tau1(870nm),Tau2(870nm),SSA(870nm),RRI(870nm),IRI(870nm),Tau1(1020nm),Tau2(1020nm),SSA(1020nm),RRI(1020nm),IRI(1020nm)"`
echo $HEADER > $outfname

foreach file(*.par)
   set filestem = `echo $file:t:r`
   echo $filestem
   set yy = `echo $filestem | cut -c1-2`
   set yyyy = 20${yy}
   
   # split up the PAR file into discrete data chunks: easy as always 6 lines long
   split $file -l 6 -d /tmp/PAR 
     
   set parfiles = `ls /tmp/PAR*`
   set nparfiles = `ls /tmp/PAR* | wc -l`
   foreach parfile($parfiles)
      # extract the data from the PAR file
      set header = `cat $parfile | head -1 | awk '{print $2,$3,$4,$5,90.-$8}'` 
      set tau1 = `cat $parfile | head -2 | tail -1 | awk '{print $2,$3,$4,$5,$6}'` #  400nm
      set tau2 = `cat $parfile | head -3 | tail -1 | awk '{print $2,$3,$4,$5,$6}'` #  500nm
      set tau3 = `cat $parfile | head -4 | tail -1 | awk '{print $2,$3,$4,$5,$6}'` #  670nm
      set tau4 = `cat $parfile | head -5 | tail -1 | awk '{print $2,$3,$4,$5,$6}'` #  870nm
      set tau5 = `cat $parfile | head -6 | tail -1 | awk '{print $2,$3,$4,$5,$6}'` # 1020nm

      echo $header $tau1 $tau2 $tau3 $tau4 $tau5 | tr -d '\r' | tr -s " " "," >> $outfname

   end
   
   # remove the Par file split data chunks
   /bin/rm /tmp/PAR*

end

exit(0)

