Rewrite and cleanup of code.