You don't really need the loop below. A function with the loop body and two calls would reduce the size of this function considerably.