Rewrote using for-comprehensions, also a bit of cleanup