Partial rewrite, new features and fixes