Fix potential bugs and compiler warnings