function iduisess(arg,Pathn,Filen)
%IDUISESS Handles load and save session as well as renaming of session.
%	Arguments:
%	load    Load session
%	save    Save session
%	save_as Save session as ...
%	direct  Load session directly from file menu

%	L. Ljung 4-4-94
%	Copyright (c) 1986-95 by the MathWorks, Inc.
%       $Revision: 1.17 $  $Date: 1995/06/01 21:44:09 $

global XIDsumb XIDcounters XIDposm XIDposd XIDposm1 XIDposd1 XIDhw
global XIDsbmen XIDsessions
iduistat('');
if strcmp(arg,'direct')
  mennr=Pathn;
  filen=get(XIDsbmen(mennr),'userdata');
  pathn=get(XIDsbmen(mennr),'tag');
  if strcmp('open',get(XIDsbmen(1),'tag'))
     othersess=[1:2*(mennr-6),2*(mennr-5)+1:8];
     XIDsessions=XIDsessions([othersess,2*(mennr-6)+1:2*(mennr-6)+2],:);
  end
  iduisess('load',pathn,filen);
elseif strcmp(arg,'load')
  gcm=get(gcf,'currentmenu');
  if strcmp(get(gcm,'tag'),'open'),msg='Open';else msg='Merge';end
  if nargin<2
   iduistat('Enter path and file name in the dialog.')
   flag=0;
   eval('[file_name,path_name]=uigetfile(''*.sid'',[msg,'' Session'']);',...
        'flag=1;')
   if flag
      iduistat('The file does not exist.')
      return
   end
   nopath=0;
  else
   file_name=Filen;path_name=Pathn;
   if isempty(Pathn),nopath=1;else nopath=0;end
   dotnr=find(file_name=='.');
   if isempty(dotnr),file_name=[file_name,'.sid'];end
  end
   iduistat(['Opening session ',file_name,' ...'])
   if isstr(file_name)
     err=0;
     eval(['load(''' path_name file_name ''',''-mat'')'],'err=1;')
     if err
        errordlg(['The file ',path_name,file_name,' cannot be found or cannot be loaded.']);
        return
     end
     stopp=0;
     eval('board_numbers;','stopp=1;')
     if stopp
        errordlg('The file is not an ident session file. Please check file name.');
        return
     end
     [kDc,dum]=size(dats);
     [kMc,dum]=size(mods);
     sessname=file_name;
     dotnr=find(sessname=='.');
     if ~isempty(dotnr),sessname=sessname(1:dotnr(1)-1);end
     hnr=XIDsumb(1);
     emp=[findobj(hnr,'tag','dataline','vis','on');...
          findobj(hnr,'tag','modelline','vis','on')];
     if isempty(emp),nono=[];else nono=1;end % List of non-empty boards
     cursbs=findobj(0,'tag','sitb30');%Current summary boards
     sbnr=1;    % List of current summary board numbers
     for hnr=cursbs(:)'
         nrb=get(hnr,'userdata');
         sbnr=[sbnr,nrb];
         emp=[findobj(hnr,'tag','dataline','vis','on');...
              findobj(hnr,'tag','modelline','vis','on')];
         if ~isempty(emp),nono=[nono,nrb];end
     end
     % Renumber boards if necessary:
     if ~isempty(nono)
         if isempty(XIDposd1),iddmtab(2);end
         lbn=length(board_numbers);
         maxnr=length(nono)+lbn;newlist=1:maxnr;
         for kk=nono
           newlist=newlist(find(newlist~=kk));
         end
         newlist=newlist(1:lbn);
         board_numbers=sort(board_numbers);
         for kk=lbn:-1:1
           if newlist(kk)~=board_numbers(kk)
             eval('indxd=find(datp(:,1)==board_numbers(kk));','indxd=[];')
             datp(indxd,1)=newlist(kk)*ones(1,length(indxd))';
             eval('indxm=find(modp(:,1)==board_numbers(kk));','indxm=[];')
             modp(indxm,1)=newlist(kk)*ones(1,length(indxm))';
             if board_numbers(kk)~=1
                eval(['notes',int2str(newlist(kk)),'=notes',...
                    int2str(board_numbers(kk)),';'])
             else
                eval(['notes',int2str(newlist(kk)),'=[''This was the main window in the session '',file_name,''.''];'])
                for ki=indxm'
                   knrim=find(all((XIDposm==ones(16,1)*modp(ki,2:5))'));
                   modp(ki,2:5)=XIDposm1(knrim,:);
                end
                for ki=indxd'
                   knrid=find(all((XIDposd==ones(8,1)*datp(ki,2:5))'));
                   datp(ki,2:5)=XIDposd1(knrid,:);
                end
             end
           end
         end
         board_numbers=newlist;
         newsess=0;
     else
         newsess=1;
         set(XIDsumb(1),'userdata',[path_name,file_name]);
         set(XIDsumb(1),'name',['ident: ',sessname])

     end  % isempty(nono)
     for kbn=board_numbers
       if kbn>1
         create=0;
         eval(['if ~(strcmp(get(XIDsumb(kbn),''tag''),''sitb30'')',...
               '&get(XIDsumb(kbn),''userdata'')==kbn),create=1;end'],...
               'create=1;')
         if create,iddmtab(kbn);end
         texth=findobj(XIDsumb(kbn),'tag','notes');
         eval(['set(texth,''string'',notes',int2str(kbn),')'])
       end
     end
     for kc=1:kDc
      datn=['dat',int2str(kc)];
      hax=iduiinsd(eval(datn),eval([datn,'_info']),...
          deblank(dats(kc,:)),0,datp(kc,:));
      if newsess
	  if kc==working_data,idinseva(hax,'seles',1);end
	  if kc==validation_data,idinseva(hax,'selva',1);end
      end
     end
     for kc=1:kMc
      modn=['mod',int2str(kc)];
      iduiinsm(eval(modn),eval([modn,'_info']),deblank(mods(kc,:)),0,...
                                               modp(kc,:));
     end
   end %isstring
   if newsess,
      XIDcounters(5)=0;
      XIDsessions=str2mat(file_name,path_name,XIDsessions);
      XIDsessions=XIDsessions(1:8,:);
      for ksess=1:4  % Update direct file menus
         [label,acc]=menulabel(['&',int2str(ksess),' ',...
                     deblank(XIDsessions(2*ksess-1,:))]);
         set(XIDsbmen(ksess+5),'label',label,...
                'userdata',deblank(XIDsessions(2*ksess-1,:)),...
                     'tag',deblank(XIDsessions(2*ksess,:)));
      end
      idlaytab('save_file');
      set(XIDsbmen([3,5]),'enable','on');
      if ~nopath,set(XIDsbmen(4),'enable','on'),end
      [label,acc]=menulabel('&Merge session... ^o');
      set(XIDsbmen(1),'label',label,'tag','merge');
   else
      XIDcounters(5)=1;
   end
  iduistat('Session open. Use Views or double-click (right/middle mouse) on icons for more info.')
elseif strcmp(arg,'save')
   if nargin<2
      PathFileName=get(XIDsumb(1),'userdata');
      if isempty(PathFileName),iduisess('save_as'),return,end
   else 
      if nargin<3,Filen='';end
      PathFileName=[Pathn,Filen];
   end
   iduistat(['Saving session to ',PathFileName,' ...'])
      working_data=get(get(XIDhw(3,1),'zlabel'),'userdata');
      validation_data=get(get(XIDhw(4,1),'zlabel'),'userdata');
      sumb=[XIDsumb(1);findobj(get(0,'children'),'flat','tag','sitb30')];
      models=[];data=[];mods=[];dats=[];km=0;kd=0;modp=[];datp=[];
      board_numbers=[];
      for ksb=sumb(:)'
        modnr=findobj(ksb,'tag','modelline','vis','on');
        datnr=findobj(ksb,'tag','dataline','vis','on');
        kwinname=get(ksb,'name');
        kpar1=find(kwinname=='(');kpar2=find(kwinname==')');
        if isempty(kpar1)
            wino=1;
        else
            wino=eval(kwinname(kpar1+1:kpar2-1));
        end
        board_numbers=[board_numbers,wino];
        if wino>1
        notetext=get(findobj(ksb,'tag','notes'),'string');
        eval(['notes',int2str(wino),'=notetext;'])

        end
        for kc=modnr(:)'
         km=km+1;
         kcp=get(kc,'parent');kcnam=findobj(kcp,'tag','name');
         mod_nam=deblank(get(kcnam,'string'));modn=['mod',int2str(km)];
         if isempty(mods),mods=mod_nam;else mods=str2mat(mods,mod_nam);end
	 modp=[modp;[wino,get(kcp,'pos'),get(kc,'color')]];
         eval([modn,'=get(kc,''UserData'');'])
         eval([modn,'_info=get(kcnam,''UserData'');'])
      end
      for kc=datnr(:)'
         kd=kd+1;
         kcp=get(kc,'parent');datatag=get(kcp,'tag');
         if strcmp(datatag,working_data)
            working_data=kd;
         end
         if strcmp(datatag,validation_data)
            validation_data=kd;
         end
         kcnam=findobj(kcp,'tag','name');
         mod_nam=deblank(get(kcnam,'string'));modn=['dat',int2str(kd)];
         if isempty(dats),dats=mod_nam;else dats=str2mat(dats,mod_nam);end
	 datp=[datp;[wino,get(kcp,'pos'),get(kc,'color')]];
         eval([modn,'=get(kc,''UserData'');'])
         eval([modn,'_info=get(kcnam,''UserData'');'])
      end
     end

     clear datnr modnr kc kd km modn wino kcp kcnam ans arg 
     clear coln data  kbn kk kpar1 kpar2 ksb kwinname lfn
     clear models notetext sumb XIDsumb XIDcounters XIDhw
     clear XIDposm XIDposd XIDposm1 XIDposd1 XIDsbmen XIDsessions
     err=0;
     eval(['save(''' PathFileName ''')'],'err=1;')
     if err,
        errordlg(str2mat('Save failed. Check your writing privileges.'));
        return
     end
     % Only when save successful do we set the clean flag
     XIDcounters(5)=0;
     iduistat([PathFileName,' saved.'])
elseif strcmp(arg,'save_as')
   iduistat('Enter path and file name in the dialog.')
   [filen,pathn]=uiputfile('*.sid','Save Session');
   iduistat('') 
   if any(filen=='(')|any(filen==')')
      errordlg('Parentheses are not allowed in filenames.');
      return
   end
   if isstr(filen)
     dotnr=find(filen=='.');if isempty(dotnr),filen=[filen,'.sid'];end
     lasterr('')
     iduisess('save',pathn,filen);
   else
     return
   end
   if ~isempty(lasterr),
      % Saving errored, so return
      return
   end
   set(XIDsumb(1),'userdata',[pathn,filen]);
   dotnr=find(filen=='.');
   if ~isempty(dotnr),sessname=filen(1:dotnr-1);else sessname=filen;end
   set(XIDsumb(1),'name',['ident: ',sessname])
   extras=findobj(get(0,'children'),'flat','tag','sitb30');
   for ksb=extras(:)'
        kwinname=get(ksb,'name');
        kpar1=find(kwinname=='(');kpar2=find(kwinname==')');
        set(ksb,'name',['ident: ',sessname,' ',kwinname(kpar1:kpar2)])
   end
      XIDsessions=str2mat(filen,pathn,XIDsessions);
      XIDsessions=XIDsessions(1:8,:);
      for ksess=1:4  % Update direct file menus
         [label,acc]=menulabel(['&',int2str(ksess),' ',...
                     deblank(XIDsessions(2*ksess-1,:))]);
         set(XIDsbmen(ksess+5),'label',label,...
                'userdata',deblank(XIDsessions(2*ksess-1,:)),...
                'tag',deblank(XIDsessions(2*ksess,:)),'enable','on');
      end

   set(XIDsbmen(4),'enable','on');
   idlaytab('save_file');

end
