protected function writeAtomic($filename, $content, $mode) {
        $temp = tempnam(dirname($filename), 'atomic');

        if (!($fp = @fopen($temp, 'wb'))) {
            $temp = dirname($filename) . '/' . uniqid('atomic');
            if (!($fp = @fopen($temp, 'wb'))) {
                trigger_error(__METHOD__." : error writing temporary file '{$temp}'", E_USER_WARNING);
                return false;
            }
        }

        $br = fwrite($fp, $content);
        fclose($fp);
        if (!$br || $br != strlen($content)) {
            unlink($temp);
            return false;
        }

        chmod($temp, $mode);

        if (!rename($temp, $filename)) {
            unlink($filename);
            rename($temp, $filename);
        }
        return true;
    }