function y=convert(x,freq1,freq2,n);
%CONVERT  Change frequency of time series.
%         y=convert(x,freq1,freq2,n) converts the time series x of frequency
%         freq1 to the series y of frequency freq2. Here, frequency is the 
%         number of times sampling occurs per year.  Thus, freq=1 is the 
%         frequency for annual data, freq=4 for quarterly data and freq=12 
%         for monthly.    If freq1>freq2, then freq1/freq2 sample points 
%         from $x$ are averaged to obtain an element of y.  In some cases, 
%         the first element of y will be an average of fewer than freq1/
%         freq2 points.  For example, if we have monthly data on x for 
%         period 47:02-75:11 and want y quarterly, then only x(47:02) and 
%         x(47:03) should be used to obtain the 1st quarter, y(47:1). The
%         input n is the number of data points in x to be used to obtain
%         y(1), where n<=freq1/freq2.  In our example, n=2.    If freq1<
%         freq2, then x is log-linearly interpolated to get y.  In this
%         case, n<=freq2/freq1 is the integer indicating which subperiod
%         of y is assigned the elements of x.  For example, if x is annual
%         and y quarterly, then n indicates the quarter which is assigned
%         the annual values.  If n=3, y(3)=x(1), y(7)=x(2), etc., and the
%         other y(i)'s are obtained by interpolation.
%
%         y=convert(x,freq1,freq2) can be used when n=max(freq1/freq2,
%         freq2/freq1).

%         Ellen R. McGrattan,  6-12-87
%         Revised, 7-3-89, ERM
%
if freq1==freq2; error('Specify a NEW frequency for your data'); end;
if nargin<4; n=max(freq1/freq2,freq2/freq1); end;
l=length(x);
if freq1>freq2;
  ratio=freq1/freq2;
  y(1,1)=sum(x(1:n))/n;
  m=fix((l-n)/ratio);
  tem=zeros(ratio,m);
  tem(:)=x(n+1:m*ratio+n);
  y(2:m+1,1)=sum(tem)'/ratio;
  if l-m*ratio-n;
    y(m+2,1)=sum(x(m*ratio+n+1:l))/(l-m*ratio-n);
  end;
else;
  ratio=freq2/freq1;
  lx=log(x);
  ly=zeros(l*ratio,1);
  ly([n:ratio:ratio*l])=lx;
  for i=1:ratio-1;
    for j=i+n:ratio:ratio*(l-1)+n-1;
      ly(j,1)=ly(j-i,1)*(1-i/ratio)+ly(j-i+ratio,1)*i/ratio;
    end;
  end;
  if n>1;
    beta=ols([ones(5,1),time(5)],ly(n:n+4,1));
    ly(1:n-1,1)=beta(1)+beta(2)*[-n+2:1:0]';
  end;
  if n<ratio;
    beta=ols([ones(10,1),time(10)],ly((l-1)*ratio+n-9:(l-1)*ratio+n,1));
    ly(ratio*(l-1)+n+1:ratio*l)=beta(1)+beta(2)*[11:11+ratio-n-1]';
  end;
  y=exp(ly);
end;
