removed unnecessary nil checks, simplified code and added comments