Partial rewrite, code cleanup, bug fixes