Major code review and rewrite