function goto_ws=iduiarx(arg,nnu,nny,onoff,nustr,nystr)
%IDUIARX Handles everything about ARX estimation in the ident GUI.
%	Arguments 
%	open     Opens up the arxstruc window
%	arx,iv   Handles the corresponding radio buttons
%	orders   Handles any changes in the order popups
%	ordedit  Handles changes in the model structure edit box
%	mname    Manages the Modelname box
%	estimate Handles the estimation phase
%	specsel  Callback for ARX choices in the SELSTRUC plot
%	comp     Callback for the best choice with given number of pars
%	close    Closes the dialog box

%	L. Ljung 4-4-94
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.13 $  $Date: 1995/05/11 14:07:19 $

global XIDarx XIDparest XIDmse XIDmen XIDplotw  XIDlayout XIDhw XIDio
global XIDcounters
usd=get(XIDhw(3,1),'userdata');nu=usd(1);ny=usd(2);
if strcmp(arg,'open')
   V=nnu;
   if isempty(iduiwok(9))
       iduistat('Opening plot window ...')
       layout
       
       butwh=[mStdButtonWidth mStdButtonHeight];
       butw=butwh(1);buth=butwh(2);
       ftb=mFrameToText;  % Frame to button
       bb = 4; % between buttons
       etf = mEdgeToFrame;
       fig=idbuildw(9); XIDplotw(9,1)=fig;
       set(fig,'units','pixels');
       FigWH=get(fig,'pos');FigWH=FigWH(3:4);
       lev1=max(0,(FigWH(2)-9*buth-8*bb)/2);
       pos = iduilay1([butw+2*ftb],9,9,lev1,bb);
       pos=pos+[(FigWH(1)-pos(1,1)-pos(1,3)-etf)*ones(10,1),zeros(10,3)];
       if strcmp(get(0,'blackandwhite'),'on'),BW=1;else BW=0;end
       s1='iduipoin(1);';s2=iduipoin(1);'iduistat(''Compiling ...'');';
       s3='iduipoin(3);';
       uicontrol(fig,'pos',pos(1,:),'style','frame');
       uicontrol(fig,'Pos',pos(10,:),'style','push','callback',...
          'iduihelp(''selordax.hlp'',''Help: Choice of ARX Structure'');'...
         ,'string','Help');
       uicontrol(fig,'Pos',pos(9,:),'style','push','callback',...
          'set(gcf,''vis'',''off'');','string','Close');
       uicontrol(fig,'Pos',pos(8,:),'style','push','callback',...
          [s1,'iduiarx(''insert'');',s3],'string','Insert');

      uicontrol(fig,'pos',pos(7,:)+[0 0 -2*butw/3 0],'style','text',...
                'string','nk=','horizontalalignment','right');
      uicontrol(fig,'pos',pos(7,:)+[butw/3 0  -butw/3 0],'style','text',...
                'tag','nk','horizontalalignment','left');
      uicontrol(fig,'pos',pos(6,:)+[0 0 -2*butw/3 0],'style','text',...
                'string','nb=','horizontalalignment','right');
      uicontrol(fig,'pos',pos(6,:)+[butw/3 0  -butw/3 0],'style','text',...
                'tag','nb','horizontalalignment','left');
      uicontrol(fig,'pos',pos(5,:)+[0 0 -2*butw/3 0],'style','text',...
                'string','na=','horizontalalignment','right');
      uicontrol(fig,'pos',pos(5,:)+[butw/3 0  -butw/3 0],'style','text',...
                'tag','na','horizontalalignment','left');
      uicontrol(fig,'pos',pos(4,:)+[0 0 -2*butw/3 0],'style','text',...
                'string','Fit=','horizontalalignment','right');
      uicontrol(fig,'pos',pos(4,:)+[butw/3 0 -butw/3 0],'style','text',...
                'tag','fit','horizontalalignment','left');
      uicontrol(fig,'pos',pos(3,:),'style','edit',...
                'string','','backgroundcolor','w','Horizontalalignment','left',...
                'callback',[s1,'iduiarx(''comp'');',s3],'tag','nupar');
      uicontrol(fig,'pos',pos(2,:),'style','text',...
                'string','# of par''s','HorizontalAlignment','left');

     handl=findobj(fig,'type','uicontrol');
     set(handl,'unit','norm')
     if length(XIDlayout)>8,if XIDlayout(9,3)
       eval('set(fig,''pos'',XIDlayout(9,1:4))','')
     end,end
     end % end create window
     % Plot data
