Parentheses added and codes have been optimized