MASSIVE code rewrite