some refactoring + bug fixes in key generation