public function count_teams($activitygroup = 0) {

        $count = 0;

        $participants = $this->list_participants($activitygroup, true);

        // If a team submission grouping id is provided all good as all returned groups
        // are the submission teams, but if no team submission grouping was specified
        // $groups will contain all participants groups.
        if ($this->get_instance()->teamsubmissiongroupingid) {

            // We restrict the users to the selected group ones.
            $groups = groups_get_all_groups($this->get_course()->id,
                                            array_keys($participants),
                                            $this->get_instance()->teamsubmissiongroupingid,
                                            'DISTINCT g.id, g.name');

            $count = count($groups);

            // When a specific group is selected we don't count the default group users.
            if ($activitygroup == 0) {
                if (empty($this->get_instance()->preventsubmissionnotingroup)) {
                    // See if there are any users in the default group.
                    $defaultusers = $this->get_submission_group_members(0, true);
                    if (count($defaultusers) > 0) {
                        $count += 1;
                    }
                }
            } else if ($activitygroup != 0 && empty($groups)) {
                // Set count to 1 if $groups returns empty.
                // It means the group is not part of $this->get_instance()->teamsubmissiongroupingid.
                $count = 1;
            }
        } else {
            // It is faster to loop around participants if no grouping was specified.
            $groups = array();
            foreach ($participants as $participant) {
                if ($group = $this->get_submission_group($participant->id)) {
                    $groups[$group->id] = true;
                } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
                    $groups[0] = true;
                }
            }

            $count = count($groups);
        }

        return $count;
    }