public function save($sessionId, $data, $existingProfiles, FileInfo $fileInfo)
    {
        $rawData = [];
        $rawData['data'] = $data;
        $rawData['profiles'] = $existingProfiles;

        $dataString = $this->serializer->serialize($rawData);
        $filename = $this->generateFilenameForDataFile($sessionId);

        $tempFilename = tempnam(dirname($filename), basename($filename));
        $writeResult = @file_put_contents($tempFilename, $dataString);
        if ($writeResult === false) {
            throw new AsmException(
                "Failed to write session data.",
                AsmException::IO_ERROR
            );
        }
        $tempLockFileHandle = null;

        if ($fileInfo->lockFileHandle) {
            $this->validateLock($sessionId, $fileInfo);
        }
        else {
            $tempLockFileHandle = $this->acquireLock(
                $sessionId,
                5000,
                1000
            );
        }

        //We have the lock - it's safe to replace the datafile
        $renamed = rename($tempFilename, $filename);
        
        if ($tempLockFileHandle) {
            fclose($tempLockFileHandle);
        }

        if (!$renamed) {
            throw new AsmException(
                "Failed to save session data during rename of file",
                AsmException::IO_ERROR
            );
        }
    }