function varargout = sltpda_control(varargin)
% SLTPDA_CONTROL M-file for sltpda_control.fig
%      SLTPDA_CONTROL, by itself, creates a new SLTPDA_CONTROL or raises the existing
%      singleton*.
%
%      H = SLTPDA_CONTROL returns the handle to a new SLTPDA_CONTROL or the handle to
%      the existing singleton*.
%
%      SLTPDA_CONTROL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SLTPDA_CONTROL.M with the given input arguments.
%
%      SLTPDA_CONTROL('Property','Value',...) creates a new SLTPDA_CONTROL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before sltpda_control_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to sltpda_control_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help sltpda_control

% Last Modified by GUIDE v2.5 04-May-2007 09:13:16

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sltpda_control_OpeningFcn, ...
                   'gui_OutputFcn',  @sltpda_control_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before sltpda_control is made visible.
function sltpda_control_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to sltpda_control (see VARARGIN)

% Choose default command line output for sltpda_control
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes sltpda_control wait for user response (see UIRESUME)
% uiwait(handles.main);

% load logo and display in axes
logo = imread('images/sltpda.jpg');
image(logo, 'Parent', handles.logoAxes) 
set(handles.logoAxes,'Visible', 'off');


% make a timer object which gets the currently selected SIMULINK model
csyst = timer();
set(csyst, 'TimerFcn', {@setCurrentModel,handles.currentModelTxt});
set(csyst, 'Period', 0.5, 'ExecutionMode', 'FixedRate');
start(csyst);
setappdata(handles.main, 'csyst', csyst);

% % make a timer object which gets the parameters for the current block
% cbt = timer();
% set(cbt, 'TimerFcn', {@setCurrentBlock,handles});
% set(cbt, 'Period', 0.5, 'ExecutionMode', 'FixedRate');
% start(cbt);
% setappdata(handles.main, 'cbt', cbt);

% setup loops
loops = [];
setappdata(handles.main, 'loops', loops);



