import re


def expand_filenames(filename, filelist, command):
    """Expand % to filename and * to filelist in command."""
    # Escape spaces for the shell
    filename = filename.replace(" ", "\\\\\\\\ ")
    filelist = [f.replace(" ", "\\\\\\\\ ") for f in filelist]
    # Substitute % and * with escaping
    command = re.sub(r'(?<!\\)(%)', filename, command)
    command = re.sub(r'(?<!\\)(\*)', " ".join(filelist), command)
    command = re.sub(r'(\\)(?!\\)', "", command)
    return command