Fix duplicate newlines being printed.
Fix buffer overflow found by Coverity scan.

Also remove redundant check at end of loop, document variables.