function iduifilt(flag,filter)
%IDUIFILT Handles prefiltering of data for ident.
%	FLAG:
%	open         Opens the dialog box.
%	spectra      Computes and plots the spectra.
%	             If FILTER has the value 'filt' this is done for
%	             the filtered data, otherwise for the estimation data.
%	down,move,up Draws the box that defines the frequency range
%	filter       Applies the selected filter to estimation data and stores
%	             the result as userdata of XIDfilt(1,1).
%	revert       One push removes the outline box, the next clears the
%	             filtered data, if any.
%	insert       Inserts the filtered data into the data summary board.
%	mark         Marks the outline box, based on information in XIDfilt(3,1).
%	done         Closes the dialog box.

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

% Userdata Used: 
%	XIDfilt(1,1) The filtered data, if any
%	XIDfilt(2,1) The handle number of the drawn box, if any
%	XIDfilt(3,1) The handle numbers of the filtered spectra plots
%	XIDfilt(4,1) The sampling interval
%	XIDfilt(5,1) The string that describes the filtering

global XIDmen XIDfilt XIDplotw
global XIDtest %%%%%
if nargin<2, filter='nofilter';end

if strcmp(flag,'open')
   figname='Prefilter Data';
   if isempty(iduiwok(15))
	iduistat('Opening dialog box ...')
	layout
	butwh=[1.3*mStdButtonWidth mStdButtonHeight];%butw=55;buth=25;
	butw=butwh(1);buth=butwh(2);
	ftb=2;  % Frame to button
	bb = 2; % between buttons, horizontally
        bbver = 4; % Between buttons, vertically
	etf = mEdgeToFrame;
        s1='iduipoin(1);';s2='iduipoin(1);iduistat(''Compiling ...'');';
        s3='iduipoin(2);';
	XIDplotw(15,1)=idbuildw(15);
       set(XIDplotw(15,1),'units','pixels');
       FigWH=get(XIDplotw(15,1),'pos');FigWH=FigWH(3:4);
       lev1=max(etf,(FigWH(2)-11*buth-9*bbver-2*mFrameToText)/2)+buth;
       pos = iduilay1(mStdButtonWidth+2*mFrameToText,10,10,...
             lev1-mEdgeToFrame,bbver);
        pos=pos+[(FigWH(1)-butw-2*bb-2*etf)*ones(11,1),zeros(11,3)];

	XIDfilt(1,1)=uicontrol(XIDplotw(15,1),'pos',pos(1,:),'style','frame');
	XIDfilt(5,1)=uicontrol(XIDplotw(15,1),'pos',pos(2,:),'style',...
	       'text','string',str2mat('Range'),'HorizontalAlignment','left');
      XIDfilt(3,1)=uicontrol(XIDplotw(15,1),'pos',pos(3,:)+[0 5 0 0],...
             'style','edit',...
        'callback',[s1,'iduifilt(''mark'');',s3],'backgroundcolor','white',...
             'HorizontalAlignment','left');
	uicontrol(XIDplotw(15,1),'pos',pos(4,:),'style','text',...
           'string',str2mat('Range is'),'HorizontalAlignment','left');

	XIDfilt(4,1)=uicontrol(XIDplotw(15,1),'pos',pos(5,:)+[0 5 0 0],...
               'style','popupmenu','string','Pass band|Stop band',...
               'value',1,'userdata',1);
	uicontrol(XIDplotw(15,1),'pos',pos(6,:),'style','text',...
	       'string','Data name:','HorizontalAlignment','left');
	XIDfilt(2,1)=uicontrol(XIDplotw(15,1),'pos',pos(7,:)+[0 5 0 0],...
               'style','edit','backgroundcolor','white',...
               'HorizontalAlignment','left');
	uicontrol(XIDplotw(15,1),'Pos',pos(8,:),'style','push','callback',...
	  [s2,'iduifilt(''filter'');',s3],'string','Filter');
	uicontrol(XIDplotw(15,1),'Pos',pos(9,:),'style','push','callback',...
	  [s1,'iduifilt(''insert'');',s3],'string','Insert');
	XIDfilt(6,1)= uicontrol(XIDplotw(15,1),'Pos',pos(10,:),'style',...
	 'push','callback',...
	 [s1,'iduifilt(''revert'');',s3],'string','Revert');
        uicontrol(XIDplotw(15,1),'pos',pos(11,:),'style','push','callback',...
         'set(gcf,''vis'',''off'');','string','Close');
        uic=findobj(XIDplotw(15,1),'type','uicontrol');
        set(uic,'units','norm');
        eval('set(XIDplotw(15,1),''pos'',XIDlayout(37,1:4))','')
        set(XIDplotw(15,1),'vis','on')
     end %if figflag
     ax=findobj(XIDplotw(15,1),'type','axes');
     for kax=ax(:)',axes(kax),cla,end
     [dat,dat_info,dat_n]=iduigetd('e');
     iduiiono('set',dat_info,15);
     iddatfig(0,15);
     iduital(15);
     set(XIDfilt(2,1),'string',[dat_n,'f']);
     set(XIDplotw(15,1),'vis','on')
     iduistat('Ready to prefilter.')
     iduistat('Mark desired frequency range using mouse or keyboard.',0,15)

