protected function start_current_file($archivepath, $filesize, $mtime,
            tgz_extractor_handler $handler = null) {
        global $CFG;

        $this->currentarchivepath = $archivepath;
        $this->currentmtime = $mtime;
        $this->currentfilesize = $filesize;
        $this->currentfileprocessed = 0;

        if ($archivepath === tgz_packer::ARCHIVE_INDEX_FILE) {
            // For index file, store in temp directory.
            $tempfolder = $CFG->tempdir . '/core_files';
            check_dir_exists($tempfolder);
            $this->currentfile = tempnam($tempfolder, '.index');
        } else {
            if ($this->mode === self::MODE_LIST) {
                // If listing, add to list.
                $this->listresults[] = (object)array(
                        'original_pathname' => $archivepath,
                        'pathname' => $archivepath,
                        'mtime' => $mtime,
                        'is_directory' => false,
                        'size' => $filesize);

                // Discard file.
                $this->currentfile = true;
            } else {
                // For other files, ask handler for location.
                $this->currentfile = $handler->tgz_start_file($archivepath);
                if ($this->currentfile === null) {
                    // This indicates that we are discarding the current file.
                    $this->currentfile = true;
                }
            }
        }
        $this->filebuffer = '';
        $this->filebufferlength = 0;

        // Open file.
        if ($this->currentfile !== true) {
            $this->currentfp = fopen($this->currentfile, 'wb');
            if (!$this->currentfp) {
                throw new moodle_exception('errorprocessingarchive', '', '', null,
                        'Failed to open output file: ' . $this->currentfile);
            }
        } else {
            $this->currentfp = null;
        }

        // If it has no size, close it right away.
        if ($filesize == 0) {
            $this->close_current_file($handler);
        }
    }