More rewriting of packet handling code + minor refactoring