function filename = rok_path_find_file (filename, path)
    % filename = ROK_PATH_FIND_FILE (filename, path)
    %
    % Construct a filename based on input filename and path. If filename is
    % an absolute path, no modification is done. If filename is a relative
    % path, it is applied relative to the path. Path can be a relative or
    % absolute path to a directory or a file. In the latter case, the path
    % is extracted from the filename.
    %
    % Input:
    %  - filename = name of the target file; either an absolute or a
    %    relative path
    %  - path = path to use in case filename is a relative path; can be
    %    either path to an existing directory, or an existing file
    %
    % Output:
    %  - filename = resulting filename
    %
    % NOTE: the function checks if the file exists and returns error if it
    % does not
    %
    % Copyright (C) 2011-2012, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    % If path is not given, use current directory
    if nargin < 2,
        path = pwd();
    end

    % If filename is relative, make it relative to path
    if ~isabsolute(filename),
        if exist(path, 'dir'),
            basePath = path;
        elseif exist(path, 'file'),
            [ basePath, ~, ~ ] = fileparts(path);
        else
            error('Rok:Path:InvalidPath', 'Path ''%s'' is neither a valid file nor a directory!', path);
        end
        
        filename = fullfile(basePath, filename);
    end
    
    % Check if file exists
    if ~exist(filename, 'file'),
        error('Rok:Path:NonExisting', 'File ''%s'' does not exist!', filename);
    end
end
