Add unit test but it is not finished. Fixed several bugs that cause crash.