Some refactoring

Nothing to commit because it isn't working (see the comments), but at least it shows you how you could refactor your code.