Refactor to use middleware, and fix all the bugs