refactor output file name generation

Lots of duplicated code removed.