make use of the mainloop code

Use the mainloop we added in the previous patch.
Some reorg is needed with the functions, they are moved up and down
to prevent forward declarations.

Signed-off-by: Daniel Lezcano <daniel.lezcano@linaro.org>
5 files changed