%PET_CREATE_DATAMAT_UI Creates a datamat file
%
%  USAGE: pet_create_datamat_ui(session_file)
%
%   PET_CREATE_DATAMAT_UI(session_file) creates a datamat file based the
%   session information. In addition, it provides users some flexabilities
%   like choosing different conditions to study etc.
%

%   Called by pet_session_profile_ui
%
%   I (session_file) - Matlab data file that contains a structure array
%			containing the session information for the study
%
%   Created on 25-SEP-2002 by Jimmy Shen
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function pet_create_datamat_ui(varargin)

    if nargin == 0 | ~ischar(varargin{1})

        session_file = varargin{1}{1};

        init(session_file);
        uiwait;				% wait for user finish

        close(gcf);
        return;
    end;

    %  clear the message line,
    %
    h = findobj(gcf,'Tag','MessageLine');
    set(h,'String','');

    action = upper(varargin{1});

    if strcmp(action,'MOVE_SLIDER'),
        MoveSlider;
    elseif strcmp(action,'SELECT_CONDITION'),
        SelectCondition;
    elseif strcmp(action,'UPDATE_FILENAME'),
        UpdateFileName;
    elseif strcmp(action,'DONE_BUTTON_PRESSED'),
        CreateDatamat;
    elseif strcmp(action,'CANCEL_BUTTON_PRESSED'),
        uiresume;
    elseif strcmp(action,'DELETE_FIG'),
        delete_fig;
    end

    return;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   init: Initialize the GUI layout
%
%   I (session_file) - Matlab data file that contains a structure array
%			containing the session information for the study
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function init(session_file)

    load(session_file);

    save_setting_status = 'on';
    pet_create_datamat_pos = [];

    try
       load('pls_profile');
    catch
    end

    if ~isempty(pet_create_datamat_pos) & strcmp(save_setting_status,'on')

       pos = pet_create_datamat_pos;

    else

       w = 0.5;
       h = 0.7;
       x = (1-w)/2;
       y = (1-h)/2;

       pos = [x y w h];

    end

    h0 = figure('Color',[0.8 0.8 0.8], ...
	'Units','normal', ...
        'Name','Create Datamat', ...
        'MenuBar','none', ...
        'NumberTitle','off', ...
        'deletefcn','pet_create_datamat_ui(''DELETE_FIG'');', ...
   	'Position',pos, ...
        'WindowStyle', 'modal', ...
   	'Tag','InputCondition', ...
   	'ToolBar','none');

    x = 0.01;
    y = 0;
    w = 1;
    h = 0.06;

    pos = [x y w h];

    fnt = 0.5;

    h1 = uicontrol('Parent',h0, ...		% Message Line Label
        'Style','text', ...
        'Units','normal', ...
        'BackgroundColor',[0.8 0.8 0.8], ...
        'ForegroundColor',[0.8 0.0 0.0], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
        'HorizontalAlignment','left', ...
        'Position',pos, ...
        'String','', ...
        'Tag','MessageLine');

    x = 0.06;
    y = 0.15;
    w = 0.35;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% Save as label
	'Units','normal', ...
	'BackgroundColor',[0.8 0.8 0.8], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String','Save Datamat As:', ...
	'Style','text', ...
		'visible','off', ...
	'Tag','lblFileName');


    filename = [session_info.datamat_prefix, '_PETdatamat.mat'];

    y = 0.08;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% Save as edit
	'Units','normal', ...
	'BackgroundColor',[1 1 1], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',filename, ...
	'Style','edit', ...
        'Callback','pet_create_datamat_ui(''UPDATE_FILENAME'');', ...
		'visible','off', ...
	'Tag','editFileName');

    w = 0.18;
    x = 0.52;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% CREATE
	'Units','normal', ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String','CREATE', ...
        'Callback','pet_create_datamat_ui(''DONE_BUTTON_PRESSED'');', ...
	'Tag','DONEButton');

    x = 1-0.06-w;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% CANCEL
	'Units','normal', ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String','CANCEL', ...
        'Callback','pet_create_datamat_ui(''CANCEL_BUTTON_PRESSED'');', ...
	'Tag','CANCELButton');

    w = 1;
    x = 0;
    y = 0.88;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% condition label
	'Units','normal', ...
	'BackgroundColor',[0.8 0.8 0.8], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'HorizontalAlignment','center', ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String','Select Conditions to Create Datamat', ...
	'Style','text', ...
	'Tag','lblCondition');

    x = 0.06;
    y = 0.25;
    w = 1-2*x;
    h = 0.62;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% selected condition frame
	'Units','normal', ...
	'BackgroundColor',[0.9 0.9 0.9], ...
	'Position',pos, ...
	'Style','frame', ...
	'Tag', 'frameCondition');

    w = 0.04;
    x = 1-x-w-0.003;

    pos = [x y w h];

    h1 = uicontrol('Parent',h0, ...		% v scroll bar
	'Style', 'slider', ...
   	'Units','normal', ...
   	'Min',1, ...
   	'Max',20, ...
   	'Value',20, ...
   	'Position',pos, ...
	'Enable','Off', ...
   	'Callback','pet_create_datamat_ui(''MOVE_SLIDER'');', ...
   	'Tag','sliderCondition');

    x = 0.07;
    y = 0.8;
    w = 0.06;
    h = 0.06;

    pos = [x y w h];

    c_h1 = uicontrol('Parent',h0, ...		% selected condition idx
   	'Style','text', ...
   	'Units','normal', ...
	'BackgroundColor',[0.9 0.9 0.9], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
   	'HorizontalAlignment','right', ...
   	'Position',pos, ...
   	'String','', ...
	'Visible','Off', ...
   	'Tag','idxCondition');

    x = x+w+0.01;
    w = 0.7;

    pos = [x y w h];

    c_h2 = uicontrol('Parent',h0, ...		% selected condition name
	'Units','normal', ...
	'BackgroundColor',[0.9 0.9 0.9], ...
   	'FontUnits','normal', ...
   	'FontSize',fnt, ...
	'HorizontalAlignment','left', ...
	'Position',pos, ...
	'String','', ...
	'Style','check', ...
	'Tag','checkboxCondition', ...
        'Value', 1);

    setappdata(h0,'pls_data_path',session_info.pls_data_path);
