@echo off
setLocal EnableDelayedExpansion

REM #################################################
REM # Adapted from \hysplit4\testing\xcluster.bat   #
REM #################################################

set DIR=c:
set PGM=%DIR%\hysplit4
cd %PGM%\working

IF NOT EXIST fdump83090100 (
   IF NOT EXIST fdump83092818 (
      echo trajectory endpoint {fdump} files missing, rerun previous batch file
      pause
   )
)

REM set final number of clusters -------------------

SET ilab1=traj_clus
SET nc=4		

REM section 1 --------------------------------------

dir /b fdump???????? >INFILE

SET dur=48
SET int=1
SET skip=1
SET ODIR=.\
SET PROJ=0
   
ECHO %dur%   > CCONTROL
ECHO %int%  >> CCONTROL 
ECHO %skip% >> CCONTROL 
ECHO %ODIR% >> CCONTROL
ECHO %PROJ% >> CCONTROL

%PGM%\exec\cluster 
DEL TNOCLUS TCLUS

REM section 2 --------------------------------------

SET  mint=15  
SET  minc=3  
SET  maxc=10
SET  pct=30 
        
REM # TSV plot
%PGM%\exec\clusplot  -iDELPCT -oclusplot.ps -l%ilab1%
clusplot.ps
PAUSE
      
REM # determine final number of clusters
%PGM%\exec\clusend -iDELPCT -n%minc% -a%maxc% -t%mint% -p%pct% -oCLUSEND

REM # generate list of trajs in each cluster
%PGM%\exec\cluslist -iCLUSTER -n%nc% -oCLUSLIST_%nc%

REM # add trajs not clustered (cluster #0) to CLUSLIST
IF EXIST CLUSTERno (
   TYPE CLUSLIST_%nc% >> CLUSTERno
   DEL CLUSLIST_%nc%
   RENAME CLUSTERno CLUSLIST_%nc%
)

REM # create TRAJ.INP.Cxx file for each cluster (list of trajs) 
%PGM%\exec\clusmem -iCLUSLIST_%nc%

for %%N in (1 2 3 4) do (
    %PGM%\exec\merglist -i+TRAJ.INP.C%%N_%nc% -omdump -ptdump
    RENAME mdump.tdump C%%N.tdump
    %PGM%\exec\trajmean -i+TRAJ.INP.C%%N_%nc% 
    RENAME tmean C%%Nmean.tdump
)

IF EXIST MEAN.LIST DEL MEAN.LIST
for %%N in (1 2 3 4) do (
    ECHO C%%Nmean.tdump  >> MEAN.LIST
)

%PGM%\exec\merglist -i+MEAN.LIST -omdump -ptdump
RENAME mdump.tdump Cmean.tdump
DEL MEAN.LIST

REM section 3 --------------------------------------

for %%N in (1 2 3 4) do (
    ECHO 'TITLE^&','TRAJECTORIES IN CLUSTER %%N of 4 Example^&' > LABELS.CFG
    %PGM%\exec\trajplot -iC%%N.tdump -e%dur% -z80 -k0 -l0 -v4 
    IF EXIST trajplot_C%%N.ps DEL trajplot_C%%N.ps
    RENAME trajplot.ps trajplot_C%%N.ps
    trajplot_C%%N.ps
    PAUSE
)

SET tmout=Cmean.tdump 
ECHO 'TITLE^&','CLUSTER MEAN TRAJECTORIES %ilab1%^&' > LABELS.CFG
%PGM%\exec\trajplot -i%tmout% -e%dur% -z80 -k%nc%:1234 -l-12 -v4
IF EXIST trajplot_MEAN.ps DEL trajplot_MEAN.ps
RENAME trajplot.ps trajplot_MEAN.ps
trajplot_MEAN.ps
PAUSE

REM section 4 cleanup --------------------------------------

rem DEL TCLUS TNOCLUS CLUSTER DELPCT CLUSTERno CMESSAGE
rem DEL INFILE CCONTROL LABELS.CFG
rem DEL *.tdump
rem DEL TRAJ.INP*
rem DEL CLUSLIST_* CLUSEND
