/**
 * utils.c: Class delivers some static helper functions
 * 
 * Copyright: See COPYING file that comes with this distribution
 *
 * Author: Matthias Feistel <hitman_47@users.sourceforge.net>, (C) 2007
 */

#include "utils.h"
#include "md5.h"

// source: http://www.cplusplus.com/reference/stl/list/sort.html 
// comparison, not case sensitive.
bool cUtils::compare_nocase( const std::string x, const std::string y )
{
	// the following code lines have been copied from: <http://souptonuts.sourceforge.net/code/list2.cc.html> 

	std::string::const_iterator p = x.begin( );
	std::string::const_iterator q = y.begin( );

	while( p!=x.end( ) && q!=y.end( ) && toupper( *p ) == toupper( *q ) )
	{
		++p;
		++q;
	}
	if( p==x.end( ) )
		return q !=y.end( );
	if( q==y.end( ) )
		return false;
	return toupper( *p ) < toupper( *q );
}

std::string cUtils::rfc1738_encode( const std::string& src )
{
	static char hex[] = "0123456789ABCDEF";
	std::string dst;

	for( size_t i = 0; i < src.size( ); i++ )
	{
		if( isalnum( src[i] ) )
		{
			dst += src[i];
		}
		else if( src[i] == ' ' )
		{
			dst += '+';
		}
		else
		{
			unsigned char c = static_cast<unsigned char>(src[i]);
			dst += '%';
			dst += hex[c / 16];
			dst += hex[c % 16];
		}
	}

	return dst;
} // rfc1738_encode

// copied from vdr-epgsearch written by C. Wieninger:
std::string cUtils::MD5(const std::string& input)
{
   char* szInput = strdup(input.c_str());
   if (!szInput) return "";
   char* szRes = MD5String(szInput);
   std::string res = szRes;
   free(szRes);
   return res;
}
