Fix buffer length checks.
Fix writer.write return value.
Cleaner rewrite?