type file;

string yes = "1";
string no = "0";

# Set which datasets are needed
int test_popdiag = @toint(@arg("popdiag",no));
int test_popdiagdiff = @toint(@arg("popdiagdiff",no));
int test_popdiagts = @toint(@arg("popdiagts",no));
int doplots = @toint(@arg("doplots",yes));trace(@strcat("doplots: ",@arg("doplots")));
int cpy_hsi = @toint(@arg("cpy_hsi",no));trace(@strcat("cpy_hsi: ",@arg("cpy_hsi")));

int need_clim_exp = @toint(@arg("need_clim_exp",no));trace(@strcat("need_clim_exp: ",@arg("need_clim_exp")));
int need_clim_SALT_exp = @toint(@arg("need_clim_SALT_exp",no));trace(@strcat("need_clim_SALT_exp: ",@arg("need_clim_SALT_exp")));
int need_clim_TEMP_exp = @toint(@arg("need_clim_TEMP_exp",no));trace(@strcat("need_clim_TEMP_exp: ",@arg("need_clim_TEMP_exp")));
int need_clim_cntrl = @toint(@arg("need_clim_cntrl",no));trace(@strcat("need_clim_cntrl: ",@arg("need_clim_cntrl")));
int need_clim_SALT_cntrl = @toint(@arg("need_clim_SALT_cntrl",no));trace(@strcat("need_clim_SALT_cntrl: ",@arg("need_clim_SALT_cntrl")));
int need_clim_TEMP_cntrl = @toint(@arg("need_clim_TEMP_cntrl",no));trace(@strcat("need_clim_TEMP_cntrl: ",@arg("need_clim_TEMP_cntrl")));
int needtavg_exp = @toint(@arg("needtavg_exp",no));trace(@strcat("needtavg_exp: ",@arg("needtavg_exp")));
int needtavg_cntrl = @toint(@arg("needtavg_cntrl",no));trace(@strcat("needtavg_cntrl: ",@arg("needtavg_cntrl")));
int needzavg_exp = @toint(@arg("needzavg_exp",no));trace(@strcat("needzavg_exp: ",@arg("needzavg_exp")));
int needzavg_cntrl = @toint(@arg("needzavg_cntrl",no));trace(@strcat("needzavg_cntrl: ",@arg("needzavg_cntrl")));

# Set data info
string wrkdir = @arg("wrkdir");trace(@strcat("wrkdir: ",@arg("wrkdir")));
string msroot = @strcat(@arg("msroot"),"/");trace(@strcat("msroot: ",@arg("msroot")));
string caseN = @arg("case");trace(@strcat("case: ",@arg("case")));
string resolution = @arg("resolution");trace(@strcat("resolution: ",@arg("resolution")));
string cntrlmsroot = @strcat(@arg("cntrlmsroot"),"/");trace(@strcat("cntrlmsroot: ",@arg("cntrlmsroot")));
string cntrlcaseN = @arg("cntrlcase");trace(@strcat("case: ",@arg("cntrlcase")));
string cntrlresolution = @arg("cntrlresolution");trace(@strcat("cntrlresolution: ",@arg("cntrlresolution")));

int year0 = @toint(@arg("year0"));trace(@strcat("test_begin: ",@arg("year0")));
int year1 = @toint(@arg("year1"));trace(@strcat("test_end: ",@arg("year1")));
int test_nyrs = ((year1 - year0) +1);
int years_to_test[] = [year0 : year0 + test_nyrs - 1 : 1];

int cntrlyear0 = @toint(@arg("cntrlyear0"));trace(@strcat("cntrl_begin: ",@arg("cntrlyear0")));
int cntrlyear1 = @toint(@arg("cntrlyear1"));trace(@strcat("cntrl_end: ",@arg("cntrlyear1")));
int cntrl_nyrs = ((cntrlyear1 - cntrlyear0) +1);
int cntrlyears_to_test[] = [cntrlyear0 : cntrlyear0 + cntrl_nyrs - 1 : 1];

string sobsfilefn = @arg("sobsfilefn");
string tobsfilefn = @arg("tobsfilefn");

