Optimize code and add comments