bigger refactoring which should improve speed and mem usage. fixes #96