[nl1,nm1]=size(V);
zvnorm=V(2,nm1);
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);bestfit=min(vv);
kt=((2+2*nu)==nl1);
Ind=[];
nopar=min(sv):max(sv);
msv=min(sv);
y=zeros(size(nopar));
for kk=nopar
   inx=find(sv==kk);
   if ~isempty(inx)
     [mv,index]=min(vv(inx));Ind=[Ind,inx(index)];
     y(kk-msv+1)=100*mv/zvnorm;
   else
     y(kk-msv+1)=0;
   end
end
V=[[V(:,Ind);sv(Ind)],[V(:,nm1);0]];sv=sv(Ind);vv=vv(Ind);
           handax=get(XIDplotw(9,1),'Userdata');
           set(handax(3),'vis','off'),axes(handax(3)),cla,axis('auto')
           set(XIDplotw(9,3),'userdata',V)
	axsv=[min(sv)-1 max(sv)+1];
        [xx,yy]=bar(nopar,y);
        barbottom=floor(10*bestfit/zvnorm)*10;
        zer=find(yy==0);
        yy(zer)=barbottom*ones(size(zer));
        line(xx,yy,'color','y');
       nndef=selstruc(V,0);
       nnaic=selstruc(V,'aic');
       nnmdl=selstruc(V,'mdl');
       ndef=sum(nndef(1:1+nu))-msv+1;naic=sum(nnaic(1:1+nu))-msv+1;
       nmdl=sum(nnmdl(1:1+nu))-msv+1;
       if nmdl>1,
          patch(xx(1:5*nmdl-3),yy(1:5*nmdl-3),'y');
       end
       patch(xx(5*nmdl-3:5*nmdl),yy(5*nmdl-3:5*nmdl),'g');
       if naic>nmdl+1
           patch(xx(5*nmdl:5*naic-3),yy(5*nmdl:5*naic-3),'y');
       end
       patch(xx(5*naic-3:5*naic),yy(5*naic-3:5*naic),'b');
       if ndef>naic+1
           patch(xx(5*naic:5*ndef-3),yy(5*naic:5*ndef-3),'y');
       end
       patch(xx(5*ndef-3:5*ndef),yy(5*ndef-3:5*ndef),'r');
       nxx=length(xx);
       if 5*ndef<nxx
           patch(xx(5*ndef:nxx),yy(5*ndef:nxx),'y');
       end
        set(handax(3),'vis','on')
     yl=get(handax(3),'ylim');ylen=length(y);ym=max(y(ceil(ylen/3):ylen));
     if ym>0.6*yl(2)
        set(handax(3),'ylim',[yl(1) ym/0.55])
     end
     iduital(9);
     if nmdl==ndef
        colm='Red: ';
     elseif nmdl==naic
        colm='Blue: ';
     else
        colm='Green: ';
     end
     if naic==ndef
        cola='Red: ';
     else
        cola='Blue: ';
     end
     text(0.97,0.75,'Red: Best Fit','units','norm','fontsize',10,...
          'Horizontalalignment','right')
     text(0.97,0.85,[cola,'AIC Choice'],'units','norm','fontsize',10,...
          'Horizontalalignment','right')
     text(0.97,0.95,[colm,'MDL Choice'],'units','norm','fontsize',10,...
          'Horizontalalignment','right')
     set(XIDplotw(9,1),'vis','on')
     set(findobj(XIDplotw(9,1),'tag','nupar'),'string',...
                        int2str(sum(nndef(1:1+nu))));
     iduiarx('comp')


elseif strcmp(arg,'arx')
   set(XIDarx(1,2),'value',1);
   set(XIDarx(1,5),'value',0);
   iduiarx('mname');
elseif strcmp(arg,'iv')
   set(XIDarx(1,5),'value',1);
   set(XIDarx(1,2),'value',0);
   iduiarx('mname');
