function [xsamp,xtime]=iduisel(flag,xdat,sampflag,arg4,arg5,arg6)
%IDUISEL Manages the selection of input/output data variables and data portions.
%	FLAG:
%	open_portions Opens the dialog box for selecting data portions.
%	open_io       Opens the dialog box for selction of inputs and outputs.
%	comput        Computes sample and time portions.
%	samples       Handles information for portions in terms of samples.
%	time          Handles informations for portions in terms of time.
%	down,move,up  Handles the drawing of boxes in the plot window.
%	revert        Erases the last drawn rectangle.
%	insert        Inserts the data with selected portions.
%	done          Closes the dialog box on data portions.
%	detrend       Detrends data.
%	decim         Resamples data.
%	revert_io     Resets all edit boxes for selection of inputs and outputs.
%	insert_io     Inserts the data with selcted inputs and outputs.
%	done_io       Closes the dialog box on input/output selction.

%	L. Ljung 4-4-94
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%       $Revision: 1.13 $  $Date: 1995/06/01 06:50:12 $

global XIDsel XIDplotw XIDlayout


if strcmp(flag,'open_portions')
   if isempty(iduiwok(14))
       iduistat('Opening dialog box ...')
       layout
       cb1='iduipoin(1);iduistat(''Compiling...'');';
       cb2='iduipoin(1);';
       cb3='iduipoin(2);';

       butwh=[mStdButtonWidth mStdButtonHeight];%butw=55;buth=25;
       butw=butwh(1);buth=butwh(2);
       ftb=2;  % Frame to button
       bb = mFrameToText; % between buttons, horizontally
       bbver = 4; % Between buttons, vertically
       etf = mEdgeToFrame;

       XIDplotw(14,1)=idbuildw(14);
       set(XIDplotw(14,1),'units','pixels');
       FigWH=get(XIDplotw(14,1),'pos');FigWH=FigWH(3:4);
      lev1=max(mEdgeToFrame,(FigWH(2)-10*buth-8*bbver-2*mFrameToText)/2)+buth;
       pos = iduilay1(mStdButtonWidth+2*mFrameToText,9,9,...
             lev1-mEdgeToFrame,bbver);
       pos=pos+[(FigWH(1)-butw-2*bb-2*etf)*ones(10,1),zeros(10,3)];
       XIDsel(3,1)=uicontrol(XIDplotw(14,1),'pos',pos(1,:),'style','frame');
       XIDsel(5,1)=uicontrol(XIDplotw(14,1),'Pos',pos(8,:),'style','push',...
          'callback',...
          [cb2,'iduisel(''insert'');',cb3],'string','Insert');
       uicontrol(XIDplotw(14,1),'Pos',pos(10,:),'style','push','callback',...
          'iduisel(''done'');','string','Close');
       uicontrol(XIDplotw(14,1),'Pos',pos(9,:),'style','push','callback',...
          'iduisel(''revert'');','string','Revert');


      uicontrol(XIDplotw(14,1),'pos',pos(6,:),'style','text',...
               'string','Data name:','HorizontalAlignment','left');
      XIDsel(2,1)=uicontrol(XIDplotw(14,1),'pos',...
               pos(7,:)+[0 5 0 0],'style',...
               'edit','backgroundcolor','white','horizontalalignment','left');

       XIDplotw(14,2)=uicontrol(XIDplotw(14,1),'pos',...
            pos(5,:)+[0 5 0 0],'style','edit',...
             'callback',[cb1,'iduisel(''samples'');',cb3],...
             'backgroundcolor','white', ...
             'horizontalalignment','left');
      set(XIDplotw(14,2),'userdata',get(XIDplotw(1,2),'userdata'));
      uicontrol(XIDplotw(14,1),'pos',pos(4,:),'HorizontalAlignment','left',...
            'style','text','string',...
              str2mat('Samples:'));
      XIDsel(4,1)=uicontrol(XIDplotw(14,1),'pos',...
             pos(3,:)+[0 5 0 0],'style',...
              'edit','callback',[cb2,'iduisel(''time'');',cb3],...
              'backgroundcolor','white','horizontalalignment','left');
      uicontrol(XIDplotw(14,1),'pos',pos(2,:),'HorizontalAlignment','left',...
              'style','text',...
              'string',str2mat('Time span:'));
