Cleanup and fix some bugs