Substantial refactor.

Passed compilation only, no tests have been performed.