Fix crash bugs and add unit tests