Refactored code and added some assertions