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

% Last Modified by GUIDE v2.5 10-Aug-2009 16:24:35

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Step2dd_OpeningFcn, ...
    'gui_OutputFcn',  @Step2dd_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 Step2dd is made visible.
function Step2dd_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 Step2dd (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 Step2dd
handles.output = hObject;


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

param.data=textscan(fid,format,'delimiter','\t','headerLines',param.headerlines);
fclose(fid);

%substitute missing values with the mode
for i=1:param.varnumber
    index_NA=find(strcmpi(param.data{i},param.missing));
    if (not(isempty(index_NA)))
        %string without NA
        temps=param.data{i}(setdiff(1:length(param.data{i}),index_NA));
        %count string occurrences
        %(tabulate(x) creates a frequency table of data in vector x
        %1st column: the unique values of x;
        %2nd column: the number of instances of each value)
        count=tabulate(temps);
        [ma ind]=max(cell2num(count(:,2)));
        %in the case max is more than 1
        ind=ind(1);
        param.data{i}(index_NA)=count(ind,1);
    end
end

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

%common control: maxpar
mpar=javax.swing.SpinnerNumberModel(2, 1, param.varnumber,1);
parspin=uicomponent('style','JSpinner','Model',mpar,'position',[360 335 100 25]);
param.maxpar=parspin;

param.savedir=0;

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


%find variables states and calculate node size
for i=1:param.varnumber
    temp=param.data{i};
    param.states{i}=unique(temp);
    param.ns(i)=length(param.states{i});
    clear temp
end

%warning: one or more variables have more than 30 states: maybe var type is
%continuous?
if any(param.ns>20)
    msgbox('There is at least one variable with more than 20 possible states! Please check that network type has been correctly selected.','Warning!!','warn');     
end

%map variables into numbers according to the position in param.states
%(alphabetical order)
for i=1:param.varnumber
    temp=param.data{i};
    for j=1:param.ns(i)
        for k=1:length(temp)
            if(strcmp(temp{k},param.states{i}(j)))
                temp{k}=j;
            end
        end
    end
    param.data{i}=cell2mat(temp);

end

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = Step2dd_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}='Step2dd'; %in varargin there is the name of the calling form
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 type of network has been chosen
global param;
global bar;

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

%visualize controls for progression 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

d=cell2mat(param.data)';
seqs={num2cell(d)};

[dag CPTnode]= learn_struct_dbn_reveal_f(seqs, param.ns, maxpar);

mkdir(param.savedir)
write_probs_discrete(param.labels, param.states, CPTnode, dag, 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 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_discrete


% --- 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

