factor out cleanup & fail functions