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

% Last Modified by GUIDE v2.5 10-Aug-2009 17:24:31

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

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

%retrieve parameters
global param;

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

% Choose default command line output for Step2cd
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 missing values (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);
bfspin=uicomponent('style','JSpinner','Model',mbf,'position',[350 345 100 25]);
param.bf=bfspin;
parspin=uicomponent('style','JSpinner','Model',mpar,'position',[350 300 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);

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = Step2cd_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}='Step2cd'; %in varargin there is the name of calling window
varargin{2}=param;
Step1(h,eventData,handles,varargin);


% --- 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 network type was 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)','',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

%make graph in new window
BayesGraph(dag,param.labels, diruse);

%save text-based representation of graph in GML format
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_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_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_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