%      uicontrol(XIDplotw(14,1),'pos',...
%             pos(2,:),'style','text',...
%              'string',str2mat('Data Range:'));

     handl=findobj(XIDplotw(14,1),'type','uicontrol');
     set(handl,'unit','norm')
     if length(XIDlayout)>30,if XIDlayout(31,3)
     eval('set(XIDplotw(14,1),''pos'',XIDlayout(31,1:4))','')
     end,end
     end % end create window

     % Plot data
     xax=findobj(XIDplotw(14,1),'type','axes');
     hbox=zeros(2,2);
     if strcmp(get(0,'blackandwhite'),'on')
        col=['y','y'];
     else
       col=['g','r'];
     end
     for kh=1:2
       axes(xax(kh));cla
       for kb=1:2
         hbox(kb,kh)=line('linestyle','--','color',col(kb),...
                          'erasemode','xor','vis','off');
       end
      end
      set(XIDsel(3,1),'userdata',hbox);
     [dat,dat_inf,dat_n]=iduigetd('e');
     iduiiono('set',dat_inf,14);
     iddatfig(0,14);
     iduital(14);
     tSamp=eval(dat_inf(1,:));[dl,dum]=size(dat);
     t0=eval(dat_inf(3,:));
     set(XIDsel(4,1),'userdata',[tSamp,t0,dl]);
     set(XIDsel(2,1),'string',[dat_n,'e']);
     [xsamp,xtime]=iduisel('comput',[1 dl],1);
     set(XIDsel(4,1),'string',xtime);
     set(XIDplotw(14,2),'string',xsamp);
     set(XIDsel(2,1),'UserData',0);   
     drawnow
     set(XIDplotw(14,1),'vis','on')
     iduistat('Ready to select data ranges.')
     iduistat('Mark data range using mouse or keyboard.',0,14)

elseif strcmp(flag,'open_io')
   figname=idlaytab('figname',28);
   if ~figflag(figname,0)
       iduistat('Opening dialog box ...')
       layout       
       f=figure('Nextplot','New',...
             'NumberTitle','off','Name',figname,'tag','sitb28',...
             'Color',get(0,'DefaultUIControlBackgroundColor'),'vis','off');
       set(f,'Menubar','none');
       XIDsel(1,2)=f;
       FigW=iduilay2(2);
      cb1='iduipoin(1);iduistat(''Compiling...'');';
      cb2='iduipoin(1);';
      cb3='iduipoin(2);';

       % LEVEL 1
  
       pos = iduilay1(FigW,4,2);
       uicontrol(f,'pos',pos(1,:),'style','frame');
       uicontrol(f,'Pos',pos(2,:),'style','push','callback',...
          [cb2,'iduisel(''insert_io'');',cb3],'string','Insert');
       uicontrol(f,'Pos',pos(3,:),'style','push','callback',...
          [cb2,'iduisel(''revert_io'');',cb3],'string','Revert');
       uicontrol(f,'Pos',pos(4,:),'style','push','callback',...
          'iduisel(''done_io'');','string','Close');
       uicontrol(f,'Pos',pos(5,:),'style','push','callback',...
          'iduihelp(''idselio.hlp'',''Help: Select Channels'');','string','Help');

      % LEVEL 2
       lev2=pos(1,2)+pos(1,4);
       pos = iduilay1(FigW,8,4,lev2);
       uicontrol(f,'pos',pos(1,:),'style','frame');
       uicontrol(f,'pos',pos(2,:),'style','text','string','Working data:',...
                'horizontalalignment','left')
       uicontrol(f,'pos',pos(3,:),'style','text','tag','wdname',...
                'horizontalalignment','left')
       
       uicontrol(f,'pos',pos(8,:),'style','text',...
               'string','Data name:','HorizontalAlignment','left');
      XIDsel(2,2)=uicontrol(f,'pos',pos(9,:),'style',...
               'edit',...
               'HorizontalAlignment','left',...
               'backgroundcolor','white');

       XIDsel(3,2)=uicontrol(f,'pos',pos(5,:),'style','edit',...
               'HorizontalAlignment','left',...
              'backgroundcolor','white');
      uicontrol(f,'pos',pos(4,:),'style','text','string',...
              str2mat('Inputs:'),'HorizontalAlignment','left');
      XIDsel(4,2)=uicontrol(f,'pos',pos(7,:),'style',...
               'edit',...
	       'HorizontalAlignment','left',...
               'backgroundcolor','white');
     uicontrol(f,'pos',pos(6,:),'style','text',...
             'string',str2mat('Outputs:'),'HorizontalAlignment',...
              'left');
     FigWH=[iduilay2(2) pos(1,2)+pos(1,4)+mEdgeToFrame];
     ScreenPos = get(0,'ScreenSize');
     FigPos=[(ScreenPos(3:4)-FigWH)/2 FigWH];
     set(f,'pos',FigPos); 
     set(get(f,'children'),'unit','norm');
     if length(XIDlayout)>27,if XIDlayout(28,3)
     eval('set(f,''pos'',XIDlayout(28,1:4))','');
     end,end
     set(f,'vis','on')
     end
     iduisel('revert_io')
     iduistat('Ready to select input output channels.')

