Cherry pick from 7254840ac9: Better way of handling scripts. Still needs improvement.