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

% Last Modified by GUIDE v2.5 10-Aug-2009 13:56:13

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

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

warning off all

% Add path
if (~isdeployed)
    curdir = pwd;
    addpath(genpathKPM(curdir));
end

global param;

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

%close calling window and store params
if(~isempty(varargin))
    close(varargin{4}{1});
    param=varargin{4}{2};
    set(handles.path,'String',param.dataset);
    if( (not(strcmp(param.filenames,''))) && (param.headerlines==0))  %names are in external file
        set(handles.names,'String',param.filenames);
        set(handles.names,'Enable','on');
        set(handles.load_names,'Value',1);
        set(handles.browse_names,'Enable','on');
    else
        set(handles.names,'Enable','off');
        set(handles.browse_names,'Enable','off');
        if(strcmp(param.labels{1},'Var1'))  %default names
            set(handles.standard_names,'Value',1);
        else
            set(handles.names_in_file,'Value',1);
        end
    end

    if(param.type(1)=='c')  %continuous net
        set(handles.continuous,'Value',1);
    else    %discrete net
        set(handles.discrete,'Value',1);
    end
    if(param.type(2)=='s')  %static net
        set(handles.static,'Value',1);
    else   %dynamic net
        set(handles.dynamic,'Value',1);
    end
else
    %first time window is opened: variables initialization
    param=struct;
    param.dataset='';
    param.filenames='';
end

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = Step1_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 browse_path.
function browse_path_Callback(hObject, eventdata, handles)
% hObject    handle to browse_path (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;

[FileName,PathName] = uigetfile({'*.txt';'*.*'},'Select the dataset file');
if ( not(isequal(FileName,0)) && not(strcmp(param.dataset,strcat(PathName,FileName))))
    %a file has been selected and the dataset is different from previous one

    %variables initialization
    param=struct;
    param.dataset=strcat(PathName,FileName);
    set(handles.path,'String',param.dataset);
    %variable names are in file (default option)
    param.filenames='';
    set(handles.names_in_file,'Value',1);
    set(handles.names,'Enable','off');
    set(handles.names,'String','Select variables names...');
    set(handles.browse_names,'Enable','off');
    guidata(hObject,handles);
end


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

[FileName,PathName] = uigetfile({'*.txt';'*.*'},'Select the file containing variables names');
if not(isequal(FileName,0))  %a file has been selected (cancel has not been pressed)
    param.filenames=strcat(PathName,FileName);
    set(handles.names,'String',param.filenames);
    guidata(hObject,handles);
end



% --- Executes when selected object is changed in varnames.
function varnames_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in varnames
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if ( strcmp( get(hObject,'Tag') ,'load_names'))   %'Load names from external file' was selected
    set(handles.browse_names,'Enable','on');
    set(handles.names,'Enable','inactive');
else
    set(handles.browse_names,'Enable','off');
    set(handles.names,'Enable','off');
end


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

global param;

%check if a dataset was correctly selected
if(isempty(param.dataset))
    msgbox('Select a dataset before continuing!','Error','error');
    return;
end

%save info for following step

%if var names are not in file header, I need to read all rows in
%following step
param.headerlines=0;

%network type
handle_variabile=get(handles.variable,'SelectedObject');
handle_rete=get(handles.network,'SelectedObject');

switch get(handle_variabile,'Tag')
    case 'discrete'
        if strcmp(get(handle_rete,'Tag'),'dynamic')
            param.type='dd';  %discrete dynamic
        else
            param.type='ds';  %discrete static
        end
    case 'continuous'
        if strcmp(get(handle_rete,'Tag'),'dynamic')
            param.type='cd';  %continuous dynamic
        else
            param.type='cs';  %continuous static
        end
end

%calculate number of vars from dataset file
fid=fopen(param.dataset);
row=fgetl(fid);
fclose(fid);
nro=0;
while(not(isempty(row))) && not(all(isspace(row)))
    [tok row]=strtok(row);
    nro=nro+1;
end


%variable names
handle_varnames=get(handles.varnames,'SelectedObject');

if (strcmp(get(handle_varnames,'Tag'),'names_in_file')) %var names are in file header
    fid=fopen(param.dataset);
    riga=fgetl(fid);
    fclose(fid);
    for i=1:nro
        [nome riga]=strtok(riga);
        param.labels{i}=nome;
    end
    param.headerlines=1;  %skip header in following step
else
    if (strcmp(get(handle_varnames,'Tag'),'standard_names'))
        for i=1:nro
            param.labels{i}=['Var' num2str(i)];
        end
    else
        %check if file with var names was correctly selected
        if(isempty(param.filenames))
            msgbox('Select a file with variables names before continuing!','Error','error');
            return;
        end
        param.labels=textread(param.filenames,'%s', 'delimiter', '\n');
             
        if length(param.labels)==1  %names are all in one row
            clear param.labels
            param.labels={};
            fid=fopen(param.filenames);
            row=fgetl(fid);
            fclose(fid);
            nro_names=0;
            while(not(isempty(row))) && not(all(isspace(row)))
                [name row]=strtok(row);
                nro_names=nro_names+1;
                param.labels{nro_names}=name;
            end
            
        end
             
        if(length(param.labels)~=nro)  %number of variable labels different from number of variables
            msgbox('Error!! The variables name file does not match the dataset file!','Error','error');
            return;
        end
    end
end

%save number of vars
param.varnumber=nro;

if get(handles.missingcheck,'Value')

    miss=get(handles.miss,'String');
    if isempty(miss)
        errordlg('You haven''t set any missing value symbol!','Warning','modal');
        return
    else
        param.missing = miss;
    end
else
    param.missing='NA';
end

%call correct type of step2 according to chosen type of network
switch param.type
    case 'ds'  %discrete static
        h=openfig('Step2ds.fig','reuse');
        guidata(hObject,handles);
        eventData=[];
        varargin{1}='Step1'; %varargin contains name of form that calls the following one
        varargin{2}=param;
        Step2ds(h,eventData,handles,varargin);
    case 'dd'  %discrete dynamic
        h=openfig('Step2dd.fig','reuse');
        guidata(hObject,handles);
        eventData=[];
        varargin{1}='Step1'; %varargin contains name of form that calls the following one
        varargin{2}=param;
        Step2dd(h,eventData,handles,varargin);
    case 'cs'   %continuous static
        h=openfig('Step2cs.fig','reuse');
        guidata(hObject,handles);
        eventData=[];
        varargin{1}='Step1'; %varargin contains name of form that calls the following one
        varargin{2}=param;
        Step2cs(h,eventData,handles,varargin);
    case 'cd'  %continuous dynamic
        h=openfig('Step2cd.fig','reuse');
        guidata(hObject,handles);
        eventData=[];
        varargin{1}='Step1'; %varargin contains name of form that calls the following one
        varargin{2}=param;
        Step2cd(h,eventData,handles,varargin);
end

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

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


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

if get(hObject,'Value')
    set(handles.miss,'Enable','on');
else
    set(handles.miss,'Enable','off');
end






