Various style changes, updated some comments and variable names and extracted a helper function for validation.