optimized script generation function