elseif strcmp(arg,'orders')

   if ny>1
      na=get(XIDio(1,4),'value')-1;
      if nu>0
         nb=get(XIDio(1,1),'value')-1;
         nk=get(XIDio(1,3),'value')-1;
         nys=int2str(ny);nus=int2str(nu);
         nnstr=['[',int2str(na),'*ones(',nys,',',nys,') ',...
              int2str(nb),'*ones(',...
           nys,',',nus,') ',int2str(nk),'*ones(',nys,',',nus,')]'];
      else
         nys=int2str(ny);nus=int2str(nu);
         nnstr=['[',int2str(na),'*ones(',nys,',',nys,')]'];
      end     
      set(XIDparest(3),'string',nnstr);
      iduiarx('mname');
      return
   end
   na=get(XIDio(1,4),'value')-1;
   if na==10,
      na=get(XIDio(1,4),'UserData');
      if isempty(na),na=10;end
      nnstr=int2str(na);
   elseif na==11
      nnstr='1:5';
   elseif na==12
      nnstr='1:10';
   else
      nnstr=int2str(na);
   end
   if nu>1,
      nnstr=[nnstr,' ['];nkstr='[';
   else 
      nnstr=[nnstr,' '];nkstr=' ';
   end
   for ku=1:nu
     nb=get(XIDio(ku,1),'value')-1;
     if nb==10
        nb=get(XIDio(ku,1),'UserData');
        if isempty(nb),nb=10;end
        nbstr=int2str(nb);
     elseif nb==11
        nbstr='1:5';
     elseif nb==12
        nbstr='1:10';
     else
        nbstr=int2str(nb);
     end
     nk=get(XIDio(ku,3),'value')-1;
     if nk==10
        nk=get(XIDio(ku,3),'UserData');
        if isempty(nk),nk=10;end
        nkstrt=int2str(nk);
     elseif nk==11
        nkstrt='1:5';
     elseif nk==12
        nkstrt='1:10';
     else
        nkstrt=int2str(nk);
     end
     nbv(ku)=nb;nkv(ku)=nk;
     nnstr=[nnstr,' ',nbstr];nkstr=[nkstr,' ',nkstrt];
   end
   if nu>1,nnstr=[nnstr,'] ',nkstr,']'];else nnstr=[nnstr,nkstr];end
   set(XIDparest(3),'string',nnstr);
   iduiarx('mname');
elseif strcmp(arg,'ordedit')

   sl1=get(XIDparest(3),'string');
   if ~any(sl1==':'),
   stopp=0;
   eval('nn=eval([''['',sl1,'']'']);','stopp=1;');
   if stopp,iduiarx('mname');return,end
   [nnr,nnc]=size(nn);
   if nnc~=2*nu+ny|nnr~=ny
      errordlg('Incorrect number of orders specified.');
   else   
      na=nn(1,1);nb=nn(1,2:nu+1);nk=nn(1,nu+2:2*nu+1);
      if nu>4|ny>1,nmu=min(1,nu);else nmu=nu;end
      set(XIDio(1,4),'value',min(na+1,11),'UserData',na);
      for ku=1:nmu
         set(XIDio(ku,1),'value',min(nb(ku)+1,11),'UserData',nb(ku));
         set(XIDio(ku,3),'value',min(nk(ku)+1,11),'UserData',nk(ku));
      end
   end
   end
elseif strcmp(arg,'mname')
   method='arx';
   eval('if get(XIDarx(1,2),''value'')==0,method=''iv'';end','')
   goto_ws=0;
   sl1=get(XIDparest(3),'string');
   if any(sl1==':')
       mname='';
   else
       eval('nn=eval([''['',sl1,'']'']);','goto_ws=1;');
       if goto_ws==0
          if length(nn)~=ny+2*nu
             errordlg('Incorrect number of orders specified.');
             goto_ws=1;return
          end
          if nu==0
             ordstr=int2str(nn(1,1));
          else
             ordstr=[int2str(nn(1,1)),int2str(nn(1,ny+1)),...
                int2str(nn(1,ny+nu+1))];
          end
          mname=[method,ordstr];
       else
          mname=sl1;
       end
   end
   set(XIDparest(7),'string',mname)

