repository segfaults

I'm not totally sure of this, but I've made these changes in an attempt to fix segfaults I was seeing, and it appears they do. Could you have a look and see whether something like this might be required?

Thanks!