modified slightly to ensure that if a directory is passed as the path, file will be generated there.