Cleanup and refactor of write_emaf