Cleaned up logic and added comments