Fix some code bugs, add some checks for possible issues