fixed some fatal error.

Also add some protections of functions.