Refactoring
Minor fixes
Mass refactoring, fix many bugs and add some tests