Fix #7522 by checking for empty byte buffers a little more

Quite a few lines have changed but that is mostly comments.
Add test for #7522