added some logic, did some refactoring