Implement flood protection, refactor main loop