Optimize and write script.