function string = rok_format_filename (format, varargin)
    % STRING = ROK_FORMAT_FILENAME (FORMAT, VARARGIN)
    %  Creates a filename from format, replacing %c with camera number
    %  ('camera'), %f with frame number ('frame') and %i with iteration 
    %  number ('iteration'), and so on.
    %
    %  Input:
    %   - FORMAT = format string
    %   - VARARGIN = string/value pairs for substitution
    %
    %  Output:
    %   - STRING = string with all the substitutions performed
    %
    %  Valid substitutions:
    %   - '%c', camera
    %   - '%f', frame
    %   - '%i', iteration
    %   - '%p', person
    %   - '%m', modality
    %
    %  Example:
    %  filename = rok_pom_sprintf('C%c-%f.png', 'camera', 1, 'frame', 10)
    %  >> filename = C1-10.png
    %
    %  Copyright (C) 2011-2012, Rok Mandeljc <rok.mandeljc@fe.uni-lj.si>
    
    % Input validation
    p = inputParser;
    p.addRequired('format', @ischar);
    p.addOptional('camera', []);
    p.addOptional('frame', []);
    p.addOptional('iteration', []);
    p.addOptional('person', []);
    p.addOptional('modality', []);
    
    p.parse(format, varargin{:});
    
    % Assign
    format = p.Results.format;
    camera = p.Results.camera;
    frame = p.Results.frame;
    iteration = p.Results.iteration;
    person = p.Results.person;
    modality = p.Results.modality;
        
    
    % Create replacement map
    fmt = {};
    rpl = {};
    
    [ fmt, rpl ] = append_replacement(fmt, rpl, '%c', camera);
    [ fmt, rpl ] = append_replacement(fmt, rpl, '%f', frame);
    [ fmt, rpl ] = append_replacement(fmt, rpl, '%i', iteration);
    [ fmt, rpl ] = append_replacement(fmt, rpl, '%p', person);
    [ fmt, rpl ] = append_replacement(fmt, rpl, '%m', modality);
    
    % Replace using regex
    string = regexprep(format, fmt, rpl);
end

function [ fmt, rpl ] = append_replacement (fmt, rpl, format, replacement)
    if isempty(replacement),
        return;
    end
    
    if isa(replacement, 'char'),
        fmt{end+1} = format;
        rpl{end+1} = num2str(replacement);
    elseif isa(replacement, 'numeric'),
        fmt{end+1} = format;
        rpl{end+1} = num2str(replacement);
    else 
        error('Rok:FormatFilename:InvalidReplacementType', 'Invalid replacement type for format ''%s''', format);
    end
end

