function [nn,Vmod]=selstruc(V,c)
%SELSTRUC	Selects model structures according to various criteria
%
%	nn = selstruc(V,c)    or   [nn,Vm] = selstruc(V,c)
%
%	V: is a matrix containing information about different structures,
%	typically obtained as the output of ARXSTRUC or IVSTRUC.
%	
%	c: selects the criterion: c='PLOT' gives plots of the loss function
%	and (if applicable) the conditioning number from IVSTRUC as func-
%	tions of the number of estimated parameters. The user then selects the
%	number of parameters. 
%	Automatic choices of structures are obtained by c='AIC', which gives
%	Akaike's information theoretic criterion, while c='MDL' gives 
%	Rissanen's minimum description length criterion. If c is given a 
%	numeric value the structure is selected by minimization of
%	(1 + c*d/N)*Vd, where d is the number of estimated parameters,
%	Vd is the loss function of the corresponding model, and N is the
%	number of data. If c is omitted, PLOT is chosen.
%
%	nn: is returned as the chosen structure. The format is compatible
%	with the input format for ARX and IV4.
%	Vm: the first row of Vm contains the logarithms of the modified
%	criteria of fit. The remaining rows of Vm coincide with V.


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

if nargin<2,c='p';,end
if c<0,c='p';end
[nl1,nm1]=size(V);
nu=floor((nl1-2)/2);
Nc=V(1,nm1);
if c(1)=='a' | c(1)=='A',alpha=2;end
if c(1)=='m' | c(1)=='M', alpha=log(Nc);end
if norm(c(1)=='mMaApPlL')==0,alpha=c;end
if norm(c(1)=='PpLl')>0,clg,alpha=0;
	if nu>0,sv=sum(V(2:2+nu,1:nm1-1));else sv=V(2,1:nm1-1);end %Cor 9007
	vv=V(1,1:nm1-1);
	if c(1)=='l' |c(1)=='L', vv=log(vv);end
	kt=((2+2*nu)==nl1);
	if kt==1,subplot(111),else subplot(121),end
	axsv=[min(sv)-1 max(sv)+1];
	plot(sv,vv,'*',axsv,[max(vv) min(vv)],'.')
	xlabel('# of par`s'),
	if c(1)=='l' |c(1)=='L',ylabel('log of loss fcn'),
	else ylabel('loss fcn'),end
	if kt==0, subplot(122),plot(sv,V(nl1,1:nm1-1),'o',axsv,[min(V(nl1,1:nm1-1)) max(V(nl1,1:nm1-1))],'.')
		xlabel('# of par`s'),ylabel('log of cond`ing #'),end
	title('RETURN TO COMMAND SCREEN TO SELECT # OF PARAMETERS TO BE ESTIMATED')
	pause
	if exist('testall')
		pp=-1;
	else	
	pp=input('Enter # of parameters to be estimated ("enter" gives default): ');
	end
	if length(pp)>0 & pp>0,kk=find(sv==pp);
	if length(kk)==0, disp('This number of par`s is not available'),return,end
	[vm,skl]=min(V(1,kk));nn=V(2:2+2*nu,kk(skl))';
	end
end	
for kj=1:nm1-1
Vmod(1,kj)=V(1,kj)*(1+(alpha/Nc)*sum(V(2:nu+2,kj)));
end
Vmod(2:nl1,1:nm1-1)=V(2:nl1,1:nm1-1);

Vmod(1,1:nm1-1)=log(Vmod(1,1:nm1-1));
if length(nn)==0,[vm,sel]=min(Vmod(1,1:nm1-1));
nn=V(2:2+2*nu,sel)';end
set(gcf,'NextPlot','replace');

