using screen program as serial terminal. output line by line.

There is nothing in that code that understands where a packet starts and ends. You need to send some kind of "Hey, this is the end of a packet; you can use the data now" marker. That whole sketch is based on the erroneous assumptions that all the data that is a packet will arrive very quickly, and that there will be a significant pause between packets.

Not robust code at all.