function secs = to_seconds(year, month, day, hour, minute, second)
% function secs = to_seconds(year, month, day, hour, minute, second)
% or              to_seconds([year month day hour minute second])
%
% returns no. of seconds elapsed between given date and 0001/01/01 00:00:00
% year is 4-digit year!
% hour, minute, second are optional, set to 0 by default
% Input arguments may be column or row vectors.
% Output argument is a column vector.
%

% 93/02/10 JR
% 95/03/02 JR generalized test for leap year to work across century boundaries
% 95/12/03 EF and JH: converted to handle matrices or vectors.

[nr_year, nc_year] = size(year);
if (nargin > 1 & nargin < 3) | (nargin == 1 & nc_year < 3)
  help to_sec
  error('Insufficient argument list; need 1 or 3-6 arguments')
end

if (nargin == 1)
   n_secs = nr_year;
else
   n_secs = nr_year * nc_year;
end

hh = zeros(n_secs,1);   % optional args default
mm = hh;
ss = hh;
if nargin == 1  % vector form
  if nc_year > 3
    hh = year(:,4);
    if nc_year > 4
      mm = year(:,5);
      if nc_year > 5
        ss = year(:,6);
      end
    end
  end
  month = year(:,2);
  day   = year(:,3);
  year  = year(:,1);
else
  if nargin > 3 
    hh = hour(:);
    if nargin > 4 
      mm = minute(:);
      if nargin > 5 
        ss = second(:);
      end
    end
  end
  month = month(:);
  day   = day(:);
  year  = year(:);
end

if (  length(year) ~= n_secs | length(month) ~= n_secs ...
    | length(day)  ~= n_secs | length(hh)    ~= n_secs ...
    | length(mm)   ~= n_secs | length(ss)    ~= n_secs),
    help to_sec
    error('All input vectors must have same length');
end

c_norm= [0 31 59 90 120 151 181 212 243 273 304 334];
c_leap= [0 31 60 91 121 152 182 213 244 274 305 335];
nonleap_mask = ( rem(year, 4) > 0 | (rem(year,100) == 0 & rem(year,400) ~= 0) );
leap_mask = ~nonleap_mask;
cumdays = c_norm(month).' .* nonleap_mask + c_leap(month).' .* leap_mask;


year = year - 1;

secs = ss + ...
       60 * mm + ...
       3600 * hh + ...
       86400 * (day - 1 + ...
                cumdays + ...
		365 * year + fix(year/4) - fix(year/100) + fix(year/400));


