#!/usr/bin/env bash
module load tools/pngcrush/1.8.11
module load climate/ncl/6.4.0
module load climate/nco/5.0.1
module load tools/ghostscript/10.03.0
#===========================================
start_hour=${1:-"00"}		# start hour mise à 00
PLOT_QUALITY=${PLOT_QUALITY:-200}
PLOT_ANTIALIAS=${PLOT_ANTIALIAS:-1}
PLOT_EXTRAS=${PLOT_EXTRAS:-1}
PLOT_PLEVS=${PLOT_PLEVS:-0}	# seulement si des stations sont definies
PLOT_ISO0=${PLOT_ISO0:-0}	# seulement si des stations sont definies
NBPROCS=${NBPROCS:-12}
#===========================================
(( PLOT_ANTIALIAS )) && ANTIALIAS_CMD="-antialias" || ANTIALIAS_CMD="+antialias"
#===========================================
function convert_eps2png
{
	local eps_file=${1:?"Error: no EPS file"}
	local png_file=$(echo ${epsfile}|sed -e "s/wrf_\(.*\)_\([0-9]*\).eps/WORK\/\1_d${dom}_t${start_hour}z_\2.png/")

	echo "Converting ${eps_file} -> ${png_file}"
	gm convert -trim -transparent white -density ${PLOT_QUALITY} ${ANTIALIAS_CMD} ${eps_file} ${png_file}
	# gm convert -trim -transparent white -density 200 -antialias 
}
function crush_png
{
	local png_file=${1:?"Error: no PNG file"}

	echo "Crushing ${png_file}..."
	pngcrush ${png_file} ${png_file}_tmp.png >&/dev/null
	mv ${png_file}_tmp.png ${png_file}
}
#===========================================
mkdir -p WORK
rm -f WORK/*
 
# date du jour pour aller chercher les sorties WRF
dirdate=`date '+%Y_%m_%d'`

echo "PLOT_EXTRAS: $PLOT_EXTRAS"


for dom in {02..03} ; do

	wrfout="wrfout_d${dom}.nc"
	wrfext="wrfout_d${dom}-extra.nc"
	wrfplevs="wrfplevl_d${dom}.nc"
	stations="stations_plot_d${dom}.txt"

	[[ -f ${stations} ]] && STATIONS_CMD="station_file=\"${stations}\""
        echo $STATIONS_CMD

	if (( PLOT_EXTRAS )) ; then
		# Compute extra variables
		ncap2 -O -v -S compute_vars.nco ${wrfout} ${wrfext}

		# Cloud fraction
		ncl plot_cldfra.ncl ncdf_file=\"${wrfext}\" ${STATIONS_CMD} &

		# RH2
		ncl plot_rh2.ncl ncdf_file=\"${wrfext}\" ${STATIONS_CMD} &
	fi

	# Iso 0°C
	if (( PLOT_ISO0 )) ; then
		python iso0.py ${wrfout}
		ncl plot_iso0c.ncl ncdf_file=\"${wrfout}\" iso0c_file=\"iso0c.nc\" ${STATIONS_CMD} &
	fi

	# Pressure / Precipitations
	ncl plot_pcp.ncl ncdf_file=\"${wrfout}\" ${STATIONS_CMD} &

	# TC 2m
	ncl plot_t2m.ncl ncdf_file=\"${wrfout}\" ${STATIONS_CMD} &

	# Wind dir & speed
	ncl plot_wnd.ncl ncdf_file=\"${wrfout}\" ${STATIONS_CMD} &

	if (( PLOT_PLEVS )) ; then
		# TC / height on pressure levels
	 	ncl plot_plevs.ncl ncdf_file=\"${wrfout}\" plevs_file=\"${wrfplevs}\" ${STATIONS_CMD} &
	 fi

	wait

	# Convert EPS files in PNG
	njobs=0
	for epsfile in $(ls *.eps) ; do
		njobs=$((njobs+1))
		convert_eps2png ${epsfile} &
		[[ $((njobs%${NBPROCS})) == 0 ]] && wait
	done
	wait

	rm -f *.eps
done

# Crush PNG files
njobs=0
for pngfile in $(ls WORK/*.png) ; do
	njobs=$((njobs+1))
        crush_png ${pngfile} &
	[[ $((njobs%${NBPROCS})) == 0 ]] && wait
done
wait
