partial rewrite and cleanup