%IMAGESELECT   Image selection dialog box.
%   IMAGE = IMAGESELECT(PROMPTSTRING,COMPUTE)
%   creates a modal dialog box which allows you to select a single
%   image from a list. The list contains all objects of type
%   dip_image defined in the base workspace.
%
%   IMAGE is the selected image, and will be [] if the user
%   pressed "Cancel".
%
%   PROMPTSTRING is a string which appears as the text above the
%   list box.
%
%   Double-clicking on an item has the same effect as clicking the
%   OK button.
%
%   If COMPUTE is true, an extra button will be displayed, with the
%   text 'Compute'. If this button is pressed, IMAGE will contain ''
%   instead of []: ISEMPTY still returns true, but it is possible to
%   discern from the cancel button.

% (C) Copyright 1999-2001               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Cris Luengo, January 2001.
% Based on MULTISELECT which is blatantly based on LISTDLG:
%   T. Krauss, 12/7/95, P.N. Secakusuma, 6/10/97
%   Copyright (c) 1984-98 by The MathWorks, Inc.
% 29/30 March 2001: Added 'Compute' button.
%                   Fixed bug that occured when no images were defined
%                      in base workspace.
%                   Added minimum dialog box size.
% 15 September 2001: Added keyboard callback.
% 18 September 2001: Fixed bug for MATLAB 6: 'CurrentCharacter' is []
%                    after pressing shift key.

function image = imageselect(promptstring,compute)

if nargin < 2
   compute = 0;
elseif nargin < 1
   error('Invalid input.');
end
initialvalue = 1;
listbox = 1;

% Get list of defined images in base workspace (copied from dipimage).
%#function whos
liststring = evalin('base','whos');
liststring = {liststring(find(strcmp({liststring.class},'dip_image'))).name};
if isempty(liststring) | isempty(liststring{1,1})
   listbox = 0;
end
errormsg = '(no images defined in base workspace)';

% Create dialog box
fig = figure('name','DIPimage dialog', ...
             'units','pixels', ...
             'resize','off', ...
             'numbertitle','off', ...
             'KeyPressFcn',['DIP_Image_DLG_ch = double(get(gcbf,''CurrentCharacter''));',...
                            'if ~isempty(DIP_Image_DLG_ch),switch DIP_Image_DLG_ch,',...
                            'case 13,set(gcbf,''userdata'',''ok'');',...
                            'case 27,set(gcbf,''userdata'',''cancel'');',...
                            'end,end;clear DIP_Image_DLG_ch'],...
             'createfcn','', ...
             'closerequestfcn','set(gcbf,''userdata'',''cancel'')', ...
             'color',get(0,'defaultuicontrolbackgroundcolor'), ...
             'windowstyle','modal', ...
             'visible','off');

% These quantities are copied from DIPIMAGE:
leftmargin = 20;          % Space between left edge and controls
internalmargin = 10;      % Horizontal space between controls
rightmargin = 20;         % Space between right edge and controls
topmargin = 10;           % Space between top edge and controls
bottommargin = 10;        % Space between bottom edge and controls
vspacing = 6;             % Space between rows
vslack = 4;               % Extra space allotted to controls (around text)
hslack = 10;              % Extra space allotted to controls (around text)
mindlgsize = [300,200];

% Calculate sizes of uicontrol elements
h = uicontrol(fig,'Style','text','String','Select All','Visible','off');
extent = get(h,'Extent');
controlwidth = extent(3)+hslack;
textheight = extent(4);
controlheight = textheight+vslack;
set(h,'String',promptstring);
extent = get(h,'Extent');
listwidth = extent(3);
if listbox
   % Calculate size for list box
   maxlistheight = 100;
   set(h,'String',liststring);
   extent = get(h,'Extent');
   listwidth = max(listwidth,extent(3))+hslack;
   listheight = min(extent(4)+2*vslack,maxlistheight);
else
   % Calculate size for message
   set(h,'String',errormsg);
   extent = get(h,'Extent');
   listwidth = max(listwidth,extent(3));
   listheight = extent(4); % same as textheight
end
listwidth = max(2*controlwidth+internalmargin,listwidth);
listwidth = max(mindlgsize(1)-leftmargin-rightmargin,listwidth);
dlgheight = topmargin+textheight+2*vspacing+controlheight+bottommargin;
if compute
   dlgheight = dlgheight+vspacing+controlheight;
end
listheight = max(mindlgsize(2)-dlgheight,listheight);
dlgheight = dlgheight+listheight;
dlgwidth = leftmargin+rightmargin+listwidth;
delete(h);

% Position dialog
fp = get(fig,'position');
fp = [fp(1) fp(2)+fp(4)-dlgheight dlgwidth dlgheight];  % keep upper left corner fixed
set(fig,'position',fp);

% Create controls
uicontrol(fig,'style','text','string',promptstring,...
          'horizontalalignment','left','units','pixels',...
          'position',[leftmargin,fp(4)-topmargin-textheight,...
                      listwidth,controlheight]);
uicontrol(fig,'style','pushbutton','string','Cancel',...
          'position',[fp(3)-rightmargin-2*controlwidth-internalmargin,...
                      bottommargin,controlwidth,controlheight],...
          'callback','set(gcbf,''userdata'',''cancel'')');
okbutton = uicontrol(fig,'style','pushbutton','string','OK','Enable','off',...
          'position',[fp(3)-rightmargin-controlwidth,bottommargin,...
                      controlwidth,controlheight],...
          'callback','set(gcbf,''userdata'',''ok'')');
if listbox
   listbox = uicontrol(fig,'style','listbox','string',liststring,...
             'backgroundcolor','w','max',2,'value',initialvalue,...
             'position',[leftmargin,...
                         fp(4)-topmargin-textheight-vspacing-listheight,...
                         listwidth,listheight],...
             'callback',['if(strcmp(get(gcbf,''SelectionType''),''open'')),',...
                         'set(gcbf,''userdata'',''ok''),end']);
   set(okbutton,'Enable','on');
else
   uicontrol(fig,'style','text','string',errormsg,...
             'horizontalalignment','center','units','pixels',...
             'position',[leftmargin,...
                         fp(4)-topmargin-textheight-vspacing-textheight-...
                         (listheight-textheight)/2,listwidth,textheight]);
end
if compute
   uicontrol(fig,'style','pushbutton','string','Compute',...
             'position',[fp(3)-rightmargin-controlwidth,...
                         bottommargin+controlheight+vspacing,...
                         controlwidth,controlheight],...
             'callback','set(gcbf,''userdata'',''compute'')');
end

% RUN!
set(fig,'visible','on');
waitfor(fig,'userdata')
switch get(fig,'userdata')
   case 'ok'
      image = evalin('base',liststring{get(listbox,'value')});
      %image = get(listbox,'value');
   case 'compute'
      image = '';
   otherwise
      image = [];
end
delete(fig)
