Fixed some nasty bugs