cleanup emulation code and fix some bugs