I modified the code based on your comments