Code optimized and comments added