% calculates time series of land surface temp at latitude bands.

 %clear all;  % remove commentout for independent use
 %close all;

% model = ('MRI-CGCM3     ');
% nruns = 1;
% pval = 2;

%for r=1:nruns

%    if strcmp(deblank(model),'MRI-CGCM3') == 1 & pval == 2  % special case
%        r = 5
%    end

    % get files for each run
    files=dir([deblank(model),'*.nc']);
    
    % number of files for each run
    nfiles=size(files,1);

    % check to make sure that there are files
    if (nfiles > 0)

        % loop over files
        for ifil=1:nfiles
        inpfile=(['/crane/s1/smiller/CMIP5/1pctCO2/ua/',files(ifil).name]);
       
        % load data from netcdf
        
        ncid=netcdf.open(inpfile,'NC_NOWRITE');

        % read lat, lon, tas, time variables
        
        varid = netcdf.inqVarID(ncid,'lat');
        lat=double(netcdf.getVar(ncid,varid));
        varid = netcdf.inqVarID(ncid,'lon');
        lon=double(netcdf.getVar(ncid,varid));
        varid = netcdf.inqVarID(ncid,'ua');
        ua=double(netcdf.getVar(ncid,varid));
        varid = netcdf.inqVarID(ncid,'time');
        time=double(netcdf.getVar(ncid,varid));
        tunits = netcdf.getAtt(ncid,varid,'units');
        varid = netcdf.inqVarID(ncid,'plev');
        plev=double(netcdf.getVar(ncid,varid));

	i300=find(plev==30000);
	tas=squeeze(ua(:,:,i300,:));

        % convert time to datenumber
        
        targdate=datenum(tunits(12:end),'yyyy-mm-dd');

        %targyr=str2num(tunits(12:15));
        if isempty(targdate) == 1;
        targdate=datenum(tunits(12:20));  % some model dates are 3 digits
        end
        time=targdate+time;
        month=str2num(datestr(time,'mm')); %% month number
        year=str2num(datestr(time,'yyyy')); %% year
        
        % close file
        netcdf.close(ncid);
        
        %concatenate time and tas into one big happy matrix.
            if (exist('wtas'))
                wtime=cat(1,wtime,time);
                wmonth=cat(1,wmonth,month);
                wyear=cat(1,wyear,year);
                wtas=cat(3,wtas,tas);
                
            else
                wtime=time;
                wmonth=month;
                wyear=year;
                wtas=tas;
            end %exist wtime

        end %for ifil

        modelonly=model(strfind(model,'Amon_')+5:end);
        
        if (strcmp(modelonly,'HadGEM2-ES_1pctCO2_r1i1p1_'))
         wtime=wtime(2:end);  %% weirdly this model starts in December 1, 1859
         wmonth=wmonth(2:end);
         wyear=wyear(2:end);
         tas=wtas(:,:,2:end);            
        end
         lasty=max(wyear);
         nyr=length(wtime)./12;
         year = repmat([lasty-nyr+1:lasty],12,1);  % this is a patch, the above code for time variables doesn't work for all models
         year = reshape(year,size(year,1)*size(year,2),1);
         month=[1:12]';
         month=repmat(month,nyr,1);
         tas=wtas;
        
        clear wtime wmonth wyear wtas;
% 
%         if strcmp(deblank(model),'HadCM3') == 1 || strcmp(deblank(model),'HadGEM2-AO') == 1 || strcmp(deblank(model),'HadGEM2-CC') == 1|| strcmp(deblank(model),'HadGEM2-ES') == 1
%             month=[1:12]';
%             month=repmat(month,146,1);
%             month1=12;
%             month=cat(1,month1,month);
%             year = repmat([1860:2005],12,1);
%             year = reshape(year,1752,1);
%             year = cat(1,1859,year);
%         end
% 
%         if strcmp(deblank(model),'HadGEM2-AO') == 1
%             month=[1:12]';
%             month=repmat(month,146,1);
%             year = repmat([1860:2005],12,1);
%             year = reshape(year,1752,1);
%         end
% 
%         if strcmp(deblank(model),'FGOALS-g2') == 1 & r == 2
%             month=[1:12]';
%             month=repmat(month,106,1);
%             year = repmat([1900:2005],12,1);
%             year = reshape(year,1272,1);
%         elseif strcmp(deblank(model),'FGOALS-g2') == 1
%             month=[1:12]';
%             month=repmat(month,156,1);
%             year = repmat([1850:2005],12,1);
%             year = reshape(year,1872,1);
%         end

        % find replace missing temp values with NaN

        temp=tas;
        temp(temp > 1000) = NaN;

        % define nyrs

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

        % calculating 5 degree latitude bands centered on ilat for June, July, August
        slat=25;
        elat=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-2.5) & lat <= (ilat+2.5) ); % 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
        saveyr=[syear:eyear]';
        savelat=[slat:5:elat];
        bigMatrix=[saveyr,lattemp'];
    
        
        modelonly=model(strfind(model,'Amon_')+5:end);
        %only keep first 151 years
        if (eyear-syear > 150)
            saveyr=saveyr(1:151);
            lattemp=lattemp(:,1:151);
            bigMatrix=bigMatrix(1:151,:);
        end
        save(['/holocene/s0/scratch/smiller/1pctCO2/',modelonly,'ua_latband_1pctCO2.mat'],'lattemp','saveyr','savelat','bigMatrix');
        clear saveyr savelat bigMatrix lattemp time month year tas
    else
        disp('no files')
        clear saveyr savelat bigMatrix lattemp time month year tas
    end % for (nfiles > 0)
    
%     saveyr=[syear:eyear]';
%     savelat=[slat:5:elat];
%     bigMatrix=[saveyr,lattemp'];
%     
%     save(['/holocene/s0/scratch/smiller/rcp85_test/',deblank(model),'_r',num2str(r),'i1p',num2str(pval),'_tas_latband_rcp85.mat'],'lattemp','saveyr','savelat','bigMatrix');
% 
%end
