Fixed some messy casting and made the code more readable.