Fixed various potential crashes and compiler warnings