Make sure data dir exists before using pwrite
Fixed bug where wrong reference element was chosen