revised code with better documentation