Refactor error functions; make re-entrant