Cleanup the script generation, make something data driven if possible, at least splitting it into methods would be a good idea.