Continuing refactoring for #130. It is moved to new system and tests are
passing. No new tests have been created yet and it is still messy.