Refactor add_asset_to_envelope() to stop duplicate filenames and reduce code nesting

Many lines of code changed, but there should be almost no functionality change. Tests pass.