/*!
* Parses lines for function/method names.
*
* \param line line to be processed
* \param lastline last line processed
* \param functionStack stack of functions
* \param functionName function name found
* \param functionCount function count found
*
* \return 1 if function name is found
*/
int CPerlCounter::ParseFunctionName(const string &line, string &lastline,
	filemap &functionStack, string &functionName, unsigned int &functionCount)
{
	string tline, str;
	size_t i, idx, tidx, cnt;
	unsigned int fcnt;

	tline = CUtil::TrimString(line);
	idx = tline.find('{');
	if (idx != string::npos)
	{
		// check whether it is at first index, if yes then function name is at above line
		if (idx == 0)
		{
			lineElement element(++functionCount, lastline);
			functionStack.push_back(element);
			lastline.erase();
		}
		else
		{
			str = tline.substr(0, idx);
			if (str.find('(') != string::npos && str[0] != '(')
				lastline = str;
			else
				lastline += " " + str;
			lineElement element(++functionCount, CUtil::TrimString(lastline));
			functionStack.push_back(element);
			lastline.erase();
		}
	}
	else if (tline.length() > 0 && tline[tline.length() - 1] != ';' &&
		lastline.length() > 0 && lastline[lastline.length() - 1] != ';')
	{
		// append until all parenthesis are closed
		tidx = lastline.find('(');
		if (tidx != string::npos)
		{
			cnt = 1;
			while (tidx != string::npos)
			{
				tidx = lastline.find('(', tidx + 1);
				if (tidx != string::npos)
					cnt++;
			}
			tidx = lastline.find(')');
			while (tidx != string::npos)
			{
				cnt++;
				tidx = lastline.find(')', tidx + 1);
			}
			if (cnt % 2 != 0)
				lastline += " " + tline;
			else
				lastline = tline;
		}
		else
			lastline = tline;
	}
	else
		lastline = tline;

	idx = line.find('}');
	if (idx != string::npos && !functionStack.empty())
	{
		str = functionStack.back().line;
		fcnt = functionStack.back().lineNumber;
		functionStack.pop_back();
		idx = CUtil::FindKeyword(str, "sub");
		if (idx != string::npos && idx + 4 < str.length())
		{
			functionName = CUtil::ClearRedundantSpaces(str.substr(idx + 4));
			functionCount = fcnt;
			lastline.erase();
			return 1;
		}
		lastline.erase();
	}

	// check stack for any "sub"
	idx = string::npos;
	if (!functionStack.empty())
	{
		for (i = 0; i < functionStack.size(); i++)
		{
			idx = CUtil::FindKeyword(functionStack[i].line, "sub");
			if (idx != string::npos)
				break;
		}
	}
	if (idx == string::npos)
	{
		// dealing with some code out of any subroutines, it a "main" code
		return 2;
	}
	return 0;
}