#!/bin/sh
#
# Change history:
#  3 Nov 2023 (SYZ) - change the optimal number of clusters to 6.

  echo "### ${0##*/} ###"
  WEB=""
  if [ -f /usr/bin/firefox ];then WEB="/usr/bin";fi
  if [ -f /usr/local/bin/firefox ];then WEB="/usr/local/bin";fi
  MDL=${1:-"${HOME}/hysplit"}
  OUT=${2:-"${MDL}/working"}
  DSP=${3:-"YES"}
  nc=${4:-6}	# number of clusters
  PGM="${MDL}"
  cd $OUT

  ilab1=CAPTEX2 # title
# nc=5		# number of clusters

  rm -f cluster.html

#################
# cluster1.scr
#################
  dur=48	                # hours to do clustering
  int=1	                        # Endpoint interval to use (hours)
  skip=1	                # Skip trajectory interval
  ODIR="${OUT}/"		# Cluster output directory (with trailing /)
  cd $ODIR
  iproj=0
   
  echo $dur   > CCONTROL
  echo $int  >> CCONTROL 
  echo $skip >> CCONTROL 
  echo $ODIR >> CCONTROL 
  echo $iproj >> CCONTROL
    
# do clustering
  rm -f TCLUS TNOCLUS CLUSTER DELPCT CLUSTERno CMESSAGE
  $PGM/exec/cluster 
  if [ ! -f CLUSTER -o ! -f DELPCT ]; then
     echo "ERROR - cluster failed"
     exit
  fi
  rm TNOCLUS	# not used
  rm TCLUS	# not used

#################
# cluster2.scr
#################
# variables for clusend (determining final number of clusters) --
  mint=15    # min number traj 
  minc=3     # min number of clusters
  maxc=10    # max number of clusters
  pct=30     # min % change in DELPCT from 1 step to the next
             #     ie breakpoint to indicate end of clustering

# TSV plot
  $PGM/exec/clusplot +g1 -iDELPCT -oclusplot.html -l${ilab1}
  mv clusplot.html cluster.html
  if [[ "$DSP" != "YES" ]]; then
     ${MDL}/exec/splitsvg -icluster.html -oclus004.svg
     convert F01-clus004.svg clus004.png
     rm -f F??-clus004.svg
  elif [ ! -s cluster.html ]; then
     echo "ERROR - clusplot failed"
     exit
  fi
      
# determine final number of clusters
  rm -f CLUSEND
  if $PGM/exec/clusend -iDELPCT -n${minc} -a${maxc} -t${mint} -p${pct} -oCLUSEND; then
     echo $PGM/exec/clusend OK 1st try
  else
     # relax criteria to help get # clusters
     pct=`expr $pct - 10`
     $PGM/exec/clusend -iDELPCT -n${minc} -a${maxc} -t${mint} -p${pct} -oCLUSEND
  fi
  if [ ! -s CLUSEND ]; then
     echo "ERROR - clusend failed"
     exit
  fi

# generate list of trajs in each cluster
  rm -f CLUSLIST_${nc}
  $PGM/exec/cluslist -iCLUSTER -n${nc} -oCLUSLIST_${nc}
  if [ ! -s CLUSLIST_${nc} ]; then
     echo "ERROR - cluslist failed"
     exit
  fi

# add trajs not clustered (cluster #0) to CLUSLIST
  if [ -s CLUSTERno ]; then       
     cat CLUSLIST_${nc} >> CLUSTERno
     mv CLUSTERno CLUSLIST_${nc}
  fi

