Code reorganized to make more readable, some comments added.