% --- Outputs from this function are returned to the command line.
function varargout = sltpda_control_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes during object creation, after setting all properties.
function main_CreateFcn(hObject, eventdata, handles)
% hObject    handle to main (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes on button press in openToolboxBtn.
function openToolboxBtn_Callback(hObject, eventdata, handles)
% hObject    handle to openToolboxBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

open('sltpda.mdl')



% --- Executes on button press in openModel.
function openModel_Callback(hObject, eventdata, handles)
% hObject    handle to openModel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Pop-up dialog box to choose model file
[filename, pathname] = uigetfile({'*.mdl', 'sLTPDA Model File';
                                  '*.xml', 'LTPDA XML AO File'},...
                        'MDL-file input',...
                        'MultiSelect', 'on');

if filename ~= 0
  % Loop over selected files
  if iscellstr(filename)
    nfiles = length(filename);
    for f=1:nfiles
      [path, name, ext, vers] = fileparts(char(filename(f)));
      switch ext
        case '.mdl'
          infile = fullfile(pathname, char(filename(f)));     
        case '.xml'          
          % make mdl file from ao
          a = ao(char(filename(f)));
          mdlfilename = get(a, 'mdlfilename');
          mdlfilein = get(a, 'mdlfile');
          idx = strfind(mdlfilein, '\n');
          % convert mdlfile to a file
          fd = fopen(mdlfilename, 'w+');
          for j=1:length(idx)-1
            i1 = idx(j)+2;
            i2 = idx(j+1)-1;
            fprintf(fd, '%s\n', mdlfilein(i1:i2));
          end
          fprintf(fd, '}\n');
          fclose(fd);
          
          infile = mdlfilename;
        otherwise
          error('### unknown file type.');
      end
      open_system(infile);
    end
  else
    [path, name, ext, vers] = fileparts(char(filename));
    switch ext
      case '.mdl'
        infile = fullfile(pathname, char(filename));
      case '.xml'
        % make mdl file from ao
        a = ao(char(filename));
        mdlfilename = get(a, 'mdlfilename');
        mdlfilein = get(a, 'mdlfile');
        idx = strfind(mdlfilein, '\n');
        % convert mdlfile to a file
        fd = fopen(mdlfilename, 'w+');
        for j=1:length(idx)-1
          i1 = idx(j)+2;
          i2 = idx(j+1)-1;
          fprintf(fd, '%s\n', mdlfilein(i1:i2));
        end
        fprintf(fd, '}\n');
        fclose(fd);

        infile = mdlfilename;
      otherwise
        error('### unknown file type.');
    end
    open_system(infile);
  end
end

% --- Executes on button press in runModel.
function runModel_Callback(hObject, eventdata, handles)
% hObject    handle to runModel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% get current model name
model = get(handles.currentModelTxt, 'String');
sltpda_execute_loops(model);

% --- Executes during object creation, after setting all properties.
function currentModelTxt_CreateFcn(hObject, eventdata, handles)
% hObject    handle to currentModelTxt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

%--------------------------------------------------------------------------
% 
function setCurrentModel(obj, event, handles)

try
  set(handles, 'String', gcs);
catch
  set(handles, 'String', '');
end


% --- Executes on button press in writeMfileBtn.
function writeMfileBtn_Callback(hObject, eventdata, handles)
% hObject    handle to writeMfileBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% get model
model = get(handles.currentModelTxt, 'String');
% get m-file name
[filename, pathname, filteridx] = uiputfile('*.m', 'Save m-file as', [model '_mfile_.m']);

if ~isempty(filename)
  mfile = fullfile(pathname, filename);  
  if sltpda_verify_model(model)
    % parse model file
    cmds = sltpda_parse_model(model);
    % write m file
    sltpda_cmds2m(model, cmds, mfile);
    % edit
    edit(mfile);
  end
end

%--------------------------------------------------------------------------
% set the current block parameters
% 
function setCurrentBlock(handles)

bh  = get_param(gcb, 'handle');
cmd = getCmdFromHandle(bh, handles);
setappdata(handles.main, 'currentBlock', cmd)

try
  set(handles.parametersHeaderTxt, 'String', ['Parameters for ' gcb]);
  
  % get parameters from cmd structure
  pl = cmd.plist;
  plist = [];
  for j=1:length(pl.params)
    p = pl.params(j);
    plist = [plist cellstr(p.key)];
  end
  set(handles.paramsList, 'String', plist);
  
catch
  set(handles.parametersHeaderTxt, 'String', 'Parameters');
end

% --- Executes when user attempts to close main.
function main_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to main (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% cbt = getappdata(handles.main, 'cbt');
% stop(cbt);
% delete(cbt);

csyst = getappdata(handles.main, 'csyst');
stop(csyst);
delete(csyst);

% Hint: delete(hObject) closes the figure
delete(hObject);


% --- Executes on button press in editLoopsBtn.
function editLoopsBtn_Callback(hObject, eventdata, handles)
% hObject    handle to editLoopsBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on selection change in paramsList.
function paramsList_Callback(hObject, eventdata, handles)
% hObject    handle to paramsList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns paramsList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from paramsList

keys = get(hObject, 'String');
key  = keys{get(hObject,'Value')};

% get the current block
cmd = getappdata(handles.main, 'currentBlock')

p = find(cmd.plist, key)

if isnumeric(p)
  set(handles.paramEdit, 'String', num2str(p));
elseif ischar(p)
  set(handles.paramEdit, 'String', p);
elseif isa(p, 'specwin')
  set(handles.paramEdit, 'String', p.name)
else
  warning('!!! unknown parameter type.');
end


% --- Executes during object creation, after setting all properties.
function paramsList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to paramsList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function paramEdit_Callback(hObject, eventdata, handles)
% hObject    handle to paramEdit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of paramEdit as text
%        str2double(get(hObject,'String')) returns contents of paramEdit as a double


% --- Executes during object creation, after setting all properties.
function paramEdit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to paramEdit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in loopList.
function loopList_Callback(hObject, eventdata, handles)
% hObject    handle to loopList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns loopList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from loopList


% --- Executes during object creation, after setting all properties.
function loopList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to loopList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%--------------------------------------------------------------------------
% get cmd from handle
function cmd = getCmdFromHandle(blockhandle, handles)

model = get(handles.currentModelTxt, 'String')
if sltpda_verify_model(model)
    % parse model file
    cmds = sltpda_parse_model(model);
    for j=1:length(cmds)
      if cmds(j).handle == blockhandle
        cmd = cmds(j);
        break;
      end
    end
end


% --- Executes on button press in loadCurrentBlock.
function loadCurrentBlock_Callback(hObject, eventdata, handles)
% hObject    handle to loadCurrentBlock (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

setCurrentBlock(handles);


% --- Executes on button press in addLoopBtn.
function addLoopBtn_Callback(hObject, eventdata, handles)
% hObject    handle to addLoopBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

contents = get(handles.paramsList,'String');
key = contents{get(handles.paramsList,'Value')};

% Find this key in current block
cmd = getappdata(handles.main, 'currentBlock')

% make new loop
loop.block  = cmd.name;
loop.handle = cmd.handle;
loop.key    = key;
loop.values = get(handles.paramEdit, 'String');
loop.on     = 1;

% get existing loops
loops = getappdata(handles.main, 'loops');

% add this loop
if ~isempty(loop.values)
  loops = [loops loop];
  setappdata(handles.main, 'loops', loops);
end


% set list
setLoopList(handles);


%--------------------------------------------------------------------------
% set loops into list
function setLoopList(handles)

loops = getappdata(handles.main, 'loops');

% build list of strings
objlist = [];
for j=1:length(loops)
  l = loops(j);
  if l.on
    str    = [sprintf('%s: %s  ', l.block, l.key) num2str(l.values) ' on'];
  else
    str    = [sprintf('%s: %s  ', l.block, l.key) num2str(l.values) ' off'];
  end
  objlist = strvcat(objlist, str);

end

set(handles.loopList, 'String', objlist);
set(handles.loopList, 'Value', 1);


% --- Executes on button press in pzmodelGuiBtn.
function pzmodelGuiBtn_Callback(hObject, eventdata, handles)
% hObject    handle to pzmodelGuiBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

pzmodel_helper;


% --- Executes on button press in clearLoopsBtn.
function clearLoopsBtn_Callback(hObject, eventdata, handles)
% hObject    handle to clearLoopsBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

setappdata(handles.main, 'loops', []);

% set list
setLoopList(handles);


% --- Executes on button press in executeLoopsChk.
function executeLoopsChk_Callback(hObject, eventdata, handles)
% hObject    handle to executeLoopsChk (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of executeLoopsChk


% --- Executes on button press in deleteLoops.
function deleteLoops_Callback(hObject, eventdata, handles)
% hObject    handle to deleteLoops (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in loopOnOff.
function loopOnOff_Callback(hObject, eventdata, handles)
% hObject    handle to loopOnOff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

loops    = getappdata(handles.main, 'loops');
vals     = get(handles.loopList,'Value');

for j=1:vals
  if loops(j).on
    loops(j).on = 0;
  else
    loops(j).on = 1;
  end    
end

setappdata(handles.main, 'loops', loops);
setLoopList(handles);
