Added unit tests and fix segfault