Major code rewrite and clean up