#### Build the ensemble predictions of tcf loss
TEMP<-"/home/karger/scratch/repj/"

INPUT<-"/mnt/storage/karger/cloudforest/Hansen_treecover_2020/"

for (year in 2001:20016)
{
  system(paste0("mkdir ",TEMP))
  
  in1<-paste0(INPUT,"GFC_v16_",year,"_mn_1k0000000000-0000000000.tif")
  in2<-paste0(INPUT,"GFC_v16_",year,"_mn_1k0000000000-0000032768.tif")
  
  outgrid<-paste0(TEMP,"temp1.sgrd")
  template="/mnt/storage/karger/cloudforest/Hansen_treecover_2020/sdms/template_treecover_latlong.sgrd"
  grids<-paste0("\"",in1,";",in2,"\"")
  sc<-paste0("saga_cmd grid_tools 3 -GRIDS=",grids," -NAME=Mosaic -TYPE=9 -RESAMPLING=0 -OVERLAP=1 -BLEND_DIST=10.000000 -BLEND_BND=0 -MATCH=0 -TARGET_DEFINITION=1 -TARGET_TEMPLATE=",template," -TARGET_OUT_GRID=",outgrid)
  system(sc)
  
  template2<-"/mnt/storage/karger/cloudforest/Hansen_treecover_2020/sdms/glm_bino_3.sgrd"
  outgrid2<-paste0(TEMP,"temp1.sgrd")
  sc<-paste0("saga_cmd pj_proj4 3 -CRS_PROJ4=\"+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\" -SOURCE=",outgrid," -RESAMPLING=0 -KEEP_TYPE=0 -TARGET_AREA=0 -TARGET_DEFINITION=0 -TARGET_TEMPLATE=",template2," -GRIDS=",outgrid2)
  system(sc)

  for (SDM in c("glm_bino_3","gam_3","glm_pois_3_0-1"))
  {
    sdm   <-paste0(INPUT,"sdms/",SDM,".sgrd")
    name1 <-paste0(SDM,"_",year)
    res1  <-paste0(TEMP,SDM,".sgrd")
    sc<-paste0("saga_cmd grid_calculus 1 -RESAMPLING=0 -FORMULA=a*b -NAME=",name1," -FNAME=0 -USE_NODATA=0 -TYPE=3 -GRIDS=",outgrid2," -XGRIDS=",sdm," -RESULT=",res1)
    system(sc)
  }
  
  meanout<-paste0(TEMP,"meanout.sgrd")
  sdout  <-paste0(TEMP,"sdout.sgrd")
  grids3<-paste0("\"",TEMP,"glm_bino_3.sgrd",";",TEMP,"gam_3.sgrd",";",TEMP,"glm_pois_3_0-1.sgrd","\"")
  sc<-paste0("saga_cmd statistics_grid 4 -GRIDS=",grids3," -RESAMPLING=0 -MEAN=",meanout," -STDDEV=",sdout)
  system(sc)
  
  regs<-paste0(INPUT,"sdms/cf_regions.sgrd")
  sc<-paste0("saga_cmd grid_calculus 1 -RESAMPLING=0 -FORMULA=a*b -FNAME=0 -USE_NODATA=0 -TYPE=3 -GRIDS=",meanout," -XGRIDS=",regs," -RESULT=",meanout)
  system(sc)
  
  regs<-paste0(INPUT,"sdms/cf_regions.sgrd")
  sc<-paste0("saga_cmd grid_calculus 1 -RESAMPLING=0 -FORMULA=a*b -FNAME=0 -USE_NODATA=0 -TYPE=3 -GRIDS=",sdout," -XGRIDS=",regs," -RESULT=",meanout)
  system(sc)
  
  outfile3<-paste0(INPUT,"tcf_ensemble_mn_",year,"_v16.tif")
  sc<-paste0("gdal_translate -ot Uint16 -of GTiff -co \"COMPRESS=DEFLATE\" -co \"PREDICTOR=2\" ",gsub(".sgrd",".sdat",meanout)," ",outfile3)
  system(sc)
  
  outfile3<-paste0(INPUT,"tcf_ensemble_sd_",year,"_v16.tif")
  sc<-paste0("gdal_translate -ot Uint16 -of GTiff -co \"COMPRESS=DEFLATE\" -co \"PREDICTOR=2\" ",gsub(".sgrd",".sdat",sdout)," ",outfile3)
  system(sc)
  
  system(paste0("rm -r ",TEMP))
}

