Fix some nasty bugs