added more logic and comments