Major refactoring, first functional version.