function [handles, sucess] = loadMFile( handles, filenames, filepath, saveFullFile)
% loadMFile loads an IMPACT model
% loadMFile internal function to load an IMPACT model

%   Project: IMPACT
%   Title of Code: loadMFile
%   Relevant additional documentation:
%   Developer: Carlos Gonzalez
%   External Dependencies: NA
%
%   Disclaimer
%   CAUTION: It is strongly recommended that changes to this code
%   should be avoided without first consulting with authors.


% the function to load *.m parameter file
sucess = 0;

if (nargin < 2) || isempty(filenames)
    cd1 = cd;
    % change the current path into previous one
    if ~isempty( handles.allFilepath )
        cd( handles.allFilepath );
    end
    
    [ filenames, filepath ] = uigetfile({ '*.m' },...
        'Select an IMPACT model');
    saveFullFile = fullfile(filepath, filenames);
    cd( cd1 );
end


if filenames == 0
    return
end


%% check parameter file
hWait = waitbarMLS(1, 'Loading data. This may take several seconds. Please wait...');
fullFile = fullfile(filepath, filenames);

[success, errorMsg]= checkParamFile(fullFile, 'caller');
if (success == -1)
    close(hWait);
    errordlgMLS(errorMsg,'Error');
    return
end

if (success == 0)
    close(hWait);
    uiwait(errordlgMLS(errorMsg,'Error'));
    filename = filenames;
    saveFullFile = fullfile(filepath,filename);
    % filepath = handles.wtPath;
    
    iWecType = getWecType(fullfile(filepath,filename));
    if (iWecType~=-1)
        hObject = handles.menu_newParam;
        setParams(iWecType, filename, filepath, hObject,handles);
    else
        errordlgMLS(sprintf('WEC type cannot be find in file or it has a value different from 1, 2, 3 or 4.\nPlease check the line "iWecType = XX;" in the model file'));
        sucess = -1;
        return;
    end
    
    handles.wtConfig = filenames;
    handles.wtPath = filepath;
    handles.saveFullFile = saveFullFile;
    return;
end


%% 

% input list value and string
val = get(handles.listbox1, 'Value');
if val > 3
    val = 1;
end
set(handles.listbox1, 'Value', val);
hOutput = handles.listbox1;
stInput = {'u1';'PTO Force Demand'};
set(hOutput, 'string', stInput);

% output list value and string
val = get(handles.listbox2, 'Value');
if val > 3
    val = 1;
end

hOutput = handles.listbox2;
if iWecType==1 || iWecType==2
    stOutput = {'Relative velocity'};
elseif iWecType == 3
    stOutput = {'Relative velocity';'Floater velocity'; 'Spar velocity'};
elseif iWecType == 4
    stOutput = {'Relative velocity';'Floater velocity'; 'Spar velocity';'Relative velocity X';'Floater velocity X'; 'Spar velocity X'};
else
    stOutput = {'Relative velocity'};
end
set(hOutput, 'string', stOutput);
set(handles.listbox2, 'Value', min(val,numel(stOutput)));

hOutput = handles.listbox1;
% output list value and string
val = get(hOutput, 'Value');
if iWecType==1 || iWecType==2 || iWecType==3
    stInput = {'u1';'PTO Force Demand'};
elseif iWecType == 4
    stInput = {'u1';'PTO Force Demand';'u2'};
end
set(hOutput, 'string', stInput);
set(handles.listbox1, 'Value', min(val,numel(stInput)));

handles.wtConfig = filenames;
handles.allFilepath = filepath;
handles.wtPath = filepath;
handles.saveFullFile = saveFullFile;





% string of model in design
stModels = get(handles.popupmenu_model, 'String');
if ~iscell(stModels)
    stModels = {stModels};
end
stModels(cellfun('isempty', stModels)) = [];
nModels = numel(stModels);

