Match output filenames to input filename; refactor