Replace spaces in generated file names with underscores, and replace multiple consecutive underscores with a single underscore. Fixes #1705