clean up some vars, and finish the apply function