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

% Last Modified by GUIDE v2.5 24-Oct-2016 11:01:38

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @save_model_OpeningFcn, ...
    'gui_OutputFcn',  @save_model_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);

global system_name;
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 save_model is made visible.
function save_model_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 save_model (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);
changes(hObject, eventdata, handles);
% UIWAIT makes save_model wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = save_model_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 listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (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
list = dir('strategies');
names = cell(1, length(list) - 2);
% ignore dot directories
for a=3:length(list)
    names{a - 2} = list(a).name(1:end - 2);
end
set(hObject, 'String', names);


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
file_name = get(handles.edit1, 'String');
if strcmp(file_name(end-3:end), '.asm')
    file_name = file_name(1:end-4);
end
[name, path] = uiputfile('*.asm', 'Select File', file_name);
if ~isa(name, 'double')
    % set full path to edit element
    set_editfield(handles.edit1, name, path);
end

function set_editfield(handles, name, path)
% set text in edit field
% handles: handle reference of edit field 
% name: model name
% path: path prefix
set(handles, 'TooltipString', name);
ext = '.asm';
if length(name) > 4 && strcmp(name(end-3:end), '.asm')
    ext = '';
end
set(handles, 'String', sprintf('%s%s%s%s', path, filesep, name, ext));

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% in a good world only one ModelReference block should exists
global system_name;
% closing the model doesn't prevent this operation
load_system(system_name);
item = find_system(system_name, 'BlockType', 'ModelReference')';
if ~isempty(item)
    % if there was a level higher element like ModelReference
    system_name = get_param(item{1}, 'ModelFile');
    system_name = system_name(1:end - 4);
end
% read out state of graphical elements
list = get(handles.listbox1, 'String');
save_path = get(handles.edit1, 'String');
optimizing = get(handles.checkbox1, 'Value');

tic();
progressbar = sprintf('started %s', datestr(clock, 'HH:MM:SS'));
set(handles.text3, 'String', progressbar);
ret = save_graph(get_graph(system_name, optimizing), save_path, optimizing, ...
    list{get(handles.listbox1, 'Value')});
if ~ret
    errordlg('Cannot save file %s !', save_path);
else
    set(handles.text3, 'String', sprintf('elapsed time: %fs', toc()));
    parts = strsplit(save_path, filesep);
    msgbox(sprintf('File %s saved.', parts{end}), 'Operation successful.');
end


function str = model_name()
global system_name;
str = system_name;
if block_level(str) > 0
    parts = strsplit(str, '/');
    str = parts{end};
end


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

set_editfield(hObject, model_name(), 'target');
if ispc && isequal(get(hObject,'BackgroundColor'), get(0, ...
        'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
global system_name;
system_name = gcs;
set(hObject, 'Name', sprintf('processing %s', model_name()));


% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (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 checkbox1


% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over pushbutton2.
function pushbutton2_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


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

% Hints: contents = cellstr(get(hObject,'String')) returns listbox2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox2
changes(hObject, eventdata, handles);

% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox2 (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
global OPTIMISATIONS;
list = OPTIMISATIONS.keys;
for a = 1 : length(list)
    list(a) = strrep(list{a}, '_',' ');
end
set(hObject, 'String', list);

function changes(hObject, eventdata, handles)
global OPTIMISATIONS;
global debug;
global verbose;

index = get(handles.listbox2, 'Value');
list = get(handles.listbox2, 'String');
if ~is_in(list{index}, {'debug', 'verbose'})
    set(handles.checkbox2, 'Value', OPTIMISATIONS(strrep(list{index}, ' ', '_')));
else
    if strcmp(list{index}, 'debug')
        set(handles.checkbox2, 'Value', debug);
    else
        set(handles.checkbox2, 'Value', verbose);
    end
end    


% --- Executes on button press in checkbox2.
function checkbox2_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox2 (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 checkbox2

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

%TODO: something goes here wrong, not the time to fix that so be quit, i'm
%working
try
    index = get(handles.listbox2, 'Value');
    list =  get(handles.listbox2, 'String');
    set(hObject, 'Value', strrep(list{index}, ' ', '_'));
catch exception
end

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global OPTIMISATIONS;
global debug;
global verbose;

index = get(handles.listbox2, 'Value');
list =  get(handles.listbox2, 'String');
if ~is_in(list{index}, {'debug', 'verbose'}) 
    OPTIMISATIONS(strrep(list{index}, ' ', '_')) = get(handles.checkbox8, 'Value');
else
    if strcmp(list{index}, 'debug')
        debug = get(handles.checkbox2, 'Value');
    else
        verbose = get(handles.checkbox2, 'Value');
    end
end