elseif strcmp(flag,'down'),
      % The following is due to the unreliability of 'gca':
   axhand1=findobj(gcf,'tag','axis1','vis','on');
   axhand2=findobj(gcf,'tag','axis2','vis','on');

   if ~isempty(axhand2)
           axhand=[axhand1 axhand2];
           morax=1;
 	   pos=get(gcf,'pos');
	   [x,y]=get(gcf,'currentpoint');
 	   if x(2)>0.5*pos(4),
              curax=axhand(1);altax=axhand(2);
           else 
	      curax=axhand(2);altax=axhand(1);
           end
       else
          curax=axhand1;moreax=0;
       end
       axes(curax)


     h=get(XIDfilt(2,1),'userdata');
     eval(['if get(h(2),''parent'')==curax,h=h([2 1]);end'],'h=[h(1),0];')
     set(XIDfilt(2,1),'userdata',h);
     pt=get(curax,'currentpoint');
     x=[pt(1,1) pt(1,1) pt(1,1) pt(1,1) pt(1,1)];
     y=[pt(1,2) pt(1,2) pt(1,2) pt(1,2) pt(1,2)];
     set(h(1),'xdata',x,'ydata',y);
     if h(2)>0
        othax=get(get(h(2),'parent'),'userdata');
        yd=get(othax(5,1),'ydata');
        yl=[0.8*max(yd),1.2*min(yd)];
        y1=[yl(1) yl(1) yl(2) yl(2) yl(1)];
        set(h(2),'xdata',x,'ydata',y1);
     end
     set(idnonzer(h),'vis','on')
     set(XIDplotw(15,1),'windowbuttonmotionfcn','iduifilt(''move'');');
     set(XIDplotw(15,1),'windowbuttonupfcn','iduifilt(''up'')');
    iduistat('Draw a rectangle with the mousebutton down.',0,15);
elseif strcmp(flag,'move')

     h=get(XIDfilt(2,1),'UserData');
     x=get(h(1),'xdata'); 
     y=get(h(1),'ydata'); 
     pt=get(gca,'currentpoint');
     x(2)=pt(1,1); 
     x(3)=pt(1,1);
     y(3)=pt(1,2); 
     y(4)=pt(1,2);
     set(h(1),'xdat',x,'ydat',y);
     if h(2)>0
        set(h(2),'xdat',x);
     end
     fre=sort([x(1) x(2)]);
     set(XIDfilt(3,1),'string',[num2str(fre(1)),' ',num2str(fre(2))]);

elseif strcmp(flag,'up'),

     set(gcf,'windowbuttonmotionfcn','');
     set(gcf,'windowbuttonupfcn','1;');
     iduistat('Press Filter to compute filtered data.',0,15)
elseif strcmp(flag,'mark')
     h=get(XIDfilt(2,1),'userdata');
     freqs = eval(['[',get(XIDfilt(3,1),'string'),']'],'[]');
    if length(freqs)<2
       errordlg('Two frequency range limits must be supplied.');
       return
    end

     x(1)=freqs(1);x(2)=freqs(2);x(3)=freqs(2);x(4)=freqs(1);x(5)=freqs(1);
     a=get(XIDplotw(15,1),'userdata');hh=idnonzer(h);
     for kk=hh(:)'%1:length(idnonzer(h))
        yl=get(get(kk,'parent'),'ylim');yl=[1.2*yl(1) 0.8*yl(2)];
        y1=[yl(1) yl(1) yl(2) yl(2) yl(1)];
	set(kk,'xdata',x,'ydata',y1);%,'vis','on');
        set(kk,'vis','on')
     end
     iduistat('Press Filter to compute filtered data.',0,15)

elseif strcmp(flag,'revert')
       delete(idnonzer(get(XIDfilt(3,1),'Userdata')));
       set(XIDfilt(1,1),'UserData',[]);
       iduistat('Select new frequency range.',0,15)

elseif strcmp(flag,'filter')

    [dat,dat_info,dat_n]=iduigetd('e');
    Tsamp=eval(deblank(dat_info(1,:)));
    freqs=eval(['[',get(XIDfilt(3,1),'string'),']'],'[]')*Tsamp*2;

    if length(freqs)<2
       errordlg('Two frequency range limits must be supplied.');
       return
    end
    freqs=sort(freqs);
    usd=get(XIDplotw(15,2),'userdata');
    if eval(usd(3))==1,freqs=freqs/pi/2;end % If unit rad/s
    if get(XIDfilt(4,1),'value')-1,BP=0;else BP=1;end
    if freqs(1)<0.01, freqs=freqs(2); if BP, type=1;else type=0;end
       %type=1 means low pass here
    elseif freqs(2)>0.95, freqs=freqs(1); if BP, type=0;else type=1;end,end
    if length(freqs)>1,
	sfreqs=['[',num2str(freqs(1)),',',num2str(freqs(2)),']'];
	if BP, type=1;else type=0;end
    else
	sfreqs=num2str(freqs);
    end
if XIDtest,ord=inf;else ord=5;end%%%%%
    if type
       zf=idfilt(dat,ord,freqs); filtstr=['idfilt(',dat_n,',5,',sfreqs,')'];
    else
       zf=idfilt(dat,ord,freqs,'high');
       filtstr=['idfilt(',dat_n,',inf,',sfreqs,'''high'')'];
   end
   set(XIDfilt(1,1),'userdata',zf);set(XIDfilt(5,1),'userdata',filtstr);
   iddatfig(-1,15);
   iduistat('Filtered data spectra shown. Press Insert to accept.',0,15)
elseif strcmp(flag,'insert')

    zf=get(XIDfilt(1,1),'userdata');
    if isempty(zf),
       errordlg(str2mat('No filtered data selected.',...
          'Press Filter to filter the working data set.'))
       return
    end
    [dat,dat_info,dat_no]=iduigetd('e');
    dat_n=get(XIDfilt(2,1),'string');
    addendum=[' ',dat_n,' = ',get(XIDfilt(5,1),'userdata')];
    dat_info=str2mat(dat_info,addendum);
    iduiinsd(zf,dat_info,dat_n);
    iduistat('New filter can now be defined.',0,15);
elseif strcmp(flag,'done')

    set(XIDplotw(15,1),'vis','off');

end
