function dummy = importapply(sisodb,ImportFig)
%IMPORTAPPLY  OK Callback for Import dialog.

%   Author(s): P. Gahinet
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.6 $  $Date: 2000/08/16 20:03:47 $

% REVISIT
dummy = [];

ImportUd = get(ImportFig,'UserData');
LoopData = sisodb.LoopData;
HG = sisodb.HG;
   
% Get values of specified models
ModelData = ImportUd.ModelData;        % initial data 
ModelList = ImportUd.ListData.Models;  % list of wkspace or MAT file models
NewP = LocalGetModel(ImportUd.Handles.ModelEdit(1),...
    ModelData.Plant,ModelList,'untitledG');
NewH = LocalGetModel(ImportUd.Handles.ModelEdit(2),...
    ModelData.Sensor,ModelList,'untitledH');
NewF = LocalGetModel(ImportUd.Handles.ModelEdit(3),...
    ModelData.PreFilter,ModelList,'untitledF');
NewC = LocalGetModel(ImportUd.Handles.ModelEdit(4),...
    ModelData.Compensator,ModelList,'untitledC');

% Start import transaction
% RE: Beware that IMPORTDATA may throw an error if data is invalid
try
    % Create transaction
    T = handle.transaction(get(findpackage('sisodata'),'DefaultDatabase'));
    set(T,'Name','Import','OperationStore','on','InverseOperationStore','on');
    
    % Import data to LoopData (may error out)
    importdata(LoopData,NewP,NewH,NewF,NewC);
    
    % Updated system name, feedback sign, and loop configuration
    LoopData.SystemName = get(ImportUd.Handles.SystemNameEdit,'String');
    LoopData.FeedbackSign = ModelData.FeedbackSign;
    LoopData.Configuration = ModelData.Configuration;
    
    % Commit and register transaction
    register(LoopData,T);
    
    % Notify peers of data change
    dataevent(LoopData,'all');
catch
    % Invalid data: abort
    delete(T)
    
    % Parse error message and remove leading "Error..."
    errmsg = lasterr;
    idx = findstr('Error',errmsg);
    if ~isempty(idx)
        [junk,errmsg] = strtok(errmsg(idx(end):end),sprintf('\n'));
    end
    % Pop up error dialog and abort apply
    errordlg(strtok(errmsg,sprintf('\n')),'Import Error')
    return
end


% Close system data view if open
% REVISIT: should update
DataViews = sisodb.DataViews;
delete(findobj(DataViews(ishandle(DataViews)),'flat','Tag','SystemView'))

% Update status bar and history
sisodb.send('StatusChanged',sisodata.dataevent(sisodb,'StatusChanged',...
    {'Imported model data. Right-click on the plots for design options.';...
        'Imported new system/compensator models.'}));

% Close import figure
close(ImportFig)


%--------------------------Local Functions------------------------

%%%%%%%%%%%%%%%%%%%%%
%%% LocalGetModel %%%
%%%%%%%%%%%%%%%%%%%%%
function NewModel = LocalGetModel(EditBoxHandle,CurrentModel,ModelList,DefaultName)
% Returns the new model based on the user input in the given edit box

EditData = get(EditBoxHandle,'UserData');
ListIndex = EditData.ListIndex;
String = EditData.String;

% Initialize to current model
NewModel = CurrentModel;

% Process user input
if isempty(ListIndex)
    % Nothing entered. Try re-evaluating (refresh)
    try
        NewValue = evalin('base',String,'[]');
        if isMatch(NewValue,CurrentModel.Model)
            if isvarname(String)
                % Watch for '1'
                NewModel.Name = String;
            end
            NewModel.Model = NewValue;
        end
    end
    
elseif ListIndex>0,
    % Selected listbox entry
    NewModel.Name = String;
    NewModel.Model = ModelList{ListIndex};
    
else
    % Entered scalar or LTI model (already validated) 
    NewModel.Model = evalin('base',String);
    if evalin('base',sprintf('exist(''%s'')',String))==1
        % Valid variable in Workspace: keep its name
        NewModel.Name = deblank(String);
    else
        % Use default name
        NewModel.Name = DefaultName;
    end
end


%%%%%%%%%%%%%%%
%%% isMatch %%%
%%%%%%%%%%%%%%%
function boo = isMatch(NewModel,CurrentModel)
% Determine if new value is admissible (variable may have been overwritten)

if ~isequal(size(NewModel),[1 1])
    boo = 0;
elseif isreal(NewModel)
    boo = 1;
elseif ~isa(NewModel,'lti')
    boo = 0;
else
    boo = isequal(NewModel.Ts,CurrentModel.Ts);
end
    