string seasavgtemp = @arg("seasavgtemp");
string seasavgsalt = @arg("seasavgsalt");
string cntrlseasavgtemp = @arg("cntrlseasavgtemp");
string cntrlseasavgsalt = @arg("cntrlseasavgsalt");
int compute_rho = @toint(@arg("compute_rho"));
int compute_cntl_rho = @toint(@arg("compute_cntl_rho"));

#ncl file list
string ncl_list = @arg("ncl_wrap");trace(@strcat("ncl_wrap: ",@arg("ncl_wrap")));

#Variables only used by NCL calls
string cntrlvls = @arg("cntrlvls");
string cpl = @arg("cpl");
string cplcntrl = @arg("cplcntrl");
string fluxobsfile = @arg("fluxobsfile");
#string idlcolortable = @arg("idlcolortable");
#string idlcolortablefile = @arg("idlcolortablefile");
#string idllndcolor = @arg("idllndcolor");
#string idlmaxcolor = @arg("idlmaxcolor");
#string idlmincolor = @arg("idlmincolor");
string rhoobsfile = @arg("rhoobsfile","null");
string sobsfilefp = @arg("sobsfilefp");
string sshobsfile = @arg("sshobsfile","null");
string sstobsfile = @arg("sstobsfile");
string tavgfile = @arg("tavgfile");
string cntrlfile = @arg("cntrlfile");
string tobsfilefp = @arg("tobsfilefp");
string togataofile = @arg("togataofile");
string windobsfile = @arg("windobsfile");
string tobsdir = @arg("tobsdir");
string ncarg_root =@arg("ncarg_root");
string nclpath = @arg("nclpath");
string diagrootpath = @arg("diagrootpath");
string ncarg_colormap_path = @arg("ncarg_colormap_path");
string seasavgfile = @arg("seasavgfile");
string seasavgrho = @arg("seasavgrho");
string cntrlseasavgfile = @arg("cntrlseasavgfile");
string cntrlseasavgrho = @arg("cntrlseasavgrho"); 

#================================================================================
# App Calls
#================================================================================

(string yrstr)yearprint(int yr){
  if(yr<10) {
    yrstr = @strcat("000",yr);
  }
  if(yr >= 10 && yr <100) {
    yrstr=@strcat("00",yr);
  }
  if(yr >= 100 && yr <1000) {
    yrstr=@strcat("0",yr);
  }
  if(yr >= 1000) {
    yrstr=@strcat(yr);
  }
}
(string mstr)monthprint(int m){
  if(m<10) {
    mstr = @strcat("0",m);
  } else {
    mstr = @strcat(m);
  }
}

### Calls ncra
(file out) Record_Average(string f[], file hsiFile[]){

     app{ ncra "-O" f @filename(out);}
}

### Calls ncra
(file out) Record_Average_Files(file f[], string firstFile, string pattern){

     app{ ncra "-O" "-n" pattern  firstFile @filename(out);}
}

### Calls ncra
(file out) Record_Average_var(string vars, string f[]){

     app{ ncra "-O" "-v" vars  f @filename(out);}
}

### Calls ncea
(file out) Ensemble_Average_var(string vars, string f[], file monhsiFileL[]){

     app{ ncea "-O" "-v" vars  f @filename(out);}
}

### Calls ncrcat
(file out) Record_Cat(file f[]){

     app{ ncrcat "-O" @filenames(f) @filename(out);}
}

### Calls ncks
(file out) ncks_var(string var, file f){

     app{ ncks "-O" "-v" var  @filename(f) @filename(out);}
}

### Calls ncks
(file out) ncks_varS(string var, string f){

     app{ ncks "-O" "-v" var  f @filename(out);}
}

### Calls za 
(file out) zonal_average(file f, string fn){

     app{ za_csh @filename(out) fn;}
}

### Creates za file
(file out)Append_ncks_za(file file1, string file2fp, string obsdir){

	app {Append_ncks_za_csh @filename(file1) file2fp @filename(out) obsdir;}
}

### Check which monthly files to get using hsi
(file out)Check_Mon_hsi(string msrootL, string casenameL, int year0L, int year1L, string workdir, string toollib, 
                 int needtavg, int needclim) {

        app{check_hsi_mfiles_csh msrootL casenameL year0L year1L @filename(out) workdir toollib needtavg needclim;}
}

