% Input:
% path: String (path to the file)
% name: String (filename)

% Output:
% path: String (path to the file)
% name: String (filename)
% filetype: String (filetyp)
% Vars: cell array of strings (variable names)
% n: integer (dimensionality of the model)
% Input: cell array of strings (names of the input parameters)
% states: cell array of structs
% q: vector of integers (state ids)
% qa: integer (start location)
% transitions: cell array of structs
% qq: matrix of integers (describing the transitions)
% I: function handle (initial set)
% U: function handle (input set)
% deltafile: double (timestep)

% Description:
% Allows the user to chose an input file (*.mdl or *.m) using a dialog and extracts all
% informations contained in the model file

function [path,name,filetype,Vars,n,Input,states,q,qa,transitions,qq,I,U,delta,N] = choseFile(path,name)
Vars = [];
Input = [];
I = [];
U = [];
delta = [];
N = [];
qq = [];

if isempty(path) && isempty(name)
    [name,path] = uigetfile({'*.m','Code files (*.m)';'*.mdl','Stateflow Diagram (*.mdl)'},'File Selector');
    addpath(path);
end;

func = regexprep(name,'\.(.)*',''); 
filetype = regexp(name,'\.\w*','match');

if strcmp( filetype, '.m')
    
    [states,q,qa,transitions,I,U,configuration] = feval(func);
    if ~isempty(configuration)
        delta = configuration.timestep;
        N = configuration.timehorizon/configuration.timestep;
    end;
    
    if isempty(states) || isempty(q)
        error('No location modeled');
    end;
    
    if isempty(qa) || ~ismember(qa,q)
        error('No valid initial location specified');
    end;
    
    if isempty(I)
        error('Missing initial set');
    end;
    
    n = size(states{1}.A,1);    % retrieve dimensionality
    
    if ~isempty(transitions)
        qq = zeros(2,length(transitions));
        for i=1:length(transitions)
            qq(:,i) = [transitions{i}.from; transitions{i}.to];
        end;
    end;
    
elseif strcmp( filetype, '.mdl')
    % I,U are read using the GUI
    input.name = name;
    input.path = path;
    [Vars,n,Input,states,q,qa,transitions,qq] = loadStateflow(input);
    
else
    error('Unknown file extension !');
end;