Fixed various potential bugs and compiler warnings