refactoring / generalizing.

still very messy...