Added optimizations based on Gary's code.