Fixed a series of bugs