function idgenfig(models,figures)
%IDGENFIG Generates all view curves for ident.
%      The function generates all curves associated with models MODELS 
%      in view windows FIGURES. The handle numbers of these curves are
%      stored in the userdata of the corresponding axes, so that row
%      number 2*K+1 of the userdata contains the handles of lines
%      associated with model number K, while row 2*K+2 contains the
%      corresponding confidence interval lines.

%	L. Ljung 4-4-94
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.10 $  $Date: 1995/05/16 18:54:02 $


global   XIDplotw XIDmen XIDsumb
hnr=[];
sumbs=findobj(get(0,'children'),'flat','tag','sitb30');
modaxs=get(XIDsumb(1),'children');
for kk=sumbs(:)'
   modaxs=[modaxs;get(kk,'children')];
end
chmess='Model(s) incompatible with chosen channels.';
chmess2='Model(s) incompatible with chosen channel.';
for Figno=figures
  hsd=findobj(XIDplotw(Figno,1),'tag','confonoff');
  SD=get(hsd,'Userdata'); 
  figure(XIDplotw(Figno,1)),
  xusd=get(XIDplotw(Figno,1),'Userdata');
  xax=xusd(3:length(xusd));
  if isempty(get(xax(1),'children')),newplot=1;else newplot=0;end
  Opthand=XIDplotw(Figno,2);
  opt=get(Opthand,'UserData');
  hnrxor=findobj(XIDplotw(Figno,1),'label',menulabel('Erasemode &xor'));
  if strcmp(get(hnrxor,'checked'),'on') 
     ermode='xor';
  else 
     ermode='normal';
  end
  %ermode='normal';
  [kydes,kudes]=iduiiono('unpack',Figno);
  if Figno==2   % This is the Bode Case
      iduistat('Computing Frequency functions...')
      w=eval(deblank(opt(4,:)));
      [rw,cw]=size(w);if cw>rw w=w'; rw=cw;end,if rw==0,rw=128;end
      hz=eval(opt(3,:))-1;
      plx=eval(opt(1,:))-1;
      ply=eval(opt(2,:))-1;
      for k=models
         isconf=1;
         doplot=1;docalc=1;
         khax=findobj(modaxs,'flat','tag',['model',int2str(k)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
         [ny,nu,ky,ku]=iduiiono('old',nam,'mod',[kudes,kydes]);
         if nu==0
           errordlg(str2mat(['The model ',name,' is a time series model.'],...
               'Use ''Noise spectrum'' instead of the frequency plot.'));
           docalc=0;doplot=0;
           figure(XIDplotw(Figno,1)),
         elseif isempty(ku)|isempty(ky)
           iduistat(chmess,0,Figno);
           docalc=0;doplot=0;  figure(XIDplotw(Figno,1)),
         end
         if docalc
         nam=nam(1,1:5);
         if nam(1:3)=='spa'
            gc=[get(klin,'UserData')];
            if nam(5)=='e'; isconf=0;end 
            [rgc,cgc]=size(gc);rw=rgc-1;
         elseif ~strcmp(nam(1:3),'cra') 
            gc=iduicalc('ff',get(klin,'UserData'),ky,ku,w);
         else
            iduistat('No frequency response for CRA model.',0,Figno); 
            doplot=0;
         end
         end %if docalc
         axes(xax(1))
         xusd1=get(xax(1),'UserData');set(xax(1),'userdata',[]);
         if doplot
            [ggw,gga,ggp,ggsda,ggsdp]=getff(gc,ku,ky);
	    if isempty(ggsda),isconf=0;end
	    if hz ggw=ggw/2/pi;end
           if plx, set(gca,'Xscale','log'),else set(gca,'Xscale','linear'),end
           if ply, set(gca,'Yscale','log'),else set(gca,'Yscale','linear'),end
           color=get(klin,'color');
           xusd1(2*k+1,1)=line(ggw,gga,'color',color,'erasemode',ermode,...
                    'visible','off','userdata',kstr);
           hnr=[xusd1(2*k+1,1)];
           if isconf
               xusd1(2*k+2,1:2)=line([ggw ggw],[gga+SD*ggsda gga-SD*ggsda],...
                  'color',color,'linestyle','-.','erasemode',ermode,...
                  'Visible','off','userdata',kstr,'tag','conf')';
               hnr=[hnr,xusd1(2*k+2,1:2)];
           else
              if nam(1:3)=='spa'
                 noconf=-2;
              else
                 noconf=-1;
              end
              xusd1(2*k+2,1:2)=[noconf,noconf];
           end
         else
          xusd1(2*k+1,1)=-1;
         end %if doplot
         set(xax(1),'userData',xusd1);
         if doplot
           axes(xax(2))
           xusd2=get(xax(2),'UserData');set(xax(2),'userdata',[]);
           if plx, set(gca,'Xscale','log'),else set(gca,'Xscale','linear'),end
           xusd2(2*k+1,1)=line(ggw,ggp,'color',color,'erasemode',ermode,...
                     'visible','off','userdata',kstr);
           hnr=[hnr,xusd2(2*k+1,1)];
           if isconf
               xusd2(2*k+2,1:2)=line([ggw ggw],[ggp+SD*ggsdp ggp-SD*ggsdp],...
                  'color',color,'linestyle','-.','erasemode',ermode,...
                  'Visible','off','userdata',kstr,'tag','conf')';
               hnr=[hnr,xusd2(2*k+2,1:2)];
           else
              if nam(1:3)=='spa'
                 noconf=-2;
              else
                 noconf=-1;
              end
              xusd2(2*k+2,1:2)=[noconf,noconf];
           end
           set(xax(2),'userdata',xusd2)
           usd=[idnonzer(get(khax,'userdata'));hnr(:)];
           set(khax,'userdata',usd);
          
         end %if doplot
    end % for models
  elseif Figno==7,   % This is the Spectrum Case
      iduistat('Computing Spectra...')
      w=eval(deblank(opt(4,:)));
      [rw,cw]=size(w);if cw>rw w=w'; rw=cw;end,if rw==0,rw=128;end
      hz=eval(opt(3,:))-1;
      plx=eval(opt(1,:))-1;
      ply=eval(opt(2,:))-1;
      for k=models
         isconf=1;
         doplot=1;docalc=1;
         khax=findobj(modaxs,'flat','tag',['model',int2str(k)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
         [ny,nu,ky,ku]=iduiiono('old',nam,'mod',[kudes,kydes]);
         if isempty(ky)
           iduistat(chmess2,0,Figno);
           docalc=0;doplot=0;  figure(XIDplotw(Figno,1)),

         end
	 if docalc
         nam=nam(1,1:5);
         if nam(1:3)=='spa'
            spe=[get(klin,'UserData')];
            if nam(5)=='e'; isconf=0;end 
            [rgc,cgc]=size(gc);rw=rgc-1;
         elseif ~strcmp(nam(1:3),'cra') 
            spe=iduicalc('spe',get(klin,'UserData'),ky,0,w);%end
         else 
            iduistat('No spectrum for CRA model.',0,Figno); 
            doplot=0;
         end
	 end % if docalc
         axes(xax(1))
         xusd1=get(xax(1),'UserData');set(xax(1),'UserData',[]);
         if doplot
            [ggw,gga,dum,ggsda,dum]=getff(spe,0,ky);
            if isempty(ggsda),isconf=0;end
	    if hz ggw=ggw/2/pi;end
           if plx, set(gca,'Xscale','log'),else set(gca,'Xscale','linear'),end
           if ply, set(gca,'Yscale','log'),else set(gca,'Yscale','linear'),end
           color=get(klin,'color');
           xusd1(2*k+1,1)=line(ggw,gga,'color',color,'erasemode',ermode,...
                    'visible','off','userdata',kstr);
           hnr=[xusd1(2*k+1,1)];
           if isconf
               xusd1(2*k+2,1:2)=line([ggw ggw],[gga+SD*ggsda gga-SD*ggsda],...
                  'color',color,'linestyle','-.','erasemode',ermode,...
                  'Visible','off','userdata',kstr,'tag','conf')';
               hnr=[hnr,xusd1(2*k+2,1:2)];
           else
              if nam(1:3)=='spa'
                 noconf=-2;
              else
                 noconf=-1;
              end
              xusd1(2*k+2,1:2)=[noconf,noconf];
           end
         usd=[idnonzer(get(khax,'userdata'));hnr(:)];
         set(khax,'userdata',usd);
         else
          xusd1(2*k+1,1)=-1;
         end %if doplot
         set(xax(1),'userData',xusd1);

    end % for models
 
  elseif Figno==3   % This is Compare
   if any(models==0)
     iduistat('Adjusting fit table ...',0,3);
   else
     iduistat('Computing simulation/prediction ...')
     if isempty(get(gca,'children'))
         newplot=1;
     else
         newplot=0;
     end

     [vDat,vDat_info,vDat_name,kv]=iduigetd('v');
     TSamp=eval(vDat_info(1,:));t0=eval(vDat_info(3,:));
     [dny,dnu,dky]=iduiiono('old',vDat_info,'dat',[kudes,kydes]);
     if isempty(dky)
     errordlg(str2mat(['The validation data ',vDat_name,' does not contain'],...
                 'the chosen output channel for the model output plot.'));
           docalc=0;doplot=0;return
     end
     dat_u_ind=eval(['[',deblank(vDat_info(7,:)),']']);
     dat_y_ind=eval(['[',deblank(vDat_info(6,:)),']']);
     gc=vDat(:,dky);
     yval=gc;
     eval('PH=eval(opt(1,:));','PH=0;')
     if isempty(PH),PH=5;end
     if length(PH)>1|PH(1)<1|floor(PH(1))~=PH(1)
        errordlg(str2mat('The prediction horizon must be a postive integer.'));
        return
     end

     isdiff=eval(opt(4,:));
     if eval(opt(2,:))==2,ISSim=0;else ISSim=1;end, if isinf(PH),ISSim=1;end
     if dnu==0&ISSim,
        hmpred=findobj(XIDplotw(3,1),'tag','predict');
        hmsim=findobj(XIDplotw(3,1),'tag','simul');
        idopttog('check',hmpred);set(hmsim,'enable','off');
        return;
     end
     flag=0;
     eval('sumsamp=eval([''['',deblank(opt(3,:)),'']'']);','flag=1;')
     if flag
        errordlg(str2mat('The time span for computing the model fit',...
                'cannot be evaluated. Please check the text you typed in',...
                'the Options dialog box.'));
        return
     end
     if isempty(sumsamp),
        sumsamp=1:length(gc);
     else
        sumsamp=(sumsamp(1)-t0)/TSamp:(sumsamp(length(sumsamp))-t0)/TSamp;
     end
     indss=find(sumsamp<=length(gc)&sumsamp>0);
     if isempty(indss)
      errordlg(str2mat('Warning: The time span for computing the fit that',...
           'you have specified does not overlap with the time span of the',...
           'validation data.'));
     end
     sumsamp=sumsamp(indss);
    end % if models==0
     for k=models
       if k>0
         khax=findobj(modaxs,'flat','tag',['model',int2str(k)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
        [ny,nu,ky]=iduiiono('old',nam,'mod',[kudes,kydes]);
        mod_u_ind=eval(['[',deblank(nam(8,:)),']']);
        mod_y_ind=eval(['[',deblank(nam(7,:)),']']);
        u_ind=[];y_ind=[];stopflag=0;
        if isempty(mod_u_ind)&~isempty(dat_u_ind),stopflag=1;end
        for kku=mod_u_ind
            kuindex=find(kku==dat_u_ind);
            if isempty(kuindex)
               stopflag=1;
            else
               u_ind=[u_ind,kuindex];
            end
        end
        if ~ISSim
          for kky=mod_y_ind
            kyindex=find(kky==dat_y_ind);
            if isempty(kyindex)
               stopflag=1;
            else
               y_ind=[y_ind,kyindex];
            end
          end
        end
        if stopflag
           errordlg(...
             str2mat(['The model ',name,' requires input/output channels'],...
                    'that are not available in the validation data.'));
           docalc=0;  figure(XIDplotw(Figno,1)),

        elseif isempty(ky)
           iduistat(chmess2,0,Figno);
           docalc=0;  figure(XIDplotw(Figno,1)),

        else
           docalc=1;
        end
        doplot=0;
        if nam(1,1:3)=='cra' | nam(1,1:3)=='spa'
           iduistat('No model output for SPA and CRA models.',0,Figno);
        elseif docalc
           doplot=1;
           [model,modelky]=iduicalc('unpack',get(klin,'UserData'),ky);
           if ISSim
             if ~isempty(modelky) 
              [gc,sdgc]=idsim([vDat(:,dny+u_ind),...
                     zeros(length(vDat),ny)],modelky,1);
              gc=idsim(vDat(:,dny+u_ind),model,1);
             else
              [gc,sdgc]=idsim(vDat(:,dny+u_ind),model,1);
             end   
           else
              gc=predict(vDat(:,[y_ind,dny+u_ind]),model,PH);sdgc=[];
           end
           gc=gc(:,ky);     
           if isempty(sdgc),isconf=0;else isconf=1;end 
           fit=sqrt(1/length(sumsamp)*sum((vDat(sumsamp,dky)-gc(sumsamp)).^2));
        end
        xusd1=get(xax(1),'UserData');set(xax(1),'userdata',[]);
        if strcmp(get(hsd,'checked'),'on')
              onoff='on';
        else
              onoff='off';
        end
        else % i.e. if k==0
          doplot=1;
        end % if k>0
        if doplot
            xaxtab=findobj(XIDplotw(3,1),'tag','table');
          if k>0
            [rgc,cgc]=size(gc);
            if isdiff,gc=yval-gc;end
            color=get(klin,'color');
            TImeC=[0:rgc-1]*TSamp+t0;TImeC=TImeC'*ones(1,cgc);
            axes(xax(1))
            xusd1(2*k+1,1)=line(TImeC,gc,'color',color,'erasemode',ermode,...
                      'userdata',kstr);
            axes(xaxtab);
	    xusd1(2*k+1,2)=text(0,0,...
                    [get(kstr,'string'),': ',num2str(fit)],'color',color,...
                    'units','points','HorizontalAlignment','left',...
                  'userdata',fit,'tag','fits','fontsize',10);
          end % if k>0
            axes(xaxtab);
            fits=findobj(xaxtab,'tag','fits');
            vals=[];
            for kf=fits'
               vals=[vals,get(kf,'userdata')];
            end
            [dum,indv]=sort(vals);
            kp=15;
            xlead=findobj(xaxtab,'tag','leader');
            set(xlead,'units','points');xlpos=get(xlead,'pos');
            set(xlead,'units','norm');
            for kf=indv(:)'
               set(fits(kf),'pos',[1 xlpos(2)-kp]);
               kp=kp+15;
            end
           if k==0,iduistat('',0,3);return,end 
               % k=0 has just been a response to resizing.
	    hnr=[xusd1(2*k+1,1:2)];
            axes(xax(1))
            if ISSim
             if isconf
              xusd1(2*k+2,1:2)=line([TImeC TImeC],[gc+SD*sdgc gc-SD*sdgc],...
                  'color',color,'linestyle','-.','erasemode',ermode,...
                  'Visible',onoff,'userdata',kstr,'tag','conf')';
              hnr=[hnr,xusd1(2*k+2,1:2)];
             else
              xusd1(2*k+2,1:2)=[-1,-1];
             end  
            end
            if xusd1(2,2)==0&~isdiff
              xusd1(2,2)=line(TImeC,vDat(:,dky),'color','w','erasemode',...
                        ermode,'userdata',kv(3));
            end
            usd=[idnonzer(get(khax,'userdata'));hnr(:)];
            set(khax,'userdata',usd);
         else 
            xusd1(2*k+1,1)=-1;
         end % end doplot
         set(xax(1),'UserData',xusd1)
      end %for models
      if newplot,axis(axis),axis('auto'),end

  elseif Figno==4  % ZPPLOT
     iduistat('Computing Poles and Zeros...')
     axes(xax(1))
     om=2.02*pi*[1:100]/100;
     w=exp(om*sqrt(-1));
     if isempty(get(gca,'children'))
         om=2.01*pi*[1:100]/100;
         w=exp(om*sqrt(-1));
         huc=line(real(w),imag(w),'color','w','vis','off','tag','zpucl');
         ucmen=findobj(XIDplotw(4,1),'tag','zpuc');
         if ~isempty(ucmen),if strcmp(get(ucmen,'checked'),'on')
            set(huc,'vis','on');
         end,end
         hreiem(1)=line([-1 1],[0 0],'color','w','vis','off','tag','zpaxr');
         hreiem(2)=line([0 0],[-1 1],'color','w','vis','off','tag','zpaxi');
         ucmen=findobj(XIDplotw(4,1),'tag','zpax');
         if ~isempty(ucmen),if strcmp(get(ucmen,'checked'),'on')
            set(hreim,'vis','on');
         end,end
         axis('equal'),%set(XIDmen(4,15),'checked','on');
     end

     for kcount=models
         khax=findobj(modaxs,'flat','tag',['model',int2str(kcount)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
	 doplot=1;docalc=1;
	 [ny,nu,ky,ku]=iduiiono('old',nam,'mod',[kudes,kydes]);
         if isempty(ky)|isempty(ku)
           iduistat(chmess,0,Figno);
           docalc=0;doplot=0;  figure(XIDplotw(Figno,1)),

         end
         if docalc
         if nam(1,1:3)=='cra' | nam(1,1:3)=='spa'
            doplot=0;
            iduistat('No plot for CRA and SPA models.',0,Figno);
         else
            doplot=1;		
            zepo=iduicalc('zp',get(klin,'Userdata'),ky,ku);
         end
         end %if docalc

         xusd=get(xax(1),'UserData');set(xax(1),'UserData',[]);
        [nrxusd,ncxusd]=size(xusd);
        if doplot
         [zz,pp,zzsd,ppsd]=getzp(zepo,ku,ky);
         if isempty(zzsd)&isempty(ppsd),isconf=0;else isconf=1;end
         color=get(klin,'color');
         MATLABversion = version;
         if MATLABversion(1)=='4',
            PropertyName = 'LineStyle';
         else
            PropertyName = 'Marker';
         end
         sl1=line(real(zz),imag(zz),...
               'color',color,PropertyName,'o','erasemode',ermode,...
               'userdata',kstr);
         sl2=line(real(pp),imag(pp),...
               'color',color,PropertyName,'x','erasemode',ermode,...
               'userdata',kstr);
% Now follows the confidence regions
       sl3=[];sl4=[];
      if isempty(zzsd)
         zeros_cf=0;
      else
         zeros_cf=1;
         zepo=[zz,zzsd];[nrll,nc]=size(zepo);
         for k=1:nrll
             sl31=[];
             if imag(zepo(k,1))==0
                rp=real(zepo(k,1)+SD*zepo(k,2)*[-1 1]);
                [mr,nr] = size(rp);
                sl31=line(rp,zeros(mr,nr),'color',color,'linestyle','-',...
                     'erasemode',ermode,'visible','off','userdata',kstr);
             elseif imag(zepo(k,1))>0
                r1=real(zepo(k,2));r2=imag(zepo(k,2));r3=zepo(k+1,2);
	        p1=r1*r1;p2=r2*r2;p3=r3*r1*r2;
	        SM=[p1 p3;p3 p2]; [V,D]=eig(SM); z1=real(w)*SD*sqrt(D(1,1));
	        z2=imag(w)*SD*sqrt(D(2,2)); X=V*[z1;z2];
	        X=[X(1,:)+real(zepo(k,1));X(2,:)+imag(zepo(k,1))];
	        sl31=line(X(1,:),X(2,:),'color',color,...
                    'linestyle','-','erasemode',ermode,'visible','off'...
                    ,'userdata',kstr);
	        sl=line(X(1,:),-X(2,:),'color',color,...
                    'linestyle','-','erasemode',ermode,'visible','off'...
                    ,'userdata',kstr);
                sl31=[sl31;sl];
            end % if imag
          
            sl3=[sl3;sl31];
        end  %for k=
      end % if isempty(zzsd)

      if isempty(ppsd)
        poles_cf=0;
      else
        poles_cf=1;
        zepo=[pp,ppsd];[nrll,nc]=size(zepo);
        for k=1:nrll
            sl41=[];
            if imag(zepo(k,1))==0
               rp=real(zepo(k,1)+SD*zepo(k,2)*[-1 1]);
               [mr,nr] = size(rp);
               sl41=line(rp,zeros(mr,nr),'color',color,'linestyle','-.',...
                      'erasemode',ermode,'visible','off','userdata',kstr,...
                      'tag','conf');
            elseif imag(zepo(k,1))>0
               r1=real(zepo(k,2));r2=imag(zepo(k,2));r3=zepo(k+1,2);
	       p1=r1*r1;p2=r2*r2;p3=r3*r1*r2;
	       SM=[p1 p3;p3 p2]; [V,D]=eig(SM); z1=real(w)*SD*sqrt(D(1,1));
	       z2=imag(w)*SD*sqrt(D(2,2)); X=V*[z1;z2];
	       X=[X(1,:)+real(zepo(k,1));X(2,:)+imag(zepo(k,1))];
	       sl41=line(X(1,:),X(2,:),'color',color,...
                    'linestyle','-','erasemode',ermode,'visible','off'...
                    ,'userdata',kstr,'tag','conf');
	       sl=line(X(1,:),-X(2,:),'color',color,...
                    'linestyle','-','erasemode',ermode,'visible','off'...
                    ,'userdata',kstr,'tag','conf');
               sl41=[sl41;sl];
            end % if imag
    
            sl4=[sl4;sl41];
        end %for k=
      end % if isempty(ppsd)
        l1=length(sl1)+length(sl2);l2=length(sl3)+length(sl4);
                if ncxusd<l1+l2+2,xusd=[xusd,zeros(nrxusd,l1+l2+2-nc)];end
        if l1>0,xusd(2*kcount+1,1:l1)=[sl1' sl2'];hnr=[sl1',sl2'];end
        if l2>0,
             xusd(2*kcount+2,1:l2)=[sl3',sl4'];hnr=[hnr,sl3',sl4'];
        else 
             xusd(2*kcount+2,1)=-1;
        end
        if strcmp(get(hsd,'checked'),'on')
              set(idnonzer([sl3',sl4']),'visible','on');
        end
       else
        xusd(2*kcount+1,1)=-1;
       end  %if doplot
         set(xax(1),'Userdata',xusd)
         usd=[idnonzer(get(khax,'userdata'));hnr(:)];
         set(khax,'userdata',usd);

    end %for kcount
    hre=findobj(XIDplotw(4,1),'tag','zpaxr');
    set(hre,'xdata',get(get(hre,'parent'),'xlim'));
    him=findobj(XIDplotw(4,1),'tag','zpaxi');
    set(him,'ydata',get(get(hre,'parent'),'ylim'));
 elseif Figno==5  % This is transient response
    iduistat('Computing transient response...')
    TImespan=eval(deblank(opt(2,:)));
    if isempty(TImespan),TImespan=1:40;end
    if eval(opt(3,:))==1,ISStep=1;else ISStep=0;end
    if eval(opt(1,:))==2,ISStem=1;else ISStem=0;end

    for k=models
         khax=findobj(modaxs,'flat','tag',['model',int2str(k)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
        [ny,nu,ky,ku]=iduiiono('old',nam,'mod',[kudes,kydes]);
        doplot=1;docalc=1;
         if isempty(ky)|isempty(ku)
           iduistat(chmess,0,Figno);
           docalc=0;doplot=0;  figure(XIDplotw(Figno,1)),

         end
         if docalc
	if nam(1,1:3)=='cra'
          if kudes<0
            iduistat('No noise response for CRA model.',0,Figno);
           doplot=0;
          else
           IR=get(klin,'UserData');IR=IR(:,(ky-1)*nu+ku);
           TSamp=IR(1);sdIR=IR(2)/2.58*ones(length(IR)-2,1);
           IR=IR(3:length(IR));
           isconf=1;
           if ISStep IR=cumsum(IR);sdIR=sdIR(1)*sqrt(1:length(IR))';end
          end
        elseif nam(1,1:3)=='spa'
           iduistat('No transient response for SPA model.',0,Figno);
           doplot=0;
        else
           [MOdel,modelky]=iduicalc('unpack',get(klin,'UserData'),ky);
           TSamp=abs(gett(MOdel));
           MSamp=TImespan;
           if ISStep 
             uu=ones(MSamp,1);
           else
             uu=[1;zeros(MSamp-1,1)];
           end
	   if ku<0,kku=nu-ku;else kku=ku;end
           uuu=[zeros(MSamp,kku-1),uu,zeros(MSamp,nu+ny-kku)];
           if ~isempty(modelky)
              [IR,sdIR]=idsim(uuu,modelky,1);
              IR=idsim(uuu,MOdel,1);
           else
              [IR,sdIR]=idsim(uuu,MOdel,1);
           end
           IR=IR(:,ky);
           if isempty(sdIR)
              isconf=0;
           else
              isconf=1; 
           end
        end
	end % if docalc
        xusd=get(xax(1),'userdata');set(xax(1),'UserData',[]);
        if doplot
           TImeS=[0:length(IR)-1]'*TSamp;
           color=get(klin,'color');
           if strcmp(get(hsd,'checked'),'on')
              onoff='on';
           else
              onoff='off';
           end
           axes(xax(1))
           if ISStem
             xx=[TImeS';TImeS';nan*ones(size(TImeS'))];
             yy=[zeros(1,length(TImeS));IR';nan*ones(size(IR'))]; 
             MATLABversion = version;
             if MATLABversion(1)=='4',
                PropertyName = 'LineStyle';
             else
                PropertyName = 'Marker';
             end
       	     sl1=line(TImeS',IR','color',color,...
                           'erasemode',ermode,PropertyName,'o','userdata',kstr);
             sl2=line(xx(:),yy(:),'color',color,'erasemode',ermode,...
                            'userdata',kstr);
             xusd(2*k+1,1:2)=[sl1' sl2'];hnr=[sl1',sl2'];
                       
           else 
             xusd(2*k+1,1)=line(TImeS,IR,'color',color,'erasemode',ermode...
                               ,'userdata',kstr);
             hnr=xusd(2*k+1,1);
           end
           if isconf
             if ISStem&~ISStep
              curves=[SD*sdIR -SD*sdIR];
             else
              curves=[IR+SD*sdIR  IR-SD*sdIR];
             end
             xusd(2*k+2,1:2)=line([TImeS TImeS],curves,'color',color,...
                           'erasemode',ermode,'linestyle','-.',...
			   'visible',onoff,'userdata',kstr,'tag','conf')';
             hnr=[hnr,xusd(2*k+2,1:2)];
           else %noconf
             xusd(2*k+2,1:2)=[-1,-1];
           end
        else
           xusd(2*k+1,1)=-1;
        end  
        set(xax(1),'Userdata',xusd)
        usd=[idnonzer(get(khax,'userdata'));hnr(:)];
        set(khax,'userdata',usd);
        if newplot, axis(axis),axis('auto'),end
    end %for k=
  elseif Figno==6
  iduistat('Computing residuals...')
    maxsize=idmsize;
    [z,z_info,vDat_name]=iduigetd('v');
    M=eval(opt);if isempty(opt),M=21;else M=M+1;end
    [dny,dnu,dky,dku]=iduiiono('old',z_info,'dat',[kudes,kydes]);
    if isempty(dky)
   errordlg(str2mat(['The validation data ',vDat_name,' does not contain'],...
                 'the chosen output channel for the residual plot.'));
           docalc=0;doplot=0;return
    end
    dat_u_ind=eval(['[',deblank(z_info(7,:)),']']);
    dat_y_ind=eval(['[',deblank(z_info(6,:)),']']);

    for k=models
         khax=findobj(modaxs,'flat','tag',['model',int2str(k)]);
         kstr=findobj(khax,'tag','name');
         klin=findobj(khax,'tag','modelline');
         nam=get(kstr,'userdata');
         name=get(kstr,'string');
         if nam(1,1:3)=='spa' | nam(1,1:3)=='cra',
            iduistat('No plot for CRA and SPA models.',0,Figno);
           docalc=0;doplot=0;
         else
           docalc=1;doplot=1;
         end
         if docalc
            [ny,nu,ky,ku]=iduiiono('old',nam,'mod',[kudes,kydes]);
             mod_u_ind=eval(['[',deblank(nam(8,:)),']']);
             mod_y_ind=eval(['[',deblank(nam(7,:)),']']);
             u_ind=[];y_ind=[];stopflag=0;
             for kku=mod_u_ind
                kuindex=find(kku==dat_u_ind);
                if isempty(kuindex)
                   stopflag=1;
                else
                   u_ind=[u_ind,kuindex];
                end
             end
             for kky=mod_y_ind
                 kyindex=find(kky==dat_y_ind);
                 if isempty(kyindex)
                    stopflag=1;
                 else
                    y_ind=[y_ind,kyindex];
                 end
             end
             if stopflag
                 errordlg(...
             str2mat(['The model ',name,' requires input/output channels'],...
                    'for the residual plot that are not available',...
                    'in the validation data.'));
                 doplot=0;  figure(XIDplotw(Figno,1)),

              elseif isempty(ky)
                iduistat(chmess2,0,Figno);            
                doplot=0;  figure(XIDplotw(Figno,1)),

              else
                 doplot=1;
              end
     if doplot
         pos = idlayout('axes',1);posy = pos(1,:);
         posyts = idlayout('axes',7);
         if nu>0
             set(xax(1),'pos',posy,'xticklabels',[]);
         else
	     set(xax(1),'pos',posyts,'xticklabelmode','auto');
             axes(xax(2)),cla,
             set(xax(2),'vis','off')
         end
        th=iduicalc('unpack',get(klin,'UserData'),ky);
        xusd1=get(xax(1),'userdata');set(xax(1),'userdata',[]);
        color=get(klin,'color');
        [N,nz]=size(z); %nu=th(1,3);ny=nz-nu;
        e=pe(z(:,[y_ind,dny+u_ind]),th);
        e=e(:,ky);
        if nu>0, e1=[e,z(:,dny+dku)];else e1=e;end
        r=covf(e1,M,maxsize);

        nr=1:M-1;
        ind=1;
        sdre=SD*(r(ind,1))/sqrt(N)*ones(2*M-1,1);
        axes(xax(1));[nllr,nllc]=size(r);
        xusd1(2*k+1,1)=line(nr,r(ind,2:nllc)'/r(ind,1),'color',color,...
                'erasemode',ermode,'userdata',kstr);
        xusd1(2*k+1,2)=line(-nr,r(ind,2:nllc)'/r(ind,1),'color',color,...
                'erasemode',ermode,'userdata',kstr);

        xusd1(2*k+2,1:2)=line([-M+1:M-1],[sdre -sdre]/r(ind,1),'color',color,...
           'linestyle',':','erasemode',ermode,'Visible','off',...
           'tag','conf','userdata',kstr)';
        hnr=[xusd1(2*k+1,1:2),xusd1(2*k+2,1:2)];
        if newplot,axis(axis),axis('auto'),end
        if nu>0
        nr=-M+1:M-1;
        set(xax(2),'vis','on')
        ind1=3;ind2=2;indy=1;indu=4;
        sdreu=SD*sqrt(r(indy,1)*r(indu,1)+2*(r(indy,2:M)*r(indu,2:M)'))...
             /sqrt(N)*ones(2*M-1,1);
        axes(xax(2))
        xusd2=get(xax(2),'userdata');set(xax(2),'userdata',[]);
        xusd2(2*k+1,1)=line(nr,...
           [r(ind1,M:-1:1) r(ind2,2:M) ]'/(sqrt(r(indy,1)*r(indu,1))),...
           'Erasemode',ermode,'color',color,'userdata',kstr);

       xusd2(2*k+2,1:2)=line(nr,[sdreu -sdreu]/(sqrt(r(indy,1)*r(indu,1))),...
           'LineStyle',':','EraseMode',ermode,'Visible','off','color',color...
            ,'userdata',kstr,'tag','conf')';
       if newplot,axis(axis),axis('auto')
       end
       set(xax(2),'userdata',xusd2)
       hnr=[hnr,xusd2(2*k+1,1),xusd2(2*k+2,1:2)];
       end %if nu>0
       if strcmp(get(hsd,'checked'),'on')
           set(idnonzer(xusd1(2*k+2,1:2)),'Visible','on')
           eval('set(idnonzer(xusd2(2*k+2,1:2)),''Visible'',''on'')','');
       end
     
     usd=[idnonzer(get(khax,'userdata'));hnr(:)];
     set(khax,'userdata',usd);
     else 
      xusd1(2*k+1,1)=-1;
     end  % if doplot
     set(xax(1),'Userdata',xusd1)
    end % if docalc
  end %for k=models
  iduital(6);
 
end %if Figno
     

end % for figures

