	if ($parse_bbcodes)
	{
		// List of valid bbcodes
		$valid_bb = array('b', 'i', 's', 'u', 'p', 'size', 'quote', 'img', 't', 'thumb',
			'list', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'del',
			'red', 'white', 'green', 'blue', 'orange', 'yellow', 'purple', 'black', 'grey', 'pink', 'sky', 'sea',
			'url', 'email', 'pfs', 'user', 'group', 'topic', 'page', 'pm', 'f', 'ac', 'youtube', 'googlevideo', 'metacafe',
			'spoiler', 'left', 'right', 'colleft', 'colright',
			'table', 'tr', 'th', 'td', 'hide', 'stud', 'studurl');
		// These bbcodes don't need closing ones
		$ignore_bb = array('br', 'hr', '_', '__', 'more', 'c1', 'c2', 'c3');
		// Count all bbcodes
		if(preg_match_all('#\[(/)?(\w+)(=[^\]]*)?\]#', $text, $mt, PREG_SET_ORDER))
		{
			// Count all unclosed bbcode entries
			for($i = 0; $i < count($mt); $i++)
			{
				if(in_array($mt[$i][2], $valid_bb))
				{
					if($mt[$i][1] == '/')
					{
						$bb = $mt[$i][2];
						// Protect from "[/foo] [/bar][foo][bar]" trick
						if($bbc[$bb] > 0) $bbc[$bb]--;
						// else echo 'ERROR: invalid closing bbcode detected';
					}
					else
					$bbc[$mt[$i][2]]++;
				}
			}
			// Close all unclosed tags. Produces non XHTML-comliant output (doesn't take tag order into account) but fixes the layout
			if(count($bbc) > 0) foreach($bbc as $bb => $c)
			$text .= str_repeat("[/$bb]", $c);
		}
		// Done, ready to parse bbcodes
		$text = sed_bbcode($text);
	}