elseif strcmp(flag,'open_dec')
   figname=idlaytab('figname',30);
   if ~figflag(figname,0)
       iduistat('Opening dialog box ...')
       layout
       f=figure('Nextplot','New',...
             'NumberTitle','off','Name',figname,'tag','sitb30',...
             'Color',get(0,'DefaultUIControlBackgroundColor'),'vis','off');
       set(f,'Menubar','none');
       FigW=iduilay2(3);
       cb1='iduipoin(1);iduistat(''Compiling...'');';
       cb2='iduipoin(1);';
       cb3='iduipoin(2);';

       % LEVEL 1

       pos = iduilay1(FigW,3);
       uicontrol(f,'pos',pos(1,:),'style','frame');
       uicontrol(f,'Pos',pos(2,:),'style','push','callback',...
          [cb1,'iduisel(''decim'');',cb3],'string','Insert');
       uicontrol(f,'Pos',pos(3,:),'style','push','callback',...
          'set(gcf,''vis'',''off'');','string','Close');
       uicontrol(f,'Pos',pos(4,:),'style','push','callback',...
          'iduihelp(''iddec.hlp'',''Help: Resample Data'');','string','Help');

      % LEVEL 2
       lev2=pos(1,2)+pos(1,4);
       pos = iduilay1(FigW,6,3,lev2,4,1.5);
       uicontrol(f,'pos',pos(1,:),'style','frame');
       uicontrol(f,'pos',pos(2,:),'style','text','string','Working data:',...
                'horizontalalignment','left')
       uicontrol(f,'pos',pos(3,:),'style','text','tag','wdname',...
                'horizontalalignment','left')
       uicontrol(f,'pos',pos(6,:),'style','text',...
               'string','Data name:','HorizontalAlignment','left');
       uicontrol(f,'pos',pos(7,:),'style',...
               'edit','backgroundcolor','white',...
               'HorizontalAlignment','left',...
               'tag','dataname');

       uicontrol(f,'pos',pos(5,:),'style','edit',...
                  'HorizontalAlignment','left',...
                  'backgroundcolor','white','tag','decfact','string','1');
       uicontrol(f,'pos',pos(4,:),'style','text','string',...
              'Resampling factor:','HorizontalAlignment','left');
       FigWH=[iduilay2(3) pos(1,2)+pos(1,4)+mEdgeToFrame];
       ScreenPos = get(0,'ScreenSize');
       FigPos=[(ScreenPos(3:4)-FigWH)/2 FigWH];
       set(f,'pos',FigPos);
     set(get(f,'children'),'unit','norm');
     if length(XIDlayout)>29,if XIDlayout(30,3)
     eval('set(f,''pos'',XIDlayout(30,1:4))','')
     end,end
     set(f,'vis','on')
     end
     iduisel('revert_dec')
     iduistat('Enter the resampling factor, and press the Insert button.')

