Fix up bugs and bring code in line with coding guidelines