rename mode to flags and add a few check to prevent NULL-ptr-deref