### Get the monthly files using hsi
(file out)GethsiFile(string fileName, string wrkdirL, string msrootL, string casenameL, string typ){

        app {get_hsi_csh fileName wrkdirL @filename(out) msrootL casenameL typ;}
}

### Check to see if any yearly ave files are located on hpss
(file out)Check_yavg_hsi(string msrootL, string caseNL, int year0L, int year1L, string wrkdirL){

        app {Check_yavg_hsi_csh msrootL caseNL year0L year1L wrkdirL @filename(out);}
}

### Create a list of year numbers that need to be computed
(file out)Check_yavg(file complete[], string caseNL, string wrkdirL, int yr0, int yr1){

        app {Check_yavg_csh caseNL wrkdirL yr0 yr1 @filename(out);}
}

### Copy file over using hsi
(file out)store_file(file fp, string msrootL, string caseNL, string dir, string f){

        app {store_file_csh @filename(fp) msrootL caseNL dir @filename(out) f;}
}

### Remove the monthly files that were retreived using hsi
(file out)removeMF(string f, file outfilesL[], file mavgFileL){

        app {removeMF_csh f @filename(out);}
}

### Run NCL plotting scripts
(file out)ncl_wrapper(file TAVG_exp, file TAVG_cntrl, file MAVG_exp, file MAVG_cntrl, file ZA_exp, file Za_cntrl, string f,
          string arg1,string arg2,string arg3,string arg4,string arg5,string arg6,string arg7,
          string arg8,string arg9,string arg10,string arg11,string arg12,string arg13,string arg14,
          string arg15,string arg16,string arg17,string arg18,
	  int arg19,int arg20,string wrkdirL,string ncarg_rootL,string nclpathL,string ncarg_colormap_pathL,
          string arg21, string arg22, string arg23, int arg24, int arg25, string arg26, string arg27,
          string arg28, string arg29, string arg30, string arg31){

	app {ncl_wrapper_diff_csh f @filename(out) arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8
              arg9 arg10 arg11 arg12 arg13 arg14 arg15 arg16 arg17 arg18 arg19 
              arg20 wrkdirL ncarg_rootL nclpathL ncarg_colormap_pathL arg21 arg22 arg23 arg24 arg25 arg26
              arg27 arg28 arg29 arg30 arg31;}
}

### Run NCL computing scripts
(file out)run_ncl(string nclFile, file f1, file f2,
          string arg1,string arg2,string arg3,string arg4,string arg5,string arg6,string arg7,
          string arg8,string arg9,string arg10,string arg11,string arg12,string arg13,string arg14,
          string arg15,string arg16,string arg17,string arg18,
          int arg19,int arg20,string wrkdirL,string ncarg_rootL,string nclpathL,string ncarg_colormap_pathL,
          string arg21, string arg22, string arg23, int arg24, int arg25, string arg26, string arg27,
          string arg28, string arg29, string arg30, string arg31){  

      app {ncl_wrapper_diff_csh nclFile @filename(out) arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8
              arg9 arg10 arg11 arg12 arg13 arg14 arg15 arg16 arg17 arg18 arg19
              arg20 wrkdirL ncarg_rootL nclpathL ncarg_colormap_pathL arg21 arg22 arg23 arg24 arg25 arg26
              arg27 arg28 arg29 arg30 arg31;}

}

### Create a list of all ps files that need to be converted
(file out)getFileList(file nclF[],string wrkdirL) {

	app {get_PSList_csh wrkdirL @filename(out);}
}

### Convert images
(file out)convertImages(string wrkdirL, string fn, string diagrootpathL){

	app{convert_images_csh wrkdirL fn @filename(out) diagrootpathL;}
}

### Next three subroutines create blank files that are only used to fill in the
### Swift dependencies for files that already exist and don't have to be computed
(file out)create_blank_file(){

	app{dummy_file_csh @filename(out);}
}

(file out)create_blank_file_f(file f){

        app{dummy_file_csh @filename(out);}
}

(file out)create_blank_file_f3(file f1, file f2, file f3){

        app{dummy_file_csh @filename(out);}
}

#================================================================================
# Create Averages
#================================================================================

