Add unit-tests and fix deep bugs