Simplified and optimized the code a bit.