Fixed various small errors and potential bugs