def increment_filename(filename):
    """
    Increment a counter on the filename, so that duplicate filenames can be avoided.
    We do this by adding a counter as a path component at the start of the filename,
    so that the original name is not changed.
    """
    if '/' not in filename:
        counter = 0
        rest = filename
    else:
        counter, rest = filename.split('/', 1)
        try:
            counter = int(counter)
        except ValueError:
            # eg. foo/bar.pdf -> 1/foo/bar.pdf
            counter = 0
            rest = filename

    return '%d/%s' % (counter + 1, rest)