elseif strcmp(arg,'estimate')
   method='arx';
   eval('if get(XIDarx(1,2),''value'')==0,method=''iv'';end','');
   if nargin==3,nn=nnu;modn=nny;elseif nargin==2,nn=nnu;end
   goto_ws=0;
   if nargin==1
      sl1=get(XIDparest(3),'string');
      if any(sl1==':')
         if ny>1,
             errordlg(str2mat('The model structure selection feature',...
                  'is not supported for multi-output systems.'));
             return
          end % in ny>1
          NN=idarxstr(sl1);
          if isempty(NN)
             errordlg(str2mat('Orders cannot be evaluated.',...
               'Please check expression in Orders: edit field.'));
             return
          end
          [nrNN,ncNN]=size(NN);
          [eDat,eDat_info]=iduigetd('e');[vDat,vDat_info]=iduigetd('v');
          kus=eval(['[',deblank(eDat_info(7,:)),']']); % The physical inputs
          kys=eval(['[',deblank(eDat_info(6,:)),']']); % The physical outputs
          kvu=[];kvy=[];flag=0;
          for ku=kus
              [nvy,nvu,dum,kk]=iduiiono('old',vDat_info,'dat',[ku,kys(1)]);
              if isempty(kk),flag=1;end
              kvu=[kvu,kk];
          end
          for ky=kys
              if isempty(kus),kus=0;end
              [nvy,nvu,kk,dum]=iduiiono('old',vDat_info,'dat',[kus(1),ky]);
              if isempty(kk),flag=1;end
              kvy=[kvy,kk];
          end
          if flag %eval(eDat_info(2,:))~=eval(vDat_info(2,:))|...
                   %eval(eDat_info(5,:))~=eval(vDat_info(5,:))
             errordlg(str2mat('The validation data do not contain',...
               'the inputs and outputs of the estimation data.'));
             return
          end % if flag ..
          vDat=vDat(:,[kvy,nvy+kvu]); % Matching the inputs and outputs
          time=nrNN*XIDcounters(6)/2.5;
          if time>60,
             exstr=['. (Could take some ',int2str(ceil(time/10)*10),' s)'];
          else
             exstr=' ...';
          end
          iduistat(['Computing all ',int2str(nrNN),' models',exstr])
          if ncNN~=ny+2*nu  % Then we make a forgiving interpretation
             NN=[NN(:,1),NN(:,2)*ones(1,nu),NN(:,ncNN)*ones(1,nu)];
          end
          tic,V=arxstruc(eDat,vDat,NN);etime=toc;
	  if time>60,XIDcounters(6)=etime*2.5/nrNN;end
          iduiarx('open',V);
          iduistat('Ready to select models.')
          iduistat('Click on bars to inspect models.',0,9);
          return
      else  
         eval('nn=eval([''['',sl1,'']'']);','goto_ws=1;');
      end  % if any :
   end  % if nargin==1
   if goto_ws,return,end
   [nnr,nnc]=size(nn);
   if nnr~=ny|nnc~=2*nu+ny
      errordlg('Incorrect number of orders specified.');
   elseif any(nn<0)
      errordlg('No order or delay can be negative.');
   else   
      [eDat,eDat_info,eDat_n]=iduigetd('e');
      TSamp=eval(eDat_info(1,:));
      for sky1=1:ny
        nastrr=[];nbstrr=[];nkstrr=[];
        for sky2=1:ny
            nastrr=[nastrr,' ',int2str(nn(sky1,sky2))];
        end
        for sky2=1:nu
            nbstrr=[nbstrr,' ',int2str(nn(sky1,sky2+ny))];
            nkstrr=[nkstrr,' ',int2str(nn(sky1,sky2+ny+nu))];
        end
        if sky1==1,
           nastr=[' na = [',nastrr,']'];
           nbstr=[' nb = [',nbstrr,']'];
           nkstr=[' nk = [',nkstrr,']'];          
        else 
           nastr=str2mat(nastr,['         [',nastrr,']']);
           nbstr=str2mat(nbstr,['         [',nbstrr,']']);
           nkstr=str2mat(nkstr,['         [',nkstrr,']']);
        end
      end
      if nu==0
         ordstr=int2str(nn(1,1));ordstr2=ordstr;
      else
         ordstr=[int2str(nn(1,1)),int2str(nn(1,ny+1)),int2str(nn(1,ny+nu+1))];
	 ordstr2=[int2str(nn(1,1)),' ',int2str(nn(1,ny+1)),' ',...
                  int2str(nn(1,ny+nu+1))];
      end
      iduistat('Computing the ARX model ...')
      if nargin<3,model=get(XIDparest(7),'string');else model=modn;end
      if strcmp(method,'arx')
  	LASTM=arx(eDat,nn,[],TSamp);
        if ny==1&nu<2
	  mod_info=str2mat(eDat_info,[' ',model,' = arx(',eDat_n,',[',...
	  ordstr2,'],[],',...
          num2str(TSamp),')']);
        else
          mod_info=str2mat(eDat_info,nastr,nbstr,nkstr,...
                   [' ',model,' = arx(',eDat_n,',[na,nb,nk],[],',...
                   num2str(TSamp),')']);
        end
      else
	if nu>0
           eval('LASTM=iv4(eDat,nn,[],TSamp);')
           meth=' = iv4(';exarg=[];
        else
           eval('LASTM=ivar(eDat,nn,[],[],TSamp);')
           meth=' = ivar(';exarg='[],';
        end
        if ny==1&nu<2
           mod_info=str2mat(eDat_info,[' ',model,meth,eDat_n,',[',...
	             ordstr2,'],[],',exarg,...
                     num2str(TSamp),')']);
        else
          mod_info=str2mat(eDat_info,nastr,nbstr,nkstr,...
                   [' ',model,meth,eDat_n,',[na,nb,nk],[],',exarg,...
                   num2str(TSamp),')']);
        end
      end
      mod_nam=model;%[model,'_',eDat_n];
      mod_nam=mod_nam(find(mod_nam~=' '));
      iduiinsm(LASTM,str2mat('',mod_info),mod_nam);
    end
