Refactoriezed the code a little as suggested by cahirwpz.
Hope nothing changed (for worse) in the semantics ;)