Paul suggests you to divide the whole problem into three functions, that would be called sequentally (inside the main "loop", that repeats continuosly; is the orthodox procedure)
Each one are the three parts I told you to develop separately.
Regards.