%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function selectedFilenames = CustomListDlg(arg)
%
% Description: A custom built list dialog that allows the user to specify a
% regular expression to filter the filenames.
%
% Dr. A. I. Hanna (2005)
function [selectedFilenames, values] = CustomListDlg(arg)
global CustomDlgList_figure_handle
if iscell(arg)
    CustomDlgList_figure_handle = openfig(mfilename, 'reuse');
    % Generate a structure of handles to pass to callbacks, and store
    Data.handles = guihandles(CustomDlgList_figure_handle);
    Data.handles.figMain = CustomDlgList_figure_handle;
    Data.handles.filenames = arg;
    set(Data.handles.filenamelist, 'String', Data.handles.filenames);
    guidata(CustomDlgList_figure_handle, Data);
    uiwait(CustomDlgList_figure_handle);
    if ~ishandle(CustomDlgList_figure_handle)
        values = [];
        selectedFilenames = 0;
        return;
    end
    info = get(CustomDlgList_figure_handle, 'UserData');
    selectedFilenames = info.selectedFilenames;
    values = info.indices;
    delete(CustomDlgList_figure_handle);
else
    Data = guidata(CustomDlgList_figure_handle);
    switch arg
        case 'Ok'
            [Data.handles] = Ok(Data.handles);
        case 'Cancel'
            [Data.handles] = Cancel(Data.handles);

        case 'SelectAll'
            set(Data.handles.filenamelist, 'value', 1:length(Data.handles.filenames));
        case 'Filter'
            [Data.handles] = Filter(Data.handles);

        otherwise
            error('Not a valid CustomListDlg function\n');
    end
    guidata(CustomDlgList_figure_handle, Data);
end
%%%%%%%%%%%%%%%%
%
% Ok
%
%%%%%%%%%%%%%%%%
function [handles] = Ok(handles)
v = get(handles.filenamelist, 'value');
info.selectedFilenames = handles.filenames(v);
info.indices = v;
set(handles.figMain, 'UserData', info);
uiresume;
return;
%%%%%%%%%%%%%%%%
%
% Cancel
%
%%%%%%%%%%%%%%%%
function [handles] = Cancel(handles)
info.selectedFilenames = {};
info.indices = [];
set(handles.figMain, 'UserData', info);
uiresume;
return;
%%%%%%%%%%%%%%%%
%
% Filter
%
%%%%%%%%%%%%%%%%
function [handles] = Filter(handles)
prompt={sprintf('Example, *10*20*  for all files containing\nthe strings "10" followed by "20"\ni.e. P10abc20qrs\n\nRegular Expression')};
name='Input for Regular Expression';
numlines=1;
defaultanswer={''};
answer=inputdlg(prompt,name,numlines,defaultanswer);
ind =[];
selectedFilenames={};
if ~isempty(answer)
    % replace the * wildcard by \w* that is the wildcard for regexprep
    answer2=regexprep(answer,'*','\\w*');
    [reg_files,a,b] = regexp(handles.filenames, answer2, 'match','start','end');
    for i=1:length(reg_files)
        if length(reg_files{i}) >0
            selectedFilenames=[selectedFilenames,handles.filenames(i)];
            ind=[ind, i];
        end
    end
end
% set(CustomDlgList_figure_handle, 'UserData', selectedFilenames);
set(handles.filenamelist, 'value', ind);
return;