calculate packet length, fixed some logic at writing packets