Refactored a bit, added some comments