Refactoring

Hi Carsten, here's some refactoring, I'm enclosing the main logic in a function so it can be reused.