Refactoring

Some refactoring to make parts of the script easier to understand and to test.

Regards.