Optimized a bit by moving some code around