elseif strcmp(flag,'comput')
    Tinfo=get(XIDsel(4,1),'UserData');
    Ts=Tinfo(1);t0=Tinfo(2);DL=Tinfo(3);
    if sampflag
       xdat=Ts*(xdat-[1 1])+t0;
    end
    xdat=sort(xdat);
    if xdat(1)<t0|xdat(1)>t0+Ts*(DL-1),xdat(1)=t0;end
    if xdat(2)>t0+Ts*(DL-1)|xdat(2)<t0,xdat(2)=t0+Ts*(DL-1);end
    xsamp1=max(floor(10^4*eps+(xdat(1)-t0)/Ts)+1,1);
    xsamp2=min(ceil((xdat(2)-t0)/Ts)+1-10^4*eps,DL);   
    xsamp=[int2str(xsamp1),' ',int2str(xsamp2)];
    xtime=[num2str(xdat(1)),' ',num2str(xdat(2))];
elseif strcmp(flag,'samples')
    strsamp=get(XIDplotw(14,2),'string');
    err=0;
    eval('test=eval([''['',strsamp,'']'']);','err=1;')
    if err,
     errordlg(str2mat('The entered sample numbers could not be evaluated.',...
            'Please check your entry.'));iduisel('revert');
     return
    end
    indcol=find(strsamp==':');
    if length(indcol)==1,strsamp(indcol)=' ';end
    if length(indcol)>1
       errordlg('Use Resample to change the sampling interval.');
       iduisel('revert');
       return
    end
    x=idstrip(strsamp);
    if length(x)<2
     errordlg('You must supply both upper and lower bounds on the interval.');
     iduisel('revert');
     return
    end
    [xsamp,xtime]=iduisel('comput',x,1);
    set(XIDsel(4,1),'string',xtime);
    set(XIDplotw(14,2),'string',xsamp);


