added most of the handle_packet function