added ensureDir to make sure the directory exists