%% daynum31.m is desgined to be called by daynum3.m
%%

function [dnon,yearn]=daynum31(dno,year,dc)

% dno = original day number
% year = original year number
% dc = number of days to change by
% 
% dnon = new day number
% yearn = new year number

dnon=dno+dc;                                                    %new day number
yearn=year;                                                     %new year number

lyc=rem(year,400)==0 | (rem(year,4)==0 & rem(year,100)~=0);     %check if leap year
upl=365*ones(size(dno));                                        %upper day number limit
upl(lyc)=366;                                                   %change upper limit if leap year

ulc=dnon>upl;                                                   %upper limit check
if any(any(ulc));                                               %if any day numbers greater than upper limit for year
 dnon(ulc)=dnon(ulc)-upl(ulc);                                  %correct day number
 yearn(ulc)=year(ulc)+1;                                        %increase year by one
end

llc=dnon<1;                                                                     %lower limit check
if any(any(llc));                                                               %if any day numbers less than one
 yearn(llc)=year(llc)-1;                                                        %decrease year by one
 lyc2=rem(yearn(llc),400)==0 | (rem(yearn(llc),4)==0 & rem(yearn(llc),100)~=0); %check if leap year
 upl2=365*ones(sum(sum(llc)),1);                                                %upper day number limit
 upl2(lyc2)=366;                                                                %change upper limit if leap year
 dnon(llc)=dnon(llc)+upl2;                                                      %correct day number  
end
