Added some error triggers, optimized code