rearrenged the code in functions

I think now is more clear.