Moved minimize loop into its own sub-function