Tidied up write_segments and fixed tests.