function [ucoef,vcoef]=tidecoef(ua,va,tt,range)
%function [ucoef,vcoef]=tidecoef(u,v,tt,range)
%        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.
%        RANGE is an optional argument to specify the number of bins to plot.
%        It should be a vector, for example, RANGE=[1:10] will fit bins
%        through 10.  If no range is specified, all the bins are fit.
%        COEFS has the mean in the first row, and cos and sin of each comp.

period=[12.42 6.21 4.14] 
if nargin==3   
  [mu,nu]=size(ua);
  range=[1:mu];
end
badfac=5;               %  cm/s s.d. from fit      Gayhead value 5
%badfac=2;	         %                          NBCS    value 2
tp=tp(:);
ntp=length(tp);
freq=(2.*pi)*ones(period)./period;
nfreq=length(freq);
uu=ua;
for repeat=1:2;             % do u and v
disp('badness:')
for nn=range,
   u=uu(nn,:);
   t=tt(nn,:);
   ind=find(u~=NaN);
   nind=length(ind);
   if nind>=9
      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] -----------------
       coef=A\u;
       badness=std(A*coef-u);

    else
       badness=999;
    end
    disp(badness)
    if badness>badfac
       coef=ones(2*nfreq+1,1)*NaN;
    end
    vcoef(nn,:)=coef';  
end

uu=va;
if repeat==1
      ucoef=vcoef;
end
end