### Create the yearly average files
(file outfile) CalcTAVG(string dpath, string casename, string msr, int yr, file monhsiFileL[]) 
{
  int m[]=[1,2,3,4,5,6,7,8,9,10,11,12];
  string filesInYear[];
  foreach month in m{
    filesInYear[month]=@strcat(dpath,casename,".pop.h.",yearprint(yr),"-",monthprint(month),".nc");
  }
  outfile = Record_Average(filesInYear,monhsiFileL);
}

### Create the mavg file
(file mavgFile) CalcMAVG(string dpath, string casename, string msr, int yr0, int yr1, int years[], file monhsiFileL[])
{ 
  string monthNames[]=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
  file monthFiles[];
  string var1 = "TEMP";
  string var2 = "SALT";
  int m[]=[1,2,3,4,5,6,7,8,9,10,11,12];
  foreach month in m {
    string mname[];
    foreach year in years {
      mname[year] = @strcat(dpath,casename,".pop.h.",yearprint(year),"-",monthprint(month),".nc");
    }
    file monthFile; 
    monthFile = Ensemble_Average_var("TEMP,SALT", mname, monhsiFileL);  
    monthFiles[month] = monthFile;
  }

  mavgFile = Record_Cat(monthFiles);

}

#================================================================================
# Get hsi files
#================================================================================
(file monhsiFileL[]) hsi_files(string monHSIfilesL[],string wrkdirL,string msrootL, string casenameL,string typ) {

  foreach f,ix in monHSIfilesL{
    if (f != " "){
      monhsiFileL[ix]=GethsiFile(f,wrkdirL,msrootL,casenameL,typ);
    }
  }
}

#================================================================================
# HSI
#================================================================================
# Check to see if we need to grab files from hsi

file monHSIFileList;
file cntrlmonHSIFileList;
monHSIFileList = Check_Mon_hsi(msroot,caseN,year0,year1,wrkdir,@strcat(diagrootpath,"/tool_lib"),needtavg_exp,need_clim_exp);
cntrlmonHSIFileList = Check_Mon_hsi(cntrlmsroot,cntrlcaseN,cntrlyear0,cntrlyear1,wrkdir,@strcat(diagrootpath,"/tool_lib"),needtavg_cntrl,need_clim_cntrl);

string monHSIfiles[] = readData(monHSIFileList);
string cntrlmonHSIfiles[] = readData(cntrlmonHSIFileList);

file  monhsiFileComplete[];
file  cntrlmonhsiFileComplete[];

### Call procedure to get monthly files using hsi
if ((needtavg_exp == 1 && yavgToCompute_exp[0] != "ALL FOUND") || need_clim_exp == 1){
  monhsiFileComplete= hsi_files(monHSIfiles,wrkdir,msroot,caseN,"monthly");
}
if ((needtavg_cntrl == 1 && yavgToCompute_cntrl[0] != "ALL FOUND") || need_clim_cntrl == 1){
  cntrlmonhsiFileComplete= hsi_files(cntrlmonHSIfiles,wrkdir,cntrlmsroot,cntrlcaseN,"monthly");
}

### Set where the monthly files are located
string datapath;
string cntrldatapath;
if (monHSIfiles[1] == " "){
  datapath = msroot;
} else {
  datapath = wrkdir;
}
if (cntrlmonHSIfiles[1] == " "){
  cntrldatapath = cntrlmsroot;
} else {
  cntrldatapath = wrkdir;
}

#================================================================================
# TAVG
#================================================================================

#### Check if any of the yearly avg files are located on hsi
file yavg_hsi_list_exp;
file yavg_hsi_list_cntrl;

yavg_hsi_list_exp = Check_yavg_hsi(msroot,caseN,year0,year1,wrkdir);
yavg_hsi_list_cntrl = Check_yavg_hsi(cntrlmsroot,cntrlcaseN,cntrlyear0,cntrlyear1,wrkdir);

string yavgHSIfiles_exp[] = readData(yavg_hsi_list_exp);
string yavgHSIfiles_cntrl[] = readData(yavg_hsi_list_cntrl);

