fix code quality and add safety checks