Fixed some subtle bugs