Fix buffer drain and rearrange state flow