# create TRAJ.INP.Cxx file for each cluster (list of trajs) 
  rm -f TRAJ.INP*
  if $PGM/exec/clusmem -iCLUSLIST_${nc}; then

     ##############################################
     # for each cluster 
     ##############################################
     run=-1					# for cluster #0 
     while [ $run -lt $nc ]; do
        run=`expr $run + 1`
        if [ -f TRAJ.INP.C${run}_${nc} ]; then	# cluster #0 may not exist
           ##############################################
           # create tdump file of all trajs
           ##############################################
           $PGM/exec/merglist -i+TRAJ.INP.C${run}_${nc} -omdump -ptdump
           if [ -s mdump.tdump ]; then
               mv mdump.tdump C$run.tdump
           else
               echo "ERROR - merglist TRAJ.INP.C${run}_${nc}"
               exit 
           fi
           ##############################################
           # compute mean 
           ##############################################
           $PGM/exec/trajmean -i+TRAJ.INP.C${run}_${nc} 
           if [ -s tmean ]; then
              mv tmean C${run}mean.tdump
           else
              echo "ERROR - trajmean TRAJ.INP.C${run}_${nc}"
              exit 
           fi
        fi
     done

     ##############################################
     # make one tdump for all means
     ##############################################
     # for each cluster  (not zero)
     run=0
     rm -f MEAN.LIST
     while [ $run -lt $nc ]; do
        run=`expr $run + 1`
        echo "C${run}mean.tdump" >> MEAN.LIST
     done

     $PGM/exec/merglist -i+MEAN.LIST -omdump -ptdump
     if [ -s mdump.tdump ]; then
        mv mdump.tdump Cmean.tdump
     else
        echo "ERROR - merglist MEAN.LIST"
        exit 
     fi
     rm -f MEAN.LIST

  else
     echo "ERROR - clusmem"
     exit 
  fi

  #################
  # cluster3.scr
  #################

# plot trajectories for each cluster
  run=-1				# for cluster #0 
  while [ $run -lt $nc ]; do
     run=`expr $run + 1`
     if [ -s C$run.tdump ]; then 
        rm -f LABELS.CFG
        echo "'TITLE&','TRAJECTORIES IN CLUSTER ${run} of ${nc}&'"  >LABELS.CFG
        $PGM/exec/trajplot +g1 -iC$run.tdump -j${PGM}/graphics/arlmap -e$dur -z80 -k0 -l0 -v4
        if [[ "$DSP" != "YES" ]]; then
           ${MDL}/exec/splitsvg -itrajplot.html -otrajplot_C${run}.svg
           convert F01-trajplot_C${run}.svg trajplot_C${run}.png
           rm -f F??-trajplot_C${run}.svg
        elif [ -s trajplot.html ]; then
           mv trajplot.html trajplot_C$run.html
           if [[ "$OSTYPE" == "darwin"* ]]; then
              open trajplot_C$run.html 
              echo "Enter to continue ...";  read x
           else
              ${WEB}/firefox trajplot_C$run.html & 
              echo "Enter to continue ...";  read x
           fi
        else
           echo "Error in trajplot +g1 -iC$run.tdump" 
           exit 
        fi
     fi
  done
  rm -f LABELS.CFG
   
# compute/plot mean traj for each cluster
  tmout=Cmean.tdump 
  if [ -s $tmout ]; then
     rm -f LABELS.CFG
     echo "'TITLE&','CLUSTER MEAN TRAJECTORIES&'" >LABELS.CFG
     if [ ${nc} -eq 5 ]; then
        kopt="-k${nc}:12345"
     else
        kopt="-k${nc}:123456"
     fi
     $PGM/exec/trajplot +g1 -j${PGM}/graphics/arlmap -i$tmout -e$dur -z80 ${kopt} -l-12 -v4
     if [[ "$DSP" != "YES" ]]; then
        ${MDL}/exec/splitsvg -itrajplot.html -oclus006.svg
        convert F01-clus006.svg clus006.png
        rm -f F??-clus006.svg
     elif [ -s trajplot.html ]; then
        mv trajplot.html trajmean.html
     else
        echo "ERROR - trajplot +g1 -i$tmout"
        exit 
     fi
     rm -f LABELS.CFG
  fi

  if [[ "$DSP" != "YES" ]]; then
     echo ""
  elif [[ "$OSTYPE" == "darwin"* ]]; then
     open trajmean.html 
  else
     ${WEB}/firefox trajmean.html & 
  fi

# ---------------------------------------------------------------------
# cleanup
# rm -f CCONTROL
# rm -f CLUSTER CLUSTERno CMESSAGE DELPCT
# rm -f CLUSLIST_* CLUSEND 
# rm -f TRAJ.INP.C?_?
# rm -f fdump8309????
# rm -f  *.tdump
