
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%-------------------------------------------------------------------------%
%                   'mon_to_ann.m', NATHAN STEIGER, JAN 2013
%-------------------------------------------------------------------------%
%  This function computes the annual average given monthly data and months
%  over which to compute the annual average (e.g. Jan-->Dec or Jun-->Jul).
%  It also requires that each year has 12 months worth of values (e.g., one
%  year cannot skip the month of December) and that the original data, 
%  'data_mon' starts in Jan and goes through to the end of December.
%-------------------------------------------------------------------------%
% Input:
%   data_mon = monthly data (lat,lon,months) or for a single time series
%   smon = starting month to average (1=Jan, 2=Feb, etc.)
%   emon = ending month to average (12=Dec, 11=Nov, etc.)
% Output:
%   data_ann = annual data (lat,lon,yrs)
%-------------------------------------------------------------------------%

function [data_ann]=mon_to_ann(data_mon,smon,emon)

% Check data type
num_dims=ndims(data_mon);

if num_dims==2
    
    % Determine size of data created above
    numMonths=length(data_mon);
    yrs=numMonths/12;
    
    % Correct number of yrs if end < start (e.g. avg over Jul-->Jun)
    if smon > emon
        emon=emon+12;
        yrs=yrs-1;
    end
    
    j=smon; % start month
    n=emon; % end month
    data_ann=zeros(yrs,1);
    for q=1:yrs
        
        data_ann(q)=nansum(data_mon(j:n))/length(j:n);
        j=j+12;
        n=n+12;
        
    end
    
elseif num_dims==3
    
    % Determine size of data created above
    [xlat,xlon,numMonths]=size(data_mon);
    yrs=numMonths/12;
    
    % Correct number of yrs if end < start (e.g. avg over Jul-->Jun)
    if smon > emon
        emon=emon+12;
        yrs=yrs-1;
    end
    
    j=smon; % start month
    n=emon; % end month
    data_ann=zeros(xlat,xlon,yrs);
    for q=1:yrs
        
        data_ann(:,:,q)=nansum(data_mon(:,:,j:n),3)/length(j:n);
        j=j+12;
        n=n+12;
        
    end
    
elseif num_dims>3
    error('Dimensions of monthly data not correct')
end

