Fix bug when writing more than 512 bytes