Cleanup and correcting some bugs