A bit of refactoring
Working version