function config = rok_parse_config_ini (filename)
    % config = ROK_PARSE_CONFIG_INI (filename)
    %
    % Parses config INI file into structure.
    %
    % Input:
    %  - filename = config file name
    %
    % Output:
    %  - config = resulting config structure
    %
    % Note: this function uses INI2STRUCT, however, it attempts to convert
    % the resulting stuctures fields, using EVAL. If a field is a string,
    % it is attempted to be converted by EVAL; if that fails, the original
    % string is kept. If a field is a substructure, its fields are
    % recursively converted.
    %
    % NOTE: this function stores the filename of the INI file into
    % config.sourceIniFilename field.
    %
    % Copyright (C) 2011-2012, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    % Parse the ini
    config = ini2struct(filename);
    
    % Convert fields
    config = convert_fields(config);
    
    % Store filename
    config.source_ini_filename = filename;
end

function s = convert_fields (s)
    % Go over all field names
    names = fieldnames(s);
    
    % If field is structure, convert it recursively
    for i = 1:numel(names),
        if isstruct( s.(names{i}) ),
            % Recursively convert struct
            s.(names{i}) = convert_fields( s.(names{i}) );
        else
            % Convert field
            s.(names{i}) = convert_field( s.(names{i}) );
        end
    end
end

function e = convert_field (str)
    try
        % Try evaluating the string
        e = eval( str );
    catch error,
        % If it doesn't work, return string
        e = str;
    end
end