function TH=ivar(y,na,nc,maxsize,T)
%IVAR	Computes IV-estimates for the AR-part of a scalar time series
%
%	TH = ivar(Y,NA)
%
%	TH: returned as the IV-estimate of the AR-part of a time series
%	model
%	A(q) y(t) =  v(t)
%	along with relevant structure information. (See HELP THETA for
%	the exact structure of TH.
%
%	Y : the time series as a column vector.
%
%	NA: the order of the AR-part (the A(q)-polynomial)
%	
%	In the above model v(t) is an arbitrary process, assumed to be a
%	(possibly time-varying) moving average process of order NC. The
%	default value of NC is NA. Other values of NC are obtained by
%	TH = ivar(Y,NA,NC)
% 	
%	With
%	TH = ivar(Y,NA,NC,maxsize,T)
%	access to some parameters associated with the algorithm is obtained.
%	See HELP AUXVAR for an explanation of these.

%	L. Ljung 4-21-87
%	Copyright (c) 1987-90 by the MathWorks, Inc.
%	All Rights Reserved.

[Ncap,nz]=size(y); 

% 
% *** Some initial tests on the input arguments ***
%
maxsdef=idmsize(Ncap);

if nargin<5, T=1;end
if nargin<4, maxsize=maxsdef;end
if nargin<3, nc=na;end
if T<0,T=1;end, if maxsize<0,maxsize=maxsdef;,end,if nc<0,nc=na;end
if isempty(T),T=1;end,if isempty(maxsize),maxsize=maxsdef;end,
if isempty(nc),nc=na;end
if nz>Ncap,y=y';end
if nz>1,error('The data should be a single time series!'),return,end
if length(na)>1,error(' NA should be a single number!'),return,end

% *** Estimate a C-polynomial by first building a high order AR-model and
%     then using the corresponding residuals as inputs in an ARX-model ***

ar=arx(y,na+nc,maxsize,T,0);
e=filter([1 ar'],1,y);
ac=arx([y e],[na nc 1],maxsize,T,0);
c=fstab([1 ac(na+1:na+nc)']);

% *** construct instruments ***

     x=[zeros(nc,1);y(1:Ncap-nc)];
     cc=conv(c,c);
     x=filter(1,cc,x);
     TH=ivx(y,na,x,maxsize,T);
     V=e'*e/Ncap;
     yf=filter(1,c,y);
     ef=filter(1,c,e);
     M=floor(maxsize/(na+nc));
     R=zeros(na+nc);
     for k1=max(na,nc):M:Ncap-1
     	jj=(k1+1:min(Ncap,k1+M));
	psi=zeros(length(jj),na+nc);
	for k=1:na, psi(:,k)=yf(jj-k);end
	for k=1:nc, psi(:,na+k)=ef(jj-k);end
	R=R+psi'*psi;
     end
     P=V*inv(R);
     TH(1,1)=V; TH(2,1)=V*(1+na/Ncap)/(1-na/Ncap);
     TH(4:3+na,1:na)=P(1:na,1:na);
	TH(2,7)=10;