### Get yearlry files from hpss
file yavghsiComplete_exp[];
if (needtavg_exp == 1){
  yavghsiComplete_exp = hsi_files(yavgHSIfiles_exp,wrkdir,msroot,caseN,"year");
}

file yavghsiComplete_cntrl[];
if (needtavg_cntrl == 1){
  yavghsiComplete_cntrl = hsi_files(yavgHSIfiles_cntrl,wrkdir,cntrlmsroot,cntrlcaseN,"year");
}

### Create a list of yearly averages that need to be computed
file yavg_list_exp;
file yavg_list_cntrl;
yavg_list_exp = Check_yavg(yavghsiComplete_exp,caseN,wrkdir,year0,year1);
yavg_list_cntrl = Check_yavg(yavghsiComplete_cntrl,cntrlcaseN,wrkdir,cntrlyear0,cntrlyear1);

string yavgToCompute_exp[] = readData(yavg_list_exp);
string yavgToCompute_cntrl[] = readData(yavg_list_cntrl);

### Compute the yearly averages
file outfiles[];
file outfileTA <simple_mapper;prefix=@strcat(wrkdir,"tavg.",year0,".",year1,".nc")>;
file cntrloutfiles[];
file cntrloutfileTA <simple_mapper;prefix=@strcat(wrkdir,"tavg.",cntrlyear0,".",cntrlyear1,".cntrl.nc")>;

file outfileTAD;
file cntrloutfileTAD;

if (needtavg_exp == 1) {
  if (yavgToCompute_exp[0] != "ALL FOUND"){
    foreach yr in yavgToCompute_exp {
      int year = @toint(yr);
      file outfile<simple_mapper;prefix=@strcat(wrkdir,caseN,".pop.h.",yearprint(year),".nc")>;
      outfile = CalcTAVG(datapath, caseN, wrkdir, year,monhsiFileComplete);
      outfiles[year] = outfile;
      string fn = @strcat(caseN,".pop.h.",yearprint(year),".nc");
      if (cpy_hsi==1) {
        file save_ann_complete = store_file(outfile,msroot,caseN,"/ocn/proc/tavg/annual/",fn);
      }
    }
  } else {
    outfiles[0] = create_blank_file();
  }
}
if (needtavg_cntrl == 1) {
  if (yavgToCompute_cntrl[0] != "ALL FOUND"){
    foreach yr in yavgToCompute_cntrl {
      int year = @toint(yr);
      file cntrloutfile<simple_mapper;prefix=@strcat(wrkdir,cntrlcaseN,".pop.h.",yearprint(year),".nc")>;
      cntrloutfile = CalcTAVG(cntrldatapath, cntrlcaseN, wrkdir, year, cntrlmonhsiFileComplete);
      cntrloutfiles[year] = cntrloutfile;
      string fn = @strcat(cntrlcaseN,".pop.h.",yearprint(year),".nc");
      if (cpy_hsi==1) {
        file save_ann_complete = store_file(cntrloutfile,cntrlmsroot,cntrlcaseN,"/ocn/proc/tavg/annual/",fn);
      }
    }
  } else {
    cntrloutfiles[0] = create_blank_file();
  }
}

### Compute tavg file
if (needtavg_exp == 1) {
  outfileTA = Record_Average_Files(outfiles,@strcat(wrkdir,caseN,".pop.h.",yearprint(year0),".nc"),@strcat(test_nyrs,",4,1"));
} else {
  outfileTAD = create_blank_file();
}
if (needtavg_cntrl == 1) {
  cntrloutfileTA = Record_Average_Files(cntrloutfiles,@strcat(wrkdir,cntrlcaseN,".pop.h.",yearprint(cntrlyear0),".nc"),@strcat(cntrl_nyrs,",4,1"));
} else {
  cntrloutfileTAD = create_blank_file();
}

### TAVG Complete
file TAVG_exp_complete;
file TAVG_cntrl_complete;

if (needtavg_exp == 1) {
  TAVG_exp_complete = create_blank_file_f(outfileTA);
} else {
  TAVG_exp_complete = create_blank_file_f(outfileTAD);
}
if (needtavg_cntrl == 1) {
  TAVG_cntrl_complete = create_blank_file_f(cntrloutfileTA);
} else {
  TAVG_cntrl_complete = create_blank_file_f(cntrloutfileTAD);
}

