Complete error handling, add loop protection