There's a lot of duplicated cleanup code, I think it should _probably_ be refactored into using goto.