function varargout = loopgui(varargin)
% LOOPGUI M-file for loopgui.fig
%      LOOPGUI, by itself, creates a new LOOPGUI or raises the existing
%      singleton*.
%
%      H = LOOPGUI returns the handle to a new LOOPGUI or the handle to
%      the existing singleton*.
%
%      LOOPGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LOOPGUI.M with the given input arguments.
%
%      LOOPGUI('Property','Value',...) creates a new LOOPGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before loopgui_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to loopgui_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 loopgui

% Last Modified by GUIDE v2.5 12-Jun-2007 20:24:04

% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @loopgui_OpeningFcn, ...
                   'gui_OutputFcn',  @loopgui_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 loopgui is made visible.
function loopgui_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 loopgui (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

set(handles.loopLevelSelect, 'String', {'1','2','3','4','5'});
set(handles.loopLevelSelect, 'Value', 1);

% get my block handles
myh = get_param(gcb, 'handle');
setappdata(handles.main, 'loopBlockHandle', myh);


% parse model elements and get block list that
% have parameters that can be looped over
blockhandles   = find_system(gcs, 'FindAll', 'on', 'type', 'block');
blocks = [];
k      = 1;
for j=1:length(blockhandles)
  b = blockhandles(j);
  maskType = get(b, 'MaskType');
  if ~strcmp(maskType, 'loop')
    maskParams = get(b, 'MaskNames');
    get(b)
    if ~isempty(maskParams)
      name      = get(b, 'Name');
      if ~strcmp(name, 'variable')
        parent    = get(b, 'Parent');
        name = [parent '/' name];
        blocks(k).handle = b;
        blocks(k).name   = name;
        k = k+1;
      end
    end
  end
end

setappdata(handles.main, 'blocks', blocks);

% Fill list
bnames = [];
for j=1:length(blocks)
  bnames = [bnames cellstr(blocks(j).name)];
end
set(handles.blockList, 'String', bnames)

% get current loop
getLoop(handles);

% set current value for selected block/param
setCurrentValues(handles)

% show current block settings
showBlockSettings(handles)


%--------------------------------------------------------------------------
% get the current loop and set lists accordingly
% 
function getLoop(handles)

myh    = getappdata(handles.main, 'loopBlockHandle');
blocks = getappdata(handles.main, 'blocks');

set(handles.main, 'Name', get(myh, 'Name'))

%--------- Set indices for lists
% get mask values
maskVals = get(myh, 'MaskValues');
bname    = maskVals{1};
% find block in list which matches the current loop settings
blistIdx = 1;
for j=1:length(blocks)
  b = blocks(j);
  if strcmp(b.name, bname)
    blistIdx = j;
  end
end
set(handles.blockList, 'Value', blistIdx)
% set params list
setParamsList(handles)

% set param to the key in loop block
params = get(handles.paramList, 'String');
param  = maskVals{3};
pidx = 1;
for j=1:length(params)
  if strcmp(params{j}, param)
    pidx = j;
  end
end
set(handles.paramList, 'Value', pidx);

%--------------------------------------------------------------------------
% set parameters list from currently selected block
% 
function setParamsList(handles)

% get block handle
bhandle = getblockhandle(handles);

% get mask params for this block
maskparams = get(bhandle, 'MaskNames');
set(handles.paramList, 'String', maskparams);


% --- Outputs from this function are returned to the command line.
function varargout = loopgui_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 on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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 popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1


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

% Hint: popupmenu 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 blockList.
function blockList_Callback(hObject, eventdata, handles)
% hObject    handle to blockList (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 blockList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from blockList

set(handles.paramList, 'Value', 1);
setParamsList(handles)
setCurrentValues(handles)

% --- Executes during object creation, after setting all properties.
function blockList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to blockList (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


% --- Executes on selection change in paramList.
function paramList_Callback(hObject, eventdata, handles)
% hObject    handle to paramList (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 paramList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from paramList

setCurrentValues(handles)

%--------------------------------------------------------------------------
% Set values edit box to current value
function setCurrentValues(handles)

param = getparam(handles);
bh    = getblockhandle(handles);
blocks = getappdata(handles.main, 'blocks');

% find relevant block
for j=1:length(blocks)
  b = blocks(j);
  if b.handle == bh
    % get maskNames
    maskparams = get(bh, 'MaskNames');
    for k=1:length(maskparams)
      if strcmp(maskparams{k}, param)
        validx = k;
      end
    end    
  end
end

% get mask values
maskvals = get(bh, 'MaskValues');
set(handles.paramValsEdit, 'String', maskvals{validx})


% --- Executes during object creation, after setting all properties.
function paramList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to paramList (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 paramValsEdit_Callback(hObject, eventdata, handles)
% hObject    handle to paramValsEdit (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 paramValsEdit as text
%        str2double(get(hObject,'String')) returns contents of paramValsEdit as a double


% --- Executes during object creation, after setting all properties.
function paramValsEdit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to paramValsEdit (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 button press in setLoopBtn.
function setLoopBtn_Callback(hObject, eventdata, handles)
% hObject    handle to setLoopBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% get block
bh    = getblockhandle(handles);
bname = getblockname(handles);

% get param
param = getparam(handles);

% get values
vals = cellstr(get(handles.paramValsEdit, 'String'));

level = get(handles.loopLevelSelect, 'Value');

setBlockSettings(handles, bh, bname, param, vals, 'on', level)

%--------------------------------------------------------------------------
% get name of currently selected param
function param = getparam(handles)

params = get(handles.paramList, 'String');
param  = params{get(handles.paramList, 'Value')};


%--------------------------------------------------------------------------
% get block name of currently selected block
function bname = getblockname(handles)

bnames = get(handles.blockList, 'String');
bname  = bnames{get(handles.blockList, 'Value')};

%--------------------------------------------------------------------------
% get block handle of currently selected block
function bh = getblockhandle(handles)

% get possible blocks
blocks = getappdata(handles.main, 'blocks');

% which block is selected
blist = get(handles.blockList, 'String');
bsel  = blist{get(handles.blockList, 'Value')};

% get handle for selected block
for j=1:length(blocks)
  if strcmp(blocks(j).name, bsel)
    bh = blocks(j).handle;
    return
  end
end

%--------------------------------------------------------------------------
% Show current setting on GUI
function showBlockSettings(handles)

% get settings from block
myh = getappdata(handles.main, 'loopBlockHandle');

% get mask values
maskVals = get(myh, 'MaskValues')

% set fields on gui
set(handles.blockname, 'String', maskVals{1});
set(handles.blockhandle, 'String', maskVals{2});
set(handles.blockkey, 'String', maskVals{3});
set(handles.blockvals, 'String', maskVals{4});
level = str2num(maskVals{6})
if isempty(level)
  level = 1;
end
if level < 1
  level = 1;
end
if level > 5
  level = 5;
end
set(handles.loopLevelSelect, 'value', level);
set(handles.blocklevel, 'String', maskVals{6});

%--------------------------------------------------------------------------
% Set current block settings to those selected
function setBlockSettings(handles, bh, bname, key, vals, state, level)

% get settings from block
myh = getappdata(handles.main, 'loopBlockHandle');

maskvals = {bname num2str(bh,20) key cell2str(vals) state num2str(level)};

set(myh, 'MaskValues', maskvals);
showBlockSettings(handles)

%--------------------------------------------------------------------------
% Convert a cell array to a space separated list of strings
function str = cell2str(c)

str = [];
for j=1:length(c)
  str = [str ' ' c{j}];
end
str = strtrim(str);


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

getLoop(handles);


% --- Executes on selection change in loopLevelSelect.
function loopLevelSelect_Callback(hObject, eventdata, handles)
% hObject    handle to loopLevelSelect (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 loopLevelSelect contents as cell array
%        contents{get(hObject,'Value')} returns selected item from loopLevelSelect


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

% Hint: popupmenu 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 loopLevelSelect.
function popupmenu4_Callback(hObject, eventdata, handles)
% hObject    handle to loopLevelSelect (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 loopLevelSelect contents as cell array
%        contents{get(hObject,'Value')} returns selected item from loopLevelSelect


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

% Hint: popupmenu 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


