Fixes several potential bugs and warnings