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

% Last Modified by GUIDE v2.5 10-Aug-2009 17:25:37

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

%close previous window
close(varargin{4}{1});

%retrieve parameters
global param;
param=varargin{4}{2};

%load logo
logo=imread('logo_BMI.jpg');
image(logo);
axis off;

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

%read data from file
fid=fopen(param.dataset);
%create format string
format='';
for i=1:param.varnumber
    format=strcat(format,'%f');  %read as double precision
end

param.data=textscan(fid,format,'delimiter','\t','TreatAsEmpty',{upper(param.missing),lower(param.missing)},'headerLines',param.headerlines);
fclose(fid);

%substitute NaNs with median of values
for i=1:param.varnumber
    %find missing values
    temp=param.data{i};
    miss=find(isnan(temp));
    %find median
    me=median(temp(setdiff(1:length(temp),miss)));
    temp(miss)=me;
    param.data{i}=temp;
end


%according to the network type chosen at step1 different controls are
%displayed

%common controls: maxpar,bayes factor
mbf=javax.swing.SpinnerNumberModel(1, 1, +100, 1);
mpar=javax.swing.SpinnerNumberModel(2, 1, param.varnumber-1,1);
bfspin=uicomponent('style','JSpinner','Model',mbf,'position',[380 370 100 25]);
param.bf=bfspin;
parspin=uicomponent('style','JSpinner','Model',mpar,'position',[380 335 100 25]);
param.maxpar=parspin;

%progression bar
global bar;
bar=uicomponent('style','JProgressBar','minimum',0,'position',[220 6 290 28]);
set(bar,'Visible','off');
guidata(hObject,handles);

%by default set order with the order of vars
param.order=1:param.varnumber;

param.stepwise=0;
param.savedir=0;

%load list of variables
set(handles.varlist,'String',param.labels);
param.states=param.data;
set(handles.varvalues,'String',param.states{1});

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Step2cs wait for user response (see UIRESUME)
% uiwait(handles.figure);


% --- Outputs from this function are returned to the command line.
function varargout = Step2cs_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 button press in back.
function back_Callback(hObject, eventdata, handles)
% hObject    handle to back (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%go back to previous window
h=openfig('Step1.fig','reuse');
guidata(hObject,handles);
eventData=[];
varargin{1}='Step2cs'; %in varargin there is the name of calling window
varargin{2}=param;
Step1(h,eventData,handles,varargin);


% --- Executes on selection change in varlist.
function varlist_Callback(hObject, eventdata, handles)
% hObject    handle to varlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
indice=get(hObject,'Value');
set(handles.varvalues,'String',param.states{indice});
if(indice==1)
    set(handles.up,'Enable','inactive');
else
    set(handles.up,'Enable','on');
end
if(indice==param.varnumber)
    set(handles.down,'Enable','inactive');
else
    set(handles.down,'Enable','on');
end

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


% --- Executes during object creation, after setting all properties.
function varlist_CreateFcn(hObject, eventdata, handles)
% hObject    handle to varlist (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 varvalues.
function varvalues_Callback(hObject, eventdata, handles)
% hObject    handle to varvalues (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 varvalues contents as cell array
%        contents{get(hObject,'Value')} returns selected item from varvalues


% --- Executes during object creation, after setting all properties.
function varvalues_CreateFcn(hObject, eventdata, handles)
% hObject    handle to varvalues (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 button press in up.
function up_Callback(hObject, eventdata, handles)
% hObject    handle to up (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%need to modify string of combo box, order and states
i=get(handles.varlist,'Value');
if(i>1)
    temp=param.order(i-1);
    param.order(i-1)=param.order(i);
    param.order(i)=temp;
    temp=param.states(i-1);
    param.states(i-1)=param.states(i);
    param.states(i)=temp;
    stringa_combo=get(handles.varlist,'String');
    temp=stringa_combo(i-1);
    stringa_combo(i-1)=stringa_combo(i);
    stringa_combo(i)=temp;
    set(handles.varlist,'String',stringa_combo);
    set(handles.varlist,'Value',i-1);
else
    msgbox('The variable is already at the top of list!','Attention','warn');
end


% --- Executes on button press in down.
function down_Callback(hObject, eventdata, handles)
% hObject    handle to down (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%need to modify string of combo box, order and states
i=get(handles.varlist,'Value');
if(i<param.varnumber)
    temp=param.order(i+1);
    param.order(i+1)=param.order(i);
    param.order(i)=temp;
    temp=param.states(i+1);
    param.states(i+1)=param.states(i);
    param.states(i)=temp;
    stringa_combo=get(handles.varlist,'String');
    temp=stringa_combo(i+1);
    stringa_combo(i+1)=stringa_combo(i);
    stringa_combo(i)=temp;
    set(handles.varlist,'String',stringa_combo);
    set(handles.varlist,'Value',i+1);
else
    msgbox('The variable is already at the bottom of list!','Attention','warn');
end


% --- Executes on button press in browsedir.
function browsedir_Callback(hObject, eventdata, handles)
% hObject    handle to browsedir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
param.savedir=uigetdir;
param.savedir=fullfile(param.savedir,'results');
if(param.savedir~=0)
    set(handles.savedir,'String',param.savedir);
end


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

%see what type of network has been chosen
global param;
global bar;

%retrieve param values
bf=get(param.bf,'Value');
maxpar=get(param.maxpar,'Value');

%visualize controls for progress bar
set(handles.help,'Visible','off');
set(bar,'Visible','on');
guidata(hObject,handles);
pause(0.1);

%check that a save dir has been chosen
if(param.savedir==0)
    %hide progress bar
    set(bar,'Visible','off');
    set(bar,'value',0);
    guidata(hObject,handles);
    msgbox('You must select a directory to save results before continuing!','Error!','error');
    return;
end

nu0=3;
sigma0=1;
[dag parents beta sigma]=BNGaussian(cell2mat(param.data)',param.order,maxpar,bf,nu0,sigma0,param.stepwise);

mkdir(param.savedir)
%write conditional probabilities
write_probs_continuous(parents, beta, sigma, param.labels, param.savedir)

if isdeployed
    diruse=ctfroot;
    diruse=fullfile(diruse, 'Bayes');
else
    diruse=cd;
end

BayesGraph(dag,param.labels, diruse);
writeGML(dag,param.labels,param.savedir)


%hide progress bar
set(bar,'Visible','off');
set(bar,'value',0);
set(handles.help,'Visible','on');
guidata(hObject,handles);


% --- Executes on button press in stepwise.
function stepwise_Callback(hObject, eventdata, handles)
% hObject    handle to stepwise (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
param.stepwise=get(hObject,'Value');
% Hint: get(hObject,'Value') returns toggle state of stepwise


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


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

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



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

