protected function finalize($temp, $to, $upload)
    {
        if (!isset($this->destination)) {
            $this->transferred = $temp;
            return true;
        }

        $directory = gplcart_file_absolute(gplcart_file_relative($this->destination));
        $pathinfo = $upload ? pathinfo($to) : pathinfo($directory);

        if ($upload) {
            $filename = $this->prepareFileName($pathinfo['filename'], $pathinfo['extension']);
        } else {
            $filename = $pathinfo['basename'];
            $directory = $pathinfo['dirname'];
        }

        if (!file_exists($directory) && !mkdir($directory, 0775, true)) {
            unlink($temp);
            throw new UnexpectedValueException($this->translation->text('Unable to create @name', array(
                '@name' => $directory)));
        }

        $destination = "$directory/$filename";

        if ($upload) {
            $destination = gplcart_file_unique($destination);
        }

        $copied = copy($temp, $destination);
        unlink($temp);

        if (!$copied) {
            throw new UnexpectedValueException($this->translation->text('Unable to move @source to @destination', array(
                '@source' => $temp,
                '@destination' => $destination)));
        }

        chmod($destination, 0644);
        $this->transferred = $destination;
        return true;
    }