Further refactoring, now code is compilable but still not fully working. Added some unit tests.