modified to create directories if they don't exist