edited possible overflows, fixed undefined.  Tried to fix more emergency handling.