Simplified some of the code and removed casting