Fixed strange bug (might have introduced it with this git merge fuckup,
but thought it worked correctly before). refactored a little bit