fixes #461 and a potential segfault

Also includes a couple of style fixes (trailing newlines).