#-------------------------------------------------------------------------------------------------------
#By Aina Johannessen for master thesis at UIO. 
# Generates a file containing the integrated IVT values (kg/(m*s)) Flux of moisture
#   - Grib outputfile paramenetrname and units are not updated: shortname; u are flux eastward, v are flux northward. Unit not in m/s but (kg/(m*s)) !!!
#   - Works for ECMWF analysis grib files
#   - NECCESSARY: u&v grib file, q grib file: in pressure levels:  Split up for dates and times
#   - Example of gribtype used ($grib_ls): 
##############################################################################################################################################
###########edition      centre       typeOfLevel  level        dataDate     stepRange    dataType     shortName    packingType  gridType     
###########1            ecmf         isobaricInhPa  1            20160929     0            an           q            grid_simple  reduced_gg 
###############################################################################################################################################
#   - Remember its bash.. carefull with spacing!
#	- I have silenced allot of processes, which might hide errors. Remove > /dev/null 2>&1 to see errors
##IF run from local to nonlocal machine: 
####sshfs ainajoh@login.nird.sigma2.no:/projects/NS1000K/ainajoh data_norstore
#IF run on nonlocal access example: 
####ssh -Y  ainajoh@login.nird.sigma2.no
#-------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------


dates=(20160920 20160921 20160922 20160923 20160924 20160925 20160926 20160927 20160928 20160929 20160930 20161001)
times=(0000 0600 1200 1800)
g=9.81
#------PATHS------------------------------------------------------------------------------------------
#Should all be consistent with what is inside main folder "masterthesis"
path_tmp_files="./tmp/"          #temporary files needed for calculation, discarded for each run.
path_integrated_files="../"      #Path for saved generated ivt files
path_norestore_files="../gribs/" #Path to original grib files for u&v grib file, q grib file: in pressure levels:  Split up for dates and times
                                 #"param_uv_$date""_$time.grib"
path_script="./generate_IVT.sh" #Path of this script and name.

#-----PRE-SET Filename--------------------------------------------------------------------------------
mult_q_uv=$path_tmp_files"mult_q_uv.grib"
merged_file=$path_tmp_files"all.grib"

#---Removes a file such that I dont have to specify to overwrite it everytime----------
if [ -e "$merged_file" ]
	then
		remove="rm $merged_file" 
		$remove > /dev/null 2>&1
fi

remove="rm IVT_gen_output.out" #Removing previous log file each time you start this script
$remove                        #see above

for date in ${dates[@]}; do
	#-------------Write logfiles for new date---------------------
	echo "----------------------------------">> IVT_gen_output.out
	echo "---------------$date--------------">> IVT_gen_output.out  
	echo "----------------------------------">> IVT_gen_output.out
	#-------------------------------------------------------------
	for time in ${times[@]}; do
		#------Inititating new timestep variables---------------------------
		remove_tmp="rm $path_tmp_files*" #Remove previous temperory files
		$remove_tmp > /dev/null 2>&1     # Should already be deleted, but to make sure as it is very important it is removed 
		
		fileq=$path_norestore_files"param_q_$date""_$time.grib"  		#kg/kg  Specific humidity
		fileuv=$path_norestore_files"param_uv_$date""_$time.grib"  		#m/s    Horizontal wind
		
                #Levels you want to integrate over: depends on rsolution of raw data. Levels corresponing to available pressure levels in ECMWF analysis
	   	levels=(100000 95000 92500 90000 85000 80000 70000 60000 50000 40000 30000 25000 20000 15000 10000) #Pa = kg/(m * s**2)
		
                echo "    "		
		echo "Using files----->"
		echo $fileq
		echo $fileuv
		echo "<----------------"
		echo "<----------------"
                #------------------------------------------------------------------

		#------------MULTIPLY------------------------------------------------
		mult_q_uv=$path_tmp_files"mult_q_uv.grib"
		echo "start multiplying wind with specific humidity"
		mult="cdo -R mul $fileq $fileuv $mult_q_uv" #m/s * kg/kg
		echo $mult
		$mult > /dev/null 2>&1
		echo "Done multiplying"
		
		
		#----------START INTEGRATION---Trapezoidal method-------------
		echo "--------------------------------------------------------"
		echo "START: Integration--->Trapezoidal method----------------"
		for idx in ${!levels[@]}; do
			P0=${levels[$idx]} 			   #i:lower level  --> high pressure
			P1=${levels[$(( $idx+1))]} 	#highest level-->lower pressure
			if [ $P0 -eq 10000 ]  #Breaks this inner loop if we are at level 10000 to not override it. 
				then
				 echo "Reached 100 hpa, so breaking inner loop"
				 break
			 fi
			dP=$((P0-P1)) # pressure difference in each level. -used for integration
			echo "---> In Pressure level $P0 to $P1 ---> pressure difference: $dP"
			
			summed_file=$path_tmp_files"sum$P0.grib" #filename of part sum of two and two levels. 
			t="cdo -mulc,$dP -add -sellevel,$P0 $mult_q_uv -sellevel,"$P1" $mult_q_uv $summed_file"
			$t  > /dev/null 2>&1 #makes output silence					
		done
		echo "---> For loop done"
		
		#--------Merging all sum files to be able to use vertsum for summing up all levels----
      u="cdo merge $path_tmp_files""sum* $merged_file"

		$u   > /dev/null 2>&1 #makes output silence
		integrated_file=$path_integrated_files"IVT_$date""_$time.grib"
		s="cdo -divc,$g -mulc,0.5 -vertsum $merged_file $integrated_file"
		$s  > /dev/null 2>&1 #makes output silence
		echo "DONE integrating--------------------------------------------"
		echo "--------------------------------------------------------"
		
		echo "$fileq -----\ "                      >> IVT_gen_output.out  
		echo "$fileuv----------> $integrated_file" >> IVT_gen_output.out  
		echo "                                   " >> IVT_gen_output.out
		
		#--------Plots-------------------------------------------------------------------------
		#If you want plotting to automatically occur as ivt files are generated:Not setup correctly here
		#python_file=$path_script"IVT.py"
		#plot="python $python_file --date $date $time"
		#$plot #> /dev/null 2>&1	 						# > /dev/null 2>&1 makes output silence
		#echo "Done plotting"
		#-------------------------------------------------------------------------------------

  		#---Removes a file such that I dont have to specify to overwrite it everytime----------
		remove="rm $path_tmp_files*"
		$remove > /dev/null 2>&1
		echo "!!all temporary files are removed!!"	

	done
done
echo "--**SUCESS**--"

#echo "removes start"
#remove="rm $merged_file"
#$remove	
#echo "removed"
