Fix and optimize code