function coefs=tidef(uu,tt,period)
%function coefs=tidef(uu,tt,[period])
%        U and T are the matrices containing the variable to be fit in U, and
%        the associated times in T.  Each row of U should be a time series.
%
if nargin==2
     period=[12.42 6.21 4.14];        % can add 24 if interested
end
[mu,nu]=size(uu);
[mt,nt]=size(tt);
if mt==1 
   tt=ones(mu,1)*tt;
end
range=[1:mu];

freq=(2.*pi)*ones(period)./period;
nfreq=length(freq);
for nn=range
   u=uu(nn,:);
   if length(tt(:))==length(uu(:))
         t=tt(nn,:);
   else
         t=tt;
   end
   ind=find(u~=NaN);
   nind=length(ind);
   if nind>=length(freq)+2
      u=u(ind);
      t=t(ind);
      u=u(:);
      t=t(:);
%------ set up A -------
       A=zeros(nind,nfreq*2+1);
       A(:,1)=ones(nind,1);
       for j=[1:nfreq]
           A(:,2*j)=cos(freq(j)*t);
           A(:,2*j+1)=sin(freq(j)*t);
       end
%-------solve [A coeff = u] -----------------
       coefs(nn,:)=(A\u)';
end
end
