Added comments, improved logic and formatting