Added some logic, fixed some bugs