Fixes segfaults and adds tests