Sounds like you are trying to
refactor rather than
optimize...big difference. Break the problem down, and think about the functionality: what pieces of code do what, splitting these into Classes and methods. Once things are reduced down to smaller pieces it makes it easier to call from other parts of code. Without an SSCCE we truly can't provide detailed advice, but it seems to me you have a single method for your program flow which should be put through the process I just described to reduce to methods that define a certain functionality/process.