elseif strcmp(arg,'comp')
    figure(XIDplotw(9,1))
    V=get(XIDplotw(9,3),'userdata');
    [nl1,nm1]=size(V);
    nu=floor((nl1-3)/2);
    Nc=V(1,nm1);
    pp=eval(get(findobj(XIDplotw(9,1),'tag','nupar'),'string'),'-1');
    if pp<min(V(nl1,:))|pp>max(V(nl1,:))
      sfit='';sna='';snb='';snk='';
      iduistat('This number of parameters is not available.',0,9);
    else
      ind=find(V(nl1,:)==pp);
      if isempty(ind),
        sfit='';sna='';snb='';snk='';
      else
        nn=V(2:2+2*nu,ind);
        sfit=num2str(V(1,ind));
        sna=int2str(nn(1));
        snb='';snk='';
        for ku=1:nu
          snb=[snb,int2str(nn(1+ku)),' '];
          snk=[snk,int2str(nn(nu+1+ku)),' '];
        end
      end
     iduistat('Press Insert to compute model or select other structure.',0,9);
    end  
    set(findobj(gcf,'tag','fit'),'string',sfit);
    set(findobj(gcf,'tag','na'),'string',sna);
    set(findobj(gcf,'tag','nb'),'string',snb);
    set(findobj(gcf,'tag','nk'),'string',snk);
elseif strcmp(arg,'down')
    cf=XIDplotw(9,1);
    figure(cf)
    V=get(XIDplotw(9,3),'userdata');
    [nl1,nm1]=size(V);
    nu=floor((nl1-3)/2);
    Nc=V(1,nm1);
    pt=get(gca,'currentpoint'); pp=round(pt(1,1));
    pp=max(min(V(nl1,1:nm1-1)),pp);pp=min(max(V(nl1,1:nm1-1)),pp);
    ind=find(V(nl1,:)==pp);
    if isempty(ind),
        sfit='';sna='';snb='';snk='';spp='';
    else
        nn=V(2:2+2*nu,ind);
        sfit=num2str(V(1,ind));
        sna=int2str(nn(1));spp=int2str(pp);
        snb='';snk='';
        for ku=1:nu
          snb=[snb,int2str(nn(1+ku)),' '];
          snk=[snk,int2str(nn(nu+1+ku)),' '];
        end
    end
    set(findobj(cf,'tag','fit'),'string',sfit);
    set(findobj(cf,'tag','na'),'string',sna);
    set(findobj(cf,'tag','nb'),'string',snb);
    set(findobj(cf,'tag','nk'),'string',snk);
    set(findobj(cf,'tag','nupar'),'string',spp);
    iduistat('Press Insert to estimate model, or click on other bar.',0,9);
elseif strcmp(arg,'insert')
  na=get(findobj(gcf,'tag','na'),'string');
  if isempty(na),
     iduistat('No model selected.',0,9);
     return
  end
  nb=get(findobj(gcf,'tag','nb'),'string');
  nk=get(findobj(gcf,'tag','nk'),'string');
  err=0;
  eval('set(XIDparest(3),''string'',[na,'' '',nb,nk]);','err=1;')
  if err
     errordlg(str2mat('Cannot find the Parametric Models Window.',...
       'Please reopen it.'));return
  end
  set(XIDparest(4),'value',1);
  iduistat('Model being computed ...',0,9);
  iduiarx('mname');
  iduiarx('estimate');
iduistat('New models may now be selected.',0,9);
elseif strcmp(arg,'close')
    set(XIDmse(1),'Visible','off')
end

