load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/shea_util.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/popRemap.ncl"     

    begin
     setfileoption("nc","Format","LargeFile")

	 homedir = "/glade/work/leishanj/CESM1_2_2/sst_flow/sst/ssta/year"
	 system("/bin/mkdir ./day")
	 system("/bin/cp /glade/work/leishanj/CESM1_2_2/sst_flow/map*.nc ./")
	 ; ---- model climatological daily sst ----
     f2 = addfile("/glade/work/leishanj/CESM1_2_2/make_modclim/B2000_ctrl/SST.B2000_ctrl.clmmean.daily.19700101-19801231.nc","r")  ; model climatology
     sst_modclm = f2->SST
	 printVarSummary(sst_modclm)

     do i = 1970 , 2018 ;2017 ;1978 ;1950 , 2016
	 print(i*1.0)
	    a = addfile(homedir+"/year."+i+".nc","r")     ; observational anomaly -- year.*.nc use cdo splityear to make this
		sst0 = a->sst  ; latitude has to be from south to north
		sst0@_FillValue = sst_modclm@_FillValue
		sst0@missing_value = sst_modclm@_FillValue

	    remap = (/PopLatLon(sst0,"1x1d","gx1v6","bilin","da","100716")/)
		remap@_FillValue = sst_modclm@_FillValue
		remap@missing_value = sst_modclm@missing_value
		
		sst_total = remap + sst_modclm
		copy_VarMeta(sst_modclm,sst_total)
		printVarSummary(sst_total)
        sst_total!0 = "time"
        sst_total!1 = "y"
        sst_total!2 = "x"
        sst_total@long_name = "Surface Potential Temperature"
        sst_total@units = "degC"
        sst_total@coordinates =  "TLONG TLAT"
        sst_total@grid_loc =  "3111"    
		sst_total@_FillValue = sst_modclm@_FillValue
		sst_total@missing_value = sst_modclm@missing_value
		; print(sst_total(0,150:160,140:150))
		do jj = 0 , 364
		   j  = jj + 1
		   if (j.lt.10)then
              ddd = "00"+j
           end if
           if (j.ge.10.and.j.lt.100)then
               ddd = "0"+j
           end if
           if (j.ge.100)then
               ddd = j
           end if
		system("/bin/rm -f "+"./day/sst."+i+"."+ddd+".12."+"nc")
        nf = addfile("./day/sst."+i+"."+ddd+".12."+"nc", "c")
        nf->sst=sst_total(jj,:,:)
		end do
	 end do
    end
