Some improvements in organization of code

We organized all the code to allow reuse and a better understanding of
what is happening in each part, separately.