Code reorganized and comments added to make more readable.