Some fixes for SG mode

Hi Andy,
I'm trying to get SG mode to work, so far I've resolved some build and memory freeing issues in the commits above. The worse part is that sgverify has apparently been broken for quite awhile, sometime between commits cf46259363085a17753d418a5754620923ac06f6 and afa513ea3508285b6141bce7aa4be18da573e85f , I doubt if I'll have the time to delve into this.