year=2001:2014;
month=1:168;
lat=ncread('/Users/yangyang/Aerosol_Variaiton/IRUN/PRECT/dat/precip.mon.mean.nc','lat');
lon=ncread('/Users/yangyang/Aerosol_Variaiton/IRUN/PRECT/dat/precip.mon.mean.nc','lon');

PRECT_temp2=ncread('/Users/yangyang/Aerosol_Variaiton/IRUN/PRECT/dat/precip.mon.mean.nc','precip');
PRECT_temp=PRECT_temp2(:,:,265:432);

PRECT=zeros(144,72,12,14);
PRECT_MONTH=zeros(144,72,length(month));


for i=1:144
    for j=1:72
        n=0;
        for yearID=1:14
            for monthID=1:12
                n=n+1;
                PRECT(i,j,monthID,yearID)=PRECT_temp(i,j,n);
            end
        end
    end
end
        
        
% Deseasonal
for i=1:144
    for j=1:72
        for monthID=1:12
            temp=mean(PRECT(i,j,monthID,:),4);
            for yearID=1:14              
                PRECT(i,j,monthID,yearID)=PRECT(i,j,monthID,yearID)-temp;
            end
        end
    end
end


% Change size
for i=1:144
    for j=1:72
        n=0;
        for yearID=1:14
            for monthID=1:12
                n=n+1;
                PRECT_MONTH(i,j,n)=PRECT(i,j,monthID,yearID);
            end
        end
    end
end

save('PRECT_CMAP_monthly.mat','PRECT_MONTH')

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