refactored envelope handling