Refactored, added some simplifications