Refactored a bit, but I'm still not happy with it.