functions should be at top now

I've moved all of the named subfunctions to the top of the function.