%    setappdata(h0,'behav_data_file',session_info.behav_data_file);
    setappdata(h0,'datamat_prefix',session_info.datamat_prefix);
    setappdata(h0,'num_conditions',session_info.num_conditions);
    setappdata(h0,'cond_name',session_info.condition);
    setappdata(h0,'num_subjects',session_info.num_subjects);
    setappdata(h0,'subject',session_info.subject);
    setappdata(h0,'subj_files',session_info.subj_files);

    setappdata(h0,'frame_pos', get(findobj(gcf,'Tag','frameCondition'),'Position'));
    setappdata(h0,'filename',filename);
    setappdata(h0,'cond_height', 0.06);
    setappdata(h0,'top_cond_idx', 1);
    setappdata(h0,'selected_conditions',ones(1,length(session_info.condition)));
    setappdata(h0,'session_info',session_info);
    setappdata(h0,'session_file',session_file);

    cond1_hdls = [c_h1,c_h2];			% save handles for the 1st one
    setappdata(h0,'cond_hlist', cond1_hdls);

    cond_template = copyobj(cond1_hdls,h0);
    set(cond_template, 'visible', 'off');
    setappdata(h0,'cond_template', cond_template);

    SetupConditionRows;
    SetupSlider;
    DisplayConditions;
    UpdateSlider;

    return;					% init


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   SetupConditionRows: Initially lay out all rows for the selected
%	conditions and their corresponding image files. Position is
%	determined by the listbox position.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function SetupConditionRows()

    frame_pos = getappdata(gcf,'frame_pos');
    cond_height = getappdata(gcf,'cond_height');

    rows = floor(frame_pos(4) / cond_height);

    cond_hdls = getappdata(gcf,'cond_hlist');
    cond_template = getappdata(gcf,'cond_template');

	% A row of vertical positions, at which
	% the 10 4-controls will be located.
	%
    top_pos = get(cond_hdls(1,1),'Position');
    v_pos = top_pos(2) - [0:rows-1] * cond_height;

    selete_cbf = 'pet_create_datamat_ui(''SELECT_CONDITION'');';

    nr = size(cond_hdls, 1);		% size(x,1) get # of rows. nr = 1 for the initial
    if (rows < nr)						% too many rows
        for i = rows+1:nr,
            delete(cond_hdls(i,:));
        end
        cond_hdls = cond_hdls(1:rows, :);
    else							% add new rows
        for i = nr + 1:rows
            new_c_hdls = copyobj(cond_template, gcf);
            cond_hdls = [cond_hdls; new_c_hdls'];		% stack cond_hdls
        end
    end

    v = 'Off';
    for i=1:rows

	% take out the handle list created above, and use it
	% in the following 'idx,name,colon,combo'.
	% those handles are valid, since they are all obtained
	% from function copyobj() above.
	%

        new_c_hdls = cond_hdls(i,:);

	% init each condition idx
	%
        pos = get(new_c_hdls(1),'Position'); pos(2) = v_pos(i);
        set(new_c_hdls(1),'String','','Position',pos,'Visible',v,'UserData',i);

	% init each condition name
	%
        pos = get(new_c_hdls(2),'Position'); pos(2) = v_pos(i);
        set(new_c_hdls(2),'String',' ','Position',pos,'Visible',v, ...
						'UserData',i,'Callback',selete_cbf);

    end

    setappdata(gcf,'cond_hlist', cond_hdls);
    setappdata(gcf,'NumRows',rows);

    return;						% SetupConditionRows


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   SetupSlider: Draw a slider,
%	%and use full displayed image file rows
%	%to determine the slider position.
%	and use the frame to determine the slider position
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function SetupSlider()

    pos_frame = get(findobj(gcf,'Tag','frameCondition'),'Position');
    slider_hdl = findobj(gcf,'Tag','sliderCondition');
    pos = get(slider_hdl,'Position');
    pos(2) = pos_frame(2) + 0.003;
    pos(4) = pos_frame(4) - 0.006;
    set(slider_hdl,'Position', pos);

    return;						% SetupSlider


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   DisplayConditions: Display all the selected conditions and their
%	corresponding image files.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function DisplayConditions()

    cond_name = getappdata(gcf,'cond_name');
    selected_conditions = getappdata(gcf,'selected_conditions');
    top_cond_idx = getappdata(gcf,'top_cond_idx');
    cond_hdls = getappdata(gcf,'cond_hlist');
    rows = getappdata(gcf,'NumRows');

    last_row = 0;				% no row at the beginning
    cond_idx = top_cond_idx;			% start from top row. Here's 1

    for i = 1:rows
        c_hdls = cond_hdls(i,:);
        if cond_idx <= length(cond_name)	% only display to these many rows
            set(c_hdls(1),'String',sprintf('%d.',cond_idx),'Visible','on');
            set(c_hdls(2),'String',sprintf('%s',cond_name{cond_idx}), ...
			'Value',selected_conditions(cond_idx),'Visible','on');
            cond_idx = cond_idx + 1;
            last_row = i;
        else
            set(c_hdls(1),'String','','Visible','off');
            set(c_hdls(2),'String','','Value',1,'Visible','off');
        end;
    end;

	%  display or hide the slider
	%
    if (top_cond_idx ~= 1) | (last_row == rows)
        slider_hdl = findobj(gcf,'Tag','sliderCondition');
        set(slider_hdl,'Enable','On');
    else
        slider_hdl = findobj(gcf,'Tag','sliderCondition');
        set(slider_hdl,'Enable','Off');
    end

    return;						% DisplayConditions


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   UpdateSlider: Set slider's (Min, Max, Value, Sliderstep) based on
%	how many rows of image files.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function UpdateSlider()

    top_cond_idx = getappdata(gcf,'top_cond_idx');
    cond_name = getappdata(gcf,'cond_name');
    num_cond = length(cond_name);
    rows = getappdata(gcf,'NumRows');
    total_rows = num_cond + 1;		% so, Max-Min = total_rows - 1
    slider_hdl = findobj(gcf,'Tag','sliderCondition');

    if (num_cond ~= 0)			% don't need to update when no cond
        set(slider_hdl, 'Min', 1, 'Max', total_rows, ...
		'Value', total_rows - top_cond_idx + 1, ...
		'Sliderstep', [1/(total_rows-1)-0.00001, 1/(total_rows-1)]);
    end

    return;						% UpdateSlider


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   MoveSlider: Respond to move slider action by changing the top index
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function MoveSlider()

    slider_hdl = findobj(gcf,'Tag','sliderCondition');
    slider_value = round(get(slider_hdl,'Value'));

    total_rows = round(get(slider_hdl,'Max'));

	% when slider_value = 1, top_cond_idx will be total_rows
	%
    top_cond_idx = total_rows - slider_value + 1;	% see above fcn
    setappdata(gcf,'top_cond_idx',top_cond_idx);
    DisplayConditions;

    return;						% MoveSlider


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   UpdateFileName: Respond to modifying Save As Edit
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function UpdateFileName()

    filename = get(findobj(gcf,'Tag','editFileName'),'String');
    setappdata(gcf,'filename',filename);

    return;					% UpdateFileName


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   SelectCondition: Respond to the Select Checkbox
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function SelectCondition()

    selected_conditions = getappdata(gcf,'selected_conditions');
    cond_hdls = getappdata(gcf,'cond_hlist');
    row_idx = get(gcbo,'UserData');
    cond_idx = str2num(get(cond_hdls(row_idx,1),'String'));

    if selected_conditions(cond_idx)		% make selected unselected
        selected_conditions(cond_idx) = 0;
    else					% make unselected selected
        selected_conditions(cond_idx) = 1;
    end;

    setappdata(gcf,'selected_conditions',selected_conditions);

    DisplayConditions;
    UpdateSlider;

    return;						% SelectCondition


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   CreateDatamat: Create Datamat file
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function CreateDatamat()

    tic

    curr = pwd;
    if isempty(curr)
       curr = filesep;
    end

    savepwd = curr;
    savefig = gcf;
    % file_change_flag = 0;

    selected_conditions = getappdata(gcf,'selected_conditions');
    k = sum(selected_conditions);
    if(~k)
        msg = sprintf('No condition was selected.');
        set(findobj(gcf,'Tag','MessageLine'),'String',['ERROR: ', msg]);
        return;
    end
    n = getappdata(gcf,'num_subjects');
    kk = getappdata(gcf,'num_conditions');

    %  in behavdata, only rows that corresponded to selected_conditions
    %  should be selected
    %
    session_info = getappdata(gcbf,'session_info');

    if isfield(session_info, 'behavdata')
       behavdata = session_info.behavdata;
    else
       behavdata = [];
    end

    if isfield(session_info, 'behavname')
       behavname = session_info.behavname;
    else
       behavname = {};
    end

%    behav_data_file = getappdata(gcf,'behav_data_file');
    if ~isempty(behavdata)
%        behavdata = load(behav_data_file);
        mask = repmat(selected_conditions, [n, 1]);

        % remember: reshape start by columnwise (1st dim), then 2nd, 3rd, ...
        %
        mask = reshape(mask, [1, kk*n]);
        mask = find(mask);
        behavdata = behavdata(mask,:);
    end

    home = getappdata(gcf,'pls_data_path');
    filename = getappdata(gcf,'filename');
    datamat_prefix = getappdata(gcf,'datamat_prefix');

    subject = getappdata(gcf,'subject');
    subj_files = getappdata(gcf,'subj_files');

    % add path for all subject
    %
    for i = 1:kk
        for j = 1:n
            subj_files{i,j} = [subject{j}, filesep, subj_files{i,j}];
        end
    end

    subj_files = subj_files(find(selected_conditions == 1),:);

    progress_hdl = rri_progress_ui('initialize', 'Creating Datamat');

    [dims, voxel_size, origin] = rri_imginfo(subj_files{1,1});
    dims = [dims(1) dims(2) 1 dims(3)];

    section1 = n*k/(n*k+10);		% 1st section of progress bar
    factor = 1/(n*k+10);		% factor for the 2nd section

    rri_progress_ui(progress_hdl, '', 0.5*factor);

    tdatamat=[];
    for i = 1:k

        temp=[];

        for j=1:n
            message=['Loading condition ',num2str(i),', subject ',num2str(j),'.'];
            rri_progress_ui(progress_hdl,'Loading Images',message);

            % img = image_load(subj_files{i,j});
            img = rri_load_img(subj_files{i,j});
            img = reshape(img,[size(img,1)*size(img,2),size(img,4)]);
            temp = [temp; img(:)'];
        end

        tdatamat=[tdatamat;temp];
        rri_progress_ui(progress_hdl, '', ((i-1)*n+j)*factor);

    end

    message = 'Selecting only the brain voxels ...';
    rri_progress_ui(progress_hdl,'Building datamat',message);

    [dr,dc]=size(tdatamat);
    imgsize = dc;
    mask=ones(1,dc);

    factor = 0.1/dr;			% factor for the 2nd section

    for i=1:dr
        mask = mask .* (tdatamat(i,:) > (max(tdatamat(i,:))/4));
        rri_progress_ui(progress_hdl,'',section1+(i*factor)*(1-section1));
    end

    % remap data to eliminate non-brain voxels
    [datamat,coords]=rri_remap(tdatamat,mask);

%    raw_datamat = datamat;

    % perform whole-brain ratio adjustment
    gmean=mean(datamat,2);		% grand mean for each image

    [dr,dc]=size(datamat);

    rri_progress_ui(progress_hdl,'Normalizing datamat',section1+0.2*(1-section1));

    message = 'Normalize datamat with its volume mean ...';
    rri_progress_ui(progress_hdl,'',message);

    factor = 0.8/dc;			% factor for the 2nd section
    checkpoint = floor(dc/10);		% set check point
    check = checkpoint;
    percentage = 10;

    for i=1:dc
        datamat(:,i)=datamat(:,i)./gmean;	% normalized on the mean of each img

        if(i==check)
            rri_progress_ui(progress_hdl,'',section1+(0.2+i*factor)*(1-section1));
            message = [num2str(percentage), '% of the volume is normalized.'];
            rri_progress_ui(progress_hdl,'',message);
            check = check + checkpoint;
            percentage = percentage + 10;
        end
    end

    message = 'Saving to the disk ...';
    rri_progress_ui(progress_hdl,'Save',message);

    elapsed_time = toc;
%    disp('Datamat is created ...');

    % save to disk

    datamatfile = [home, filesep, filename];

    if(exist(filename,'file')==2)	% datamat file with the same file name exist

        dlg_title = 'Confirm File Overwrite';
        msg = ['File ',filename,' exist. Are you sure you want to overwrite it?'];
        response = questdlg(msg,dlg_title,'Yes','No','Yes');

        if(strcmp(response,'No'))

            cd(home);

            putfile_filter = [datamat_prefix,'*datamat.mat'];
            [filename, pathname] = uiputfile(putfile_filter,'Save As',350,150);

            if isequal(filename,0)
                datamatfile = [];
                close(progress_hdl);

                msg1 = ['WARNING: No file is saved.'];
                % msgbox(msg1,'Uncomplete');
                %uiwait(msgbox(msg1,'Uncomplete','modal'));
                set(findobj(gcf,'Tag','MessageLine'),'String',msg1);

                uiresume;
                return;
            else
                datamatfile = fullfile(pathname, filename);
            end

            % file_change_flag = 1;

        end
    end

    session_file = getappdata(gcbf,'session_file');
    session_info = getappdata(gcbf,'session_info');
    selected_conditions = getappdata(gcbf,'selected_conditions');
    create_ver = plsgui_vernum;

    done = 0;

    while ~done
       try
          save(datamatfile,'datamat','coords','behavdata','behavname', ...
		'dims','voxel_size','origin','session_file','session_info', ...
		'selected_conditions','create_ver');
          done = 1;
       catch
            putfile_filter = [datamat_prefix,'*datamat.mat'];
            [filename, pathname] = uiputfile(putfile_filter, ...
		'Can not save datamat file, please try again',350,150);

            if isequal(filename,0)
                datamatfile = [];
                close(progress_hdl);

                msg1 = ['WARNING: No file is saved.'];
                % msgbox(msg1,'Uncomplete');
                %uiwait(msgbox(msg1,'Uncomplete','modal'));
                set(findobj(gcf,'Tag','MessageLine'),'String',msg1);

                uiresume;
                return;
            else
                datamatfile = fullfile(pathname, filename);
            end
       end
    end

    cd(savepwd);

    close(progress_hdl);

%    msg1 = ['Datamat file "',datamatfile,'" has been created and saved on your hard drive.'];
%    msg2 = ['The total elapse time to build this datamat is ',num2str(elapsed_time),' seconds.'];

%    uiwait(msgbox({msg1;'';msg2},'Completed','modal'));
%%    uiwait(msgbox(msg1,'Completed','modal'));
    %% msgbox({msg1;'';msg2},'Completed');	% however, this works for PC

   msg1 = ['WARNING: Do not change file name manually in command window.'];
   uiwait(msgbox(msg1,'File has been saved'));

    uiresume;
    return;					% CreateDatamat


%----------------------------------------------------------------------------
function delete_fig

    try
       load('pls_profile');
       pls_profile = which('pls_profile.mat');

       pet_create_datamat_pos = get(gcbf,'position');

       save(pls_profile, '-append', 'pet_create_datamat_pos');
    catch
    end

    return;

