% calculates time series of 5 degree latitude bands for Hadcrut. Note that Hadcrut has 5 degree resolution centered at 2.5, 7.5, 12.5 etc.

clear all;
close all;

% load data from netcdf

ncfile='Z:\Google Drive\Parallels\Matlab\2016_Mann_templat\HadCRUT.4.4.0.0.median.nc';
% ncfile='/holocene/s1/smiller/gistemp/gistemp1200_ERSSTv4.nc';
ncid=netcdf.open(ncfile,'NC_NOWRITE');
varid = netcdf.inqVarID(ncid,'latitude');
lat=double(netcdf.getVar(ncid,varid));
varid = netcdf.inqVarID(ncid,'longitude');
lon=double(netcdf.getVar(ncid,varid));
varid = netcdf.inqVarID(ncid,'time');
time=double(netcdf.getVar(ncid,varid));
%varid = netcdf.inqVarID(ncid,'air');
varid= netcdf.inqVarID(ncid,'temperature_anomaly');
temp=double(netcdf.getVar(ncid,varid)); %% temp is lon,lat,time
netcdf.close(ncid);

% find replace missing temp values with NaN

temp(temp < -1000) = NaN;  % big negative values represent NaN in HadCRUT
% temp=temp*0.01; %% scale factor, non for HadCrut, results in degrees K

% convert time to datenumber

stime=datenum('1850-01-01');
time=time+stime;
month=str2num(datestr(time,'mm')); %% month number
year=str2num(datestr(time,'yyyy')); %% year

syear=min(year);
eyear=2015;
nyrs=eyear-syear+1;

% calculating 5 degree latitude bands centered on ilat for June, July, August
slat=22.5;
elat=77.5;
slatq=25;
elatq=75;

nlats=(elat-slat)/5.+1;

lattemp=NaN([nlats,nyrs]);

for iyr=syear:eyear 
   
   mtimes=find( (month == 7 | month == 8 | month == 6 ) & year == iyr); %find JJA for that year
   icount=0;
   
   for ilat=slat:5:elat 

    mlats=find(lat == ilat); % find lat band

    icount=icount+1
	lattemp(icount,iyr-syear+1)=nanmean(nanmean(nanmean(temp(:,mlats,mtimes)))); %% calculate mean for JJA iyr and latitude band and all longitudes
  
   end

end

% interpolate to desired spacing

lattemp_int=NaN(size(slatq:5:elatq,2),nyrs);

for n=1:size(lattemp,2)

lattemp_int(:,n)=interp1([slat:5:elat]',lattemp(:,n),[slatq:5:elatq]');

end

saveyr=[syear:eyear]';
savelat=[slatq:5:elatq];

save('HadCRUT_latband.mat','lattemp_int','saveyr','savelat');
bigMatrix=[saveyr,lattemp_int'];

save('HadCRUT_latband.txt','bigMatrix','-ascii');