#================================================================================
# MAVG
#================================================================================
#Compute mavg files
file mavgFile <simple_mapper;prefix=@strcat(wrkdir,"mavg.",year0,".",year1,".nc")>;
file mavgTFile <simple_mapper;prefix=@strcat(wrkdir,seasavgtemp)>;
file mavgSFile <simple_mapper;prefix=@strcat(wrkdir,seasavgsalt)>;
file mavgRFile;
file cntrlmavgFile <simple_mapper;prefix=@strcat(wrkdir,"cntrl.mavg.",cntrlyear0,".",cntrlyear1,".nc")>;
file cntrlmavgTFile <simple_mapper;prefix=@strcat(wrkdir,cntrlseasavgtemp)>;
file cntrlmavgSFile <simple_mapper;prefix=@strcat(wrkdir,cntrlseasavgsalt)>;
file cntrlmavgRFile;

file mavgFileD;
file mavgTFileD;
file mavgSFileD;
file cntrlmavgFileD;
file cntrlmavgTFileD;
file cntrlmavgSFileD;

file mavgT_complete_exp;
file mavgS_complete_exp;

if (need_clim_exp == 1){
  mavgFile = CalcMAVG(datapath, caseN, wrkdir, year0, year1, years_to_test,monhsiFileComplete);
## EXP TEMP
  if (need_clim_TEMP_exp == 1) {
    mavgTFile = ncks_var("TEMP",mavgFile);
    if (cpy_hsi==1) {
      file save_T_complete = store_file(mavgTFile,msroot,caseN,"/ocn/proc/tavg/monthly/",seasavgtemp);
    }
  } else {
    mavgTFileD = create_blank_file();
  }
## EXP SALT
  if (need_clim_SALT_exp == 1) {
    mavgSFile = ncks_var("SALT",mavgFile);
    if (cpy_hsi==1) {
      file save_S_complete = store_file(mavgSFile,cntrlmsroot,cntrlcaseN,"/ocn/proc/tavg/monthly/",seasavgsalt);
    }
  } else {
    mavgTFileD = create_blank_file();
  }
## Singal that temp and salt are complete
  if  (need_clim_TEMP_exp == 1){
    mavgT_complete_exp = create_blank_file_f(mavgTFile);
  } else {
    mavgT_complete_exp = create_blank_file_f(mavgTFileD);
  }
  if  (need_clim_SALT_exp == 1){
    mavgS_complete_exp = create_blank_file_f(mavgSFile);
  } else {
    mavgS_complete_exp = create_blank_file_f(mavgSFileD);
  }
## EXP RHO
  if (compute_rho == 1){
    mavgRFile = run_ncl(@strcat(nclpath,"/compute_rho.ncl"),mavgT_complete_exp,mavgS_complete_exp,caseN,cntrlvls,cpl,
     fluxobsfile,resolution,
     rhoobsfile,sobsfilefp,sshobsfile,sstobsfile,tavgfile,tobsfilefp,togataofile,windobsfile,year0,year1,wrkdir,
     ncarg_root,nclpath,ncarg_colormap_path,seasavgfile,seasavgrho,cntrlcaseN,cntrlyear0,cntrlyear1,seasavgtemp,seasavgsalt,
     cntrlfile,cntrlseasavgtemp,cntrlseasavgsalt, cntrlseasavgrho);
  } else {
    mavgRFile = create_blank_file();
  }
} else {
## Create blank files since they didn't need to be computed
  mavgFileD = create_blank_file();
  mavgTFileD = create_blank_file();
  mavgSFileD = create_blank_file();
  if (compute_rho == 1){
    mavgRFile = run_ncl(@strcat(nclpath,"/compute_rho.ncl"),mavgTFileD,mavgSFileD,caseN,cntrlvls,cpl,     
     fluxobsfile,resolution,
     rhoobsfile,sobsfilefp,sshobsfile,sstobsfile,tavgfile,tobsfilefp,togataofile,windobsfile,year0,year1,wrkdir,
     ncarg_root,nclpath,ncarg_colormap_path,seasavgfile,seasavgrho,cntrlcaseN,cntrlyear0,cntrlyear1,seasavgtemp,seasavgsalt,
     cntrlfile,cntrlseasavgtemp,cntrlseasavgsalt, cntrlseasavgrho);

  } else {
    mavgRFile = create_blank_file();
  }
}

