Refactored, added some comments