Fixed logic and renamed function to make easier to understand