file mavgT_complete_cntrl;
file mavgS_complete_cntrl;

if (need_clim_cntrl == 1){
  cntrlmavgFile = CalcMAVG(cntrldatapath, cntrlcaseN, wrkdir, cntrlyear0, cntrlyear1, cntrlyears_to_test, cntrlmonhsiFileComplete);
## CNTRL TEMP 
 if (need_clim_TEMP_cntrl == 1) {
    cntrlmavgTFile = ncks_var("TEMP",cntrlmavgFile);
    if (cpy_hsi==1) {
      file save_T_complete = store_file(cntrlmavgTFile,cntrlmsroot,cntrlcaseN,"/ocn/proc/tavg/monthly/",cntrlseasavgtemp);
    }
  } else {
    cntrlmavgTFile = create_blank_file();
  }
## CNTRL SALT
  if (need_clim_SALT_cntrl == 1) {
    cntrlmavgSFile = ncks_var("SALT",cntrlmavgFile);
    if (cpy_hsi==1) {
      file save_S_complete = store_file(cntrlmavgSFile,cntrlmsroot,cntrlcaseN,"/ocn/proc/tavg/monthly/",cntrlseasavgsalt);
    }
  } else {
    cntrlmavgSFile = create_blank_file();
  }
## Singal that temp and salt are complete
  if  (need_clim_TEMP_cntrl == 1){
    mavgT_complete_cntrl = create_blank_file_f(cntrlmavgTFile);
  } else {
    mavgT_complete_cntrl = create_blank_file_f(cntrlmavgTFileD);
  }
  if  (need_clim_SALT_cntrl == 1){
    mavgS_complete_cntrl = create_blank_file_f(cntrlmavgSFile);
  } else {
    mavgS_complete_cntrl = create_blank_file_f(cntrlmavgSFileD);
  }
## CNTRL RHO
  if (compute_cntl_rho == 1){
    cntrlmavgRFile = run_ncl(@strcat(nclpath,"/compute_rho_cntl.ncl"),mavgT_complete_cntrl,mavgS_complete_cntrl,cntrlcaseN,cntrlvls,cpl,     
     fluxobsfile,resolution,
     rhoobsfile,sobsfilefp,sshobsfile,sstobsfile,tavgfile,tobsfilefp,togataofile,windobsfile,year0,year1,wrkdir,
     ncarg_root,nclpath,ncarg_colormap_path,cntrlseasavgfile,cntrlseasavgrho,cntrlcaseN,cntrlyear0,cntrlyear1,cntrlseasavgtemp,cntrlseasavgsalt,
     cntrlfile,cntrlseasavgtemp,cntrlseasavgsalt, cntrlseasavgrho);

  } else {
    cntrlmavgRFile = create_blank_file();
  }
} else {
## Create blank files since they didn't need to be computed
  cntrlmavgFileD = create_blank_file();
  cntrlmavgTFileD = create_blank_file();
  cntrlmavgSFileD = create_blank_file();
  if (compute_cntl_rho == 1){
    cntrlmavgRFile = run_ncl(@strcat(nclpath,"/compute_rho_cntl.ncl"),cntrlmavgTFileD,cntrlmavgSFileD,cntrlcaseN,cntrlvls,cpl,     
     fluxobsfile,resolution,
     rhoobsfile,sobsfilefp,sshobsfile,sstobsfile,tavgfile,tobsfilefp,togataofile,windobsfile,year0,year1,wrkdir,
     ncarg_root,nclpath,ncarg_colormap_path,cntrlseasavgfile,cntrlseasavgrho,cntrlcaseN,cntrlyear0,cntrlyear1,cntrlseasavgtemp,cntrlseasavgsalt,
     cntrlfile,cntrlseasavgtemp,cntrlseasavgsalt, cntrlseasavgrho);

  } else {
    cntrlmavgRFile = create_blank_file();
  }
}

### Signal that MAVG is complete
file MAVG_exp_complete;
if (need_clim_exp == 1){
  MAVG_exp_complete = create_blank_file_f3(mavgT_complete_exp,mavgS_complete_exp,mavgRFile);
} else {
  MAVG_exp_complete = create_blank_file_f3(mavgTFileD,mavgSFileD,mavgRFile);
}

file MAVG_cntrl_complete;
if (need_clim_cntrl == 1){
  MAVG_cntrl_complete = create_blank_file_f3(mavgT_complete_cntrl,mavgS_complete_cntrl,cntrlmavgRFile);
} else { 
  MAVG_cntrl_complete = create_blank_file_f3(cntrlmavgTFileD,cntrlmavgSFileD,cntrlmavgRFile);
}

#================================================================================
# Remove monthly files
#================================================================================

foreach f in monHSIfiles{
  file rmComplete;
  rmComplete = removeMF(@strcat(wrkdir,f),outfiles,MAVG_exp_complete);
}
foreach f in cntrlmonHSIfiles{
  file rmComplete;
  rmComplete = removeMF(@strcat(wrkdir,f),cntrloutfiles,MAVG_cntrl_complete);
}

#================================================================================
# ZA
#================================================================================
file zataFile <simple_mapper;prefix=@strcat(wrkdir,"za_tavg.",year0,".",year1,".nc")>;
file tobsFileTemp1; 
file za_tobs <simple_mapper;prefix=@strcat(wrkdir,"za_",tobsfilefn)>;
file sobsFileTemp1;
file za_sobs <simple_mapper;prefix=@strcat(wrkdir,"za_",sobsfilefn)>;
file cntrlzataFile <simple_mapper;prefix=@strcat(wrkdir,"za_tavg.",cntrlyear0,".",cntrlyear1,".cntrl.nc")>;

file zataFileD;
file tobsFileTemp1D;
file za_tobsD;
file sobsFileTemp1D;
file za_sobsD;
file cntrlzataFileD;

if (needzavg_exp == 1){
  zataFile = zonal_average(outfileTA,@strcat("/",@filename(outfileTA)));
} else {
  zataFileD = create_blank_file();
}
if (needzavg_cntrl == 1) {
  cntrlzataFile = zonal_average(cntrloutfileTA,@strcat("/",@filename(cntrloutfileTA)));
} else {
  cntrlzataFileD = create_blank_file();
}

# Signal ZA is complete
file ZA_exp_complete;
if (needzavg_exp == 1) {
  ZA_exp_complete = create_blank_file_f(zataFile);
} else {
  ZA_exp_complete = create_blank_file_f(zataFileD);
}
file ZA_cntrl_complete;
if (needzavg_cntrl == 1) {
  ZA_cntrl_complete = create_blank_file_f(cntrlzataFile);
} else {
  ZA_cntrl_complete = create_blank_file_f(cntrlzataFileD);
}



#================================================================================
# NCL FILE LIST
#================================================================================
string ncl_files[] = readData(ncl_list);
file ncl_finished[];

if (doplots == 1){
  foreach f,i in ncl_files{
    ncl_finished[i] = ncl_wrapper(TAVG_exp_complete,TAVG_cntrl_complete,MAVG_exp_complete,MAVG_cntrl_complete,
     ZA_exp_complete,ZA_cntrl_complete,
     f,caseN,cntrlvls,cpl,fluxobsfile,resolution,
     rhoobsfile,sobsfilefp,sshobsfile,sstobsfile,tavgfile,tobsfilefp,togataofile,windobsfile,year0,year1,wrkdir,
     ncarg_root,nclpath,ncarg_colormap_path,seasavgfile,seasavgrho,cntrlcaseN,cntrlyear0,cntrlyear1,seasavgtemp,seasavgsalt,
     cntrlfile,cntrlseasavgtemp,cntrlseasavgsalt, cntrlseasavgrho);
  } 
}

#================================================================================
# Convert the image files
#================================================================================
file psFileList;

if (doplots == 1){
  psFileList = getFileList(ncl_finished,wrkdir);

  string psFiles[] = readData(psFileList);
  foreach f in psFiles{
    file convertFile; 
    convertFile = convertImages(wrkdir,f,diagrootpath); 
  } 
}
