REFACTOR code and changed some logic