load ~/NC/grid
load ~/NC/OCNFRAC
year=1:150;
month=1:1800;

SST_temp=ncread('~/Aerosol_Variaiton/ERUN/read_nc/ncfile/read_nc_TS.nc','TS');

SST_MONTH=zeros(144,96,length(month));

% Deseasonal
for i=1:144
    for j=1:96
        for monthID=1:12
            temp=mean(SST_temp(i,j,monthID,:),4);
            for yearID=1:length(year)
                SST_temp(i,j,monthID,yearID)=SST_temp(i,j,monthID,yearID)-temp;
            end
        end
    end
end

% Change size
for i=1:144
    for j=1:96
        n=0;
        for yearID=1:length(year)
            for monthID=1:12
                n=n+1;
                SST_MONTH(i,j,n)=SST_temp(i,j,monthID,yearID);
            end
        end
    end
end


%Set fillValues
%for i=1:144
%    for j=1:96
%        if OCNFRAC(i,j)<0.95
%            SST_MONTH(i,j,:)=-999;
%        end
%    end
%end

save('SST_monthly.mat','SST_MONTH')

nccreate('SST_monthly.nc','Month','Dimensions',{'time',Inf},'Format','classic')
ncwrite('SST_monthly.nc','Month', month)
ncwriteatt('SST_monthly.nc','Month','long_name','Month')
nccreate('SST_monthly.nc','lat','Dimensions',{'lat',96},'Format','classic')
ncwrite('SST_monthly.nc','lat', lat)
ncwriteatt('SST_monthly.nc','lat','units','degrees_north')
ncwriteatt('SST_monthly.nc','lat','long_name','Latitude')
nccreate('SST_monthly.nc','lon','Dimensions',{'lon',144},'Format','classic')
ncwrite('SST_monthly.nc','lon', lon)
ncwriteatt('SST_monthly.nc','lon','units','degrees_east')
ncwriteatt('SST_monthly.nc','lon','long_name','Longitude')
nccreate('SST_monthly.nc','SST_MONTH','Dimensions',{'lon',144,'lat',96,'month',length(month)},'Format','classic')
ncwrite('SST_monthly.nc','SST_MONTH', SST_MONTH)
ncdisp('SST_monthly.nc')