% model index
indModel = 0;
ModelNames = ModelName ( handles, filenames, filepath, saveFullFile);
for m = 1:nModels
   fullFileOld = fullfile(handles.Design.Models(m).wtPath, handles.Design.Models(m).wtConfig);
   fullFile = fullfile(handles.wtPath, handles.wtConfig);
   if strcmpi(fullFileOld, fullFile)
       % warning dialogue
       handle_tempFig = figureMLS('visible', 'off', 'handleVisibility', 'off');
       guidata(handle_tempFig, 'Cancel');
       hWarn = wrndlgMLS(handle_tempFig, sprintf('%s has already been loaded as %s. It will be replaced by this new model. Continue?', fullFile, stModels{m}), 'invisible');
       stModels2 = strrep(stModels, stModels{m}, ModelNames);
       uiwait(hWarn);
       button = guidata(handle_tempFig);
       close(handle_tempFig);
       if ~strcmp(button, 'OK')
           close(hWait);
           return;
       end
       
       indModel = m;
       break;
   end
end
stModels = [stModels;ModelNames];
if indModel ~= 0
    set(handles.popupmenu_model, 'Value', indModel);
    set(handles.popupmenu_model, 'String', stModels2);
else
    nModels = nModels+1;
    set(handles.popupmenu_model, 'String', stModels);
    if ~isempty(stModels)
        set(handles.popupmenu_model, 'Value', nModels);
    end
    indModel = nModels;
end


%% Design panel
% handles.Design.Models(indModel).StoredData = StoredData;
handles.Design.Models(indModel).wtConfig = handles.wtConfig;
handles.Design.Models(indModel).allFilepath = filepath;
handles.Design.Models(indModel).wtPath = handles.wtPath;
fullFileName = fullfile(handles.wtPath,handles.wtConfig);
iWecType = getWecType(fullFileName);
handles.model = indModel;
handles.iWecType = iWecType;
handles.Design.Models(indModel).iWecType = iWecType;
if iWecType==1 || iWecType==2
    zModel = wecModel1Body(fullFileName);
elseif iWecType == 3
    zModel = wecModel2Body(fullFileName);
elseif iWecType == 4
    zModel = wecModel2Body(fullFileName);
    zModelX = wecModel2BodyX(fullFileName);
    handles.Design.Models(indModel).zModelX = zModelX;
end
handles.Design.Models(indModel).zModel = zModel;


% file for Save&Load button
% may be different from loaded
handles.Design.Models(indModel).saveFullFile = handles.saveFullFile;

% Max magnitude is at resonant frequency - find the element in the vector
% and hence find the corresponding impedance.
arImpedance = 1./zModel.zModelPto.arMagnitude./zModel.zModelPto.arFreq;

arFreqInRange = find(zModel.zModelPto.arFreq<2*pi/4 &...
    zModel.zModelPto.arFreq>2*pi/16);
[~, iMaxElement] = max(zModel.zModelPto.arMagnitude(arFreqInRange)...
    .*zModel.zModelPto.arMagnitude(arFreqInRange));
rPassiveDampingGain = - arImpedance(arFreqInRange(iMaxElement));
set(handles.edit_gainPLD,'String',num2str(rPassiveDampingGain));

if iWecType == 4
    arImpedanceX = 1./zModelX.zModelPto.arMagnitude./zModel.zModelPto.arFreq;
    [~, iMaxElement] = max(1./arImpedanceX);
    
    rPassiveDampingGainX = - arImpedanceX(arFreqInRange(iMaxElement));
    set(handles.edit_gainPLDX,'String',num2str(rPassiveDampingGainX));
else
    rPassiveDampingGainX = 0;
    set(handles.edit_gainPLDX,'String','0');
    set(handles.edit_displacementLimitX,'String','0');
end

handles.gainPLD = rPassiveDampingGain;
handles.gainPLDX = rPassiveDampingGainX;

enableAsPerWEcType(handles);


%% assign file extension name & display the loaded status
set( handles.text_wtLoad, 'String', 'IMPACT model loaded');
% enable menu: modify model
set(handles.menu_modifyModel, 'Enable', 'On');
guidata(handles.menu_modifyModel,handles);
sucess = 1;
close(hWait);

