Rearranged the code a bit to simplify the problem of optimization.