Lots of refactoring and added in key retrieval