function [result,modelky]=iduicalc(arg,model,ky,ku,w)
%IDUICALC Unpacks the (vectorized) theta model and provides help to idgenfig.
%       The help is for ff spe and zp.

%	L. Ljung 9-27-94
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%	$Revision: 1.4 $  $Date: 1995/05/10 21:36:59 $

[nr,nc]=size(model);
if nc==1
   ny=model(1);ns=ny*3+5;ne=ns+model(2)*model(3)-1;
   model0=reshape(model(ns:ne),model(2),model(3));
   if nargin>2
     ns=model(ky*3+1);nr=model(ky*3+2);nc=model(ky*3+3);ne=ns+nr*nc-1;
     modelky=reshape(model(ns:ne),nr,nc);
   end 
   model=model0;
   ssky=1;ss=1;
else
   modelky=[];
   ssky=0;if isthss(model),ss=1;else ss=0;end
end
nu=model(1,3);
if strcmp(arg,'unpack')
   result=model;
elseif strcmp(arg,'ff')
   if ss
      g=trf(model,ku,w,ky);
      if ssky
         gsd=th2ff(modelky,ku,w);
         gsd(1,:)=gsd(1,:)+1000*(ky-1);
         result=[g(:,[1 2]),gsd(:,3),g(:,3),gsd(:,5)];
      else
         result=g;
      end
   else
      result=th2ff(model,ku,w,ky);
   end
elseif strcmp(arg,'spe')
   if ss
    [g,pv]=trf(model,ku,w,ky);
    if ssky  
       [nrg,dum]=size(g);T=gett(model);
       Ncap=getncap(model);if isempty(Ncap),Ncap=inf;end
       nu=model(1,3);ny=model(1,4);[dum,dum,lambda]=th2par(model);
       w=g(2:nrg,1);
       gy=th2ff(modelky,[nu+[1:ny]],w);
       pp=zeros(length(w),1);psd=pp;
       for jj=nu+[1:ny]
         [w,amp,fas,sdamp]=getff(gy,jj,1);
         dum=zeros(length(w),1);dumsd=dum;
         for kk=nu+[1:ny]
           [w,ampkk,faskk,sdampkk]=getff(gy,kk,1);
           term=ampkk.*cos((faskk-fas)/180*pi)*lambda(jj-nu,kk-nu);
           dum=dum+term;
           if kk==jj,factor=4;else factor=2;end
           dumsd=dumsd+factor*term.^2;
         end
         pp=pp+dum.*amp;
         psd=psd+dumsd.*sdamp.^2;
        end 
        result=[pv,[50+(ky-1)*1000;...
                  sqrt(2/Ncap)*abs(T)*pp+abs(T)*sqrt(psd)]];
     else 
        result=pv;
     end
   else
      [dum,result]=th2ff(model,ku,w,ky);
   end
elseif strcmp(arg,'zp')
   if ss
    if ssky
     if ku<0,kku=nu+abs(ku);else kku=ku;end
     zeposd=th2zp(modelky,kku);

     if ku<0, zeposd(1,:)=500+abs(ku)+[0 60 20 80];end
     zeposd(1,:)=zeposd(1,:)+1000*(ky-1);
     result=zeposd;
    else
     result=zp(model,ku,ky);
    end
     %result=[zepo(:,1) zeposd(:,2) zepo(:,2) zeposd(:,4)];
   else
     result=th2zp(model,ku,ky);
   end
end