elseif strcmp(flag,'time')
    strsamp=get(XIDsel(4,1),'string');
    err=0;
    eval('test=eval([''['',strsamp,'']'']);','err=1;')
    if err,
     errordlg(str2mat('The entered time span could not be evaluated.',...
            'Please check your entry.'));iduisel('revert');
     return
    end
    indcol=find(strsamp==':');
    if length(indcol)==1,strsamp(indcol)=' ';end
    if length(indcol)>1
       errordlg('Use Resample to change the sampling interval.');
       iduisel('revert');
       return
    end
    x=idstrip(strsamp);
    if length(x)<2
     errordlg('You must supply both upper and lower bounds on the interval.');
     iduisel('revert');
     return
    end
    [xsamp,xtime]=iduisel('comput',x,0);
    set(XIDsel(4,1),'string',xtime);
    set(XIDplotw(14,2),'string',xsamp);

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)
        frame_no=rem(get(XIDsel(2,1),'userdata'),2)+1;
        set(XIDsel(2,1),'UserData',frame_no);
        h=get(XIDsel(3,1),'userdata');
        h=h(frame_no,:);
     eval('if get(h(2),''parent'')==curax,h=h([2 1]);,end','');
     eval(['if strcmp(get(get(h(2),''parent''),''vis''),''off''),',...
             'h=[h(1),0];end'],'h=[h(1),0];')	
     set(XIDsel(5,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');
        m1=max(yd);s1=sign(m1); 
        if s1>0,m1=1.1*m1;else m1=0.9*m1;end
        m2=min(yd);s2=sign(m2); 
        if s2<0,m2=1.1*m2;else m2=0.9*m2;end
        yl=[m1 m2];
        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(14,1),'windowbuttonmotionfcn','iduisel(''move'');');
	set(XIDplotw(14,1),'windowbuttonupfcn','iduisel(''up'');');
    iduistat('Draw rectangle with the mousebutton down.',0,14);
elseif strcmp(flag,'move'),
     h=get(XIDsel(5,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
        [xsamp,xtime]=iduisel('comput',x(1:2),0);
        set(XIDsel(4,1),'string',xtime);
        set(XIDplotw(14,2),'string',xsamp);
        
elseif strcmp(flag,'up'),
	set(gcf,'windowbuttonmotionfcn','');
	set(gcf,'windowbuttonupfcn','1;');
      iduistat('Press Insert to accept marked data set.',0,14)

elseif strcmp(flag,'revert')
       Tinfo=get(XIDsel(4,1),'UserData');
       DL=Tinfo(3);
       [xsamp,xtime]=iduisel('comput',[1 DL],1);
       set(XIDsel(4,1),'string',xtime);
       set(XIDplotw(14,2),'string',xsamp);
       frame_no=get(XIDsel(2,1),'UserData');
       if frame_no<1,return,end
       hbox=get(XIDsel(3,1),'userdata');
       h=hbox(frame_no,:);
       eval('set(h,''vis'',''off'')','')
       newframe=frame_no-1;if newframe==0;newframe=2;end
       set(XIDsel(2,1),'UserData',newframe);
       iduistat('Mark new data set.',0,14);

elseif strcmp(flag,'insert')
    if nargin==1
       [dat,dat_info,dat_no]=iduigetd('e');
       xsamp=get(XIDplotw(14,2),'string');
       indcol=find(xsamp==':');
       if length(indcol)==1,xsamp(indcol)=' ';end
       if length(indcol)>1
          errordlg('Use Resample to change the sampling interval.');
          return
       end
       xs=idstrip(xsamp);
    else
      dat=xdat;dat_info=sampflag;dat_no=arg4;xs=arg5;
    end
       Tsamp=eval(deblank(dat_info(1,:)));
       t0=eval(deblank(dat_info(3,:)));

       [SL1,dum]=size(dat_info);
       dat_info=str2mat(dat_info(1:2,:),num2str(t0+Tsamp*(xs(1)-1)),...
                int2str(xs(2)-xs(1)+1),dat_info(5:SL1,:));
       dat=dat([xs(1):xs(2)],:);
       if nargin==1,
          dat_n=get(XIDsel(2,1),'string');
       else
          dat_n=arg6;
       end
     dat_info=str2mat(dat_info,[' ',dat_n,' = ',dat_no,'([',int2str(xs(1)),...
                ':',int2str(xs(2)),'],:)']);
       xsamp=iduiinsd(dat,dat_info,dat_n);
       if nargin>1,return,end
       lstr=length(dat_n);
       if dat_n(lstr)=='e'
          set(XIDsel(2,1),'string',[dat_n(1:lstr-1),'v']);
       end
       iduistat('New data sets may now be chosen.',0,14)
elseif strcmp(flag,'done')
       frame_no=get(XIDsel(2,1),'UserData');
       indx=6:frame_no;
       if ~isempty(indx),delete(idnonzer(XIDsel(indx))),end
%       set(XIDplotw(14,1),'windowbuttondownfcn','');
       set(XIDplotw(14,1),'visible','off')
      
elseif strcmp(flag,'dtrend')
       [dat,dat_info,dat_no]=iduigetd('e');
      dat=dtrend(dat,xdat);
      dat_n=[dat_no,'d'];
      dat_info=str2mat(dat_info,...
               [' ',dat_n,' = dtrend(',dat_no,',',int2str(xdat),')']);
       if nargin<3,sampflag=1;end
       xsamp=iduiinsd(dat,dat_info,dat_n,sampflag);

elseif  strcmp(flag,'decim')
       [dat,dat_info,dat_no]=iduigetd('e');
      cwin=gcf;
      erflag=0;R=0;
      eval('R=eval(get(findobj(cwin,''tag'',''decfact''),''string''));',...
           'erflag=1;');
      if R<=0|erflag
         errordlg('The resampling factor must be positive number.');
         return
      end
      [rz,cz]=size(dat);
      if R>rz/2
         errordlg('The resampling factor must be less than half the number of data points.');
         return
      end
      [dat,Ract] = idresamp(dat,R);
      dat_n=get(findobj(cwin,'tag','dataname'),'string');
      [N,dum]=size(dat);
      Tsamp=eval(deblank(dat_info(1,:)))*Ract;[rda,cda]=size(dat_info);
      dat_info=str2mat(num2str(Tsamp),dat_info(2:3,:),int2str(N),...
                dat_info(5:rda,:),...
               [' ',dat_n,' = idresamp(',dat_no,',',num2str(R),')']);
       iduiinsd(dat,dat_info,dat_n);

elseif strcmp(flag,'revert_io')
   [dat,dat_info,dat_n]=iduigetd('e');
   set(XIDsel(3,2),'string',deblank(dat_info(7,:)));
   set(XIDsel(4,2),'string',deblank(dat_info(6,:)));
   set(XIDsel(2,2),'string',[dat_n,'r']);
   set(findobj(XIDsel(1,2),'tag','wdname'),'string',dat_n);
elseif strcmp(flag,'revert_dec')
   [dat,dat_info,dat_n]=iduigetd('e');
   decwin=iduiwok(30);
   set(findobj(decwin,'tag','dataname'),'string',[dat_n,'c']);
   set(findobj(decwin,'tag','wdname'),'string',dat_n);

elseif strcmp(flag,'insert_io')
   [dat,dat_info,dat_n]=iduigetd('e');
   oldun=eval(['[',deblank(dat_info(7,:)),']']);   
   oldyn=eval(['[',deblank(dat_info(6,:)),']']);
   [oldny,oldnu]=iduiiono('old',dat_info,'dat');
   err=0;
   s_newun=deblank(get(XIDsel(3,2),'string'));
   eval('newun=eval([''['',s_newun,'']'']);','err=1;')
   s_newyn=deblank(get(XIDsel(4,2),'string'));
   eval('newyn=eval([''['',s_newyn,'']'']);','err=1;')
   if err
      errordlg('Channel number could not be evaluated. Check your entry.');
      return
   end
   newname=deblank(get(XIDsel(2,2),'string'));
   u_index=[];y_index=[];s_uin=[];s_yin=[];
   for ku=newun
      ku_number=find(ku==oldun);
      if isempty(ku_number)
         errordlg(['The chosen input number ',int2str(ku) ' is not available in the data set.']);
         return
      else
        u_index=[u_index,ku_number];
        s_uin=[s_uin,' ',int2str(oldny+ku_number)];
      end
   end
   for ky=newyn
      ky_number=find(ky==oldyn);
      if isempty(ky_number)
         errordlg(['The chosen output number ',int2str(ky) ' is not available in the data set.']);
         return
      else
        y_index=[y_index,ky_number];s_yin=[s_yin,' ',int2str(ky_number)];
      end
   end
   dat=dat(:,[y_index,oldny+u_index]);
   new_dat_info=str2mat(dat_info(1,:),int2str(length(y_index)),...
          dat_info(3,:),dat_info(4,:),int2str(length(u_index)),...
          s_newyn,s_newun);
   [nsr,dum]=size(dat_info);
   for kk=8:nsr
       new_dat_info=str2mat(new_dat_info,dat_info(kk,:));
   end
   new_dat_info=str2mat(new_dat_info,...
     [' ',newname,' = ',dat_n,'(:,[',s_yin,' ',s_uin,']);']);
   iduiinsd(dat,new_dat_info,newname);

elseif strcmp(flag,'done_io')
  set(XIDsel(1,2),'vis','off')

end
