Fix bugs in key generation, cleanup, refactor