Refactor emulator with its tests.