%% daynum2.m calculates the day and month for the given day number and year.
%% 

function [day,month]=daynum2(dno,year)

% dno = day number
% year = year matrix
% day = day matrix
% month = month matrix

sz=size(dno);                                   %size of input
dno=dno(:);                                     %convert input to column vector
year=year(:);
lyc=rem(year,400)==0 | (rem(year,4)==0 & rem(year,100)~=0);     %check if leap year
day=zeros(sz);                                                  %day results matrix
month=day;                                                      %month results matrix

sv2=ones(1,13);

if any(~lyc)
 sv1=ones(length(dno(~lyc)),1);
 dv=[0 31 59 90 120 151 181 212 243 273 304 334 365];           %cumculative number of days in year
 mn1=sum(dno(~lyc)*sv2>sv1*dv,2);                               %month number in non-leap year 
 dy1=dno(~lyc)-dv(mn1)';                                        %day number in non-leap year
 month(~lyc)=mn1;                                               %record month number
 day(~lyc)=dy1;                                                 %record month number
end 

if any(lyc)
 sv1=ones(length(dno(lyc)),1);
 dv=[0 31 60 91 121 152 182 213 244 274 305 335 366];           %cumculative number of days in year
 mn1=sum(dno(lyc)*sv2>sv1*dv,2);                                %month number in leap year 
 dy1=dno(lyc)-dv(mn1)';                                         %day number in leap year
 month(lyc)=mn1;                                                %record month number
 day(lyc)=dy1;                                                  %record month number
end
