Example #1
0
/**
Convert a tag to a C string
*/
static const char* 
ConvertAnyTag(FITAG *tag) {
	char format[MAX_TEXT_EXTENT];
	static std::string buffer;
	DWORD i;

	if(!tag)
		return NULL;

	buffer.erase();
	
	// convert the tag value to a string buffer

	FREE_IMAGE_MDTYPE tag_type = FreeImage_GetTagType(tag);
	DWORD tag_count = FreeImage_GetTagCount(tag);

	switch(tag_type) {
		case FIDT_BYTE:		// N x 8-bit unsigned integer 
		{
			BYTE *pvalue = (BYTE*)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld",	(LONG) pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %ld",	(LONG) pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_SHORT:	// N x 16-bit unsigned integer 
		{
			unsigned short *pvalue = (unsigned short *)FreeImage_GetTagValue(tag);

			sprintf(format, "%hu", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %hu",	pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_LONG:		// N x 32-bit unsigned integer 
		{
			DWORD *pvalue = (DWORD *)FreeImage_GetTagValue(tag);

			sprintf(format, "%lu", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %lu",	pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_RATIONAL: // N x 64-bit unsigned fraction 
		{
			DWORD *pvalue = (DWORD*)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld/%ld", pvalue[0], pvalue[1]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %ld/%ld", pvalue[2*i], pvalue[2*i+1]);
				buffer += format;
			}
			break;
		}
		case FIDT_SBYTE:	// N x 8-bit signed integer 
		{
			char *pvalue = (char*)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld",	(LONG) pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %ld",	(LONG) pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_SSHORT:	// N x 16-bit signed integer 
		{
			short *pvalue = (short *)FreeImage_GetTagValue(tag);

			sprintf(format, "%hd", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %hd",	pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_SLONG:	// N x 32-bit signed integer 
		{
			LONG *pvalue = (LONG *)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %ld",	pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_SRATIONAL:// N x 64-bit signed fraction 
		{
			LONG *pvalue = (LONG*)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld/%ld", pvalue[0], pvalue[1]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %ld/%ld", pvalue[2*i], pvalue[2*i+1]);
				buffer += format;
			}
			break;
		}
		case FIDT_FLOAT:	// N x 32-bit IEEE floating point 
		{
			float *pvalue = (float *)FreeImage_GetTagValue(tag);

			sprintf(format, "%f", (double) pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, "%f", (double) pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_DOUBLE:	// N x 64-bit IEEE floating point 
		{
			double *pvalue = (double *)FreeImage_GetTagValue(tag);

			sprintf(format, "%f", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, "%f", pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_IFD:		// N x 32-bit unsigned integer (offset) 
		{
			DWORD *pvalue = (DWORD *)FreeImage_GetTagValue(tag);

			sprintf(format, "%X", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " %X",	pvalue[i]);
				buffer += format;
			}
			break;
		}
		case FIDT_PALETTE:	// N x 32-bit RGBQUAD 
		{
			RGBQUAD *pvalue = (RGBQUAD *)FreeImage_GetTagValue(tag);

			sprintf(format, "(%d,%d,%d,%d)", pvalue[0].rgbRed, pvalue[0].rgbGreen, pvalue[0].rgbBlue, pvalue[0].rgbReserved);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, " (%d,%d,%d,%d)", pvalue[i].rgbRed, pvalue[i].rgbGreen, pvalue[i].rgbBlue, pvalue[i].rgbReserved);
				buffer += format;
			}
			break;
		}
		
		case FIDT_LONG8:	// N x 64-bit unsigned integer 
		{
			FIUINT64 *pvalue = (FIUINT64 *)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, "%ld", pvalue[i]);
				buffer += format;
			}
			break;
		}

		case FIDT_IFD8:		// N x 64-bit unsigned integer (offset)
		{
			FIUINT64 *pvalue = (FIUINT64 *)FreeImage_GetTagValue(tag);

			sprintf(format, "%X", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, "%X", pvalue[i]);
				buffer += format;
			}
			break;
		}

		case FIDT_SLONG8:	// N x 64-bit signed integer
		{
			FIINT64 *pvalue = (FIINT64 *)FreeImage_GetTagValue(tag);

			sprintf(format, "%ld", pvalue[0]);
			buffer += format;
			for(i = 1; i < tag_count; i++) {
				sprintf(format, "%ld", pvalue[i]);
				buffer += format;
			}
			break;
		}

		case FIDT_ASCII:	// 8-bit bytes w/ last byte null 
		case FIDT_UNDEFINED:// 8-bit untyped data 
		default:
		{
			int max_size = MIN((int)FreeImage_GetTagLength(tag), (int)MAX_TEXT_EXTENT);
			if(max_size == MAX_TEXT_EXTENT)
				max_size--;
			memcpy(format, (char*)FreeImage_GetTagValue(tag), max_size);
			format[max_size] = '\0';
			buffer += format;
			break;
		}
	}

	return buffer.c_str();
}
Example #2
0
// Quick little trim functions
void trimWhiteSpace(std::string& str)
{
	while(size_t pos = str.find(" ") != std::string::npos)
		str.erase(pos,1);
}
Example #3
0
/*
 * Python Interface pass script and reference to user record.
 */
void pybbs_run(std::string script, UserRec *usr)
{
    SESSION _io;
    pyUser = usr;
    // Setup scripts path.
    std::string path;
    path = SCRIPTS;
    path += script;

    // Clear for initial run.
    KeyCombination.erase();

    sigset_t signal_set; // We don't need oldset in this program. You can add it,
    //but it's best to use different sigsets for the second
    //and third argument of sigprocmask.
    sigemptyset(&signal_set);

    // Block Signals in Python, casue then the BBS doesn't get them.
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGILL);
    sigaddset(&signal_set, SIGABRT);
    sigaddset(&signal_set, SIGCHLD);
    sigaddset(&signal_set, SIGQUIT);
    sigaddset(&signal_set, SIGKILL);
    sigaddset(&signal_set, SIGWINCH);
    sigprocmask(SIG_BLOCK, &signal_set, NULL);
    try
    {
        //function should be called before Py_Initialize() to inform
        //the interpreter about paths to Python run-time libraries.
        //Next, the Python interpreter is initialized with Py_Initialize(),
        //followed by the execution of a hard-coded Python script that
        //prints the date and time.
        //Py_SetProgramName(BBSPATH);
        /* Simple Test Code
        PyRun_SimpleString("result = 5 ** 2");

        object module(handle<>(borrowed(PyImport_AddModule("__main__"))));
        object dictionary = module.attr("__dict__");
        object result = dictionary["result"];

        int result_value = extract<int>(result);
        std::cout << result_value << std::endl;

        dictionary["result"] = 20;
        PyRun_SimpleString("print result");

        initbbs_io(); // initialize Pointless

        PyRun_SimpleString("import bbs_io");
        PyRun_SimpleString("print bbs_io.add_five(4)");
        */
        // Testing
        //path += "MyModule.py";
        if(boost::filesystem::exists(path.c_str()))       // does actually exist?
        {
            //if (boost::filesystem::is_regular_file(path.c_str()))        // is p a regular file?
            //    std::cout << path.c_str() << " size is " << boost::filesystem::file_size(path.c_str()) << endl;
        }
        else
        {
            std::cout << "\n *** ERROR: \n" << path.c_str() << " NOT FOUND!" << endl;
            return;
        }
        _io.errlog2((char *) "Starting Boost_Python %s",path.c_str());

        Py_Initialize();
        initbbs_io(); // initialize Pointless
        object module = import("__main__");
        object name_space = module.attr("__dict__");

        // Setup global variables for script.
        //Only works for wavlues set before scripts, is not dynamic!
        //name_space["KeyCombination"]=KeyCombination;
        object result = exec_file(path.c_str(), name_space, name_space);
        _io.errlog2((char *) "Exiting Boost_Python");
    }
    catch(error_already_set const &)
    {
        PyErr_Print();
        /*
        boost::python::object sys(
            boost::python::handle<>(PyImport_ImportModule("sys"))
        );
        boost::python::object err = sys.attr("stderr");
        std::string err_text = boost::python::extract<std::string>(err.attr("getvalue")());
        //MessageBox(0, err_text.c_str(), "Python Error", MB_OK);
        _io.errlog2((char *)err_text.c_str());*/
        _io.errlog2((char *) "Python Exception");
        // Only Exit if a user, not if sysop debuging!
        if(isSysop == FALSE)
            exit(1);
    }
    _io.errlog2((char *) "Finished Boost_Python");

    // Unblock Signals
    sigprocmask(SIG_UNBLOCK, &signal_set, NULL);
    //do not call this, causes issue memory leaks in BOOST_PYTHON
    // can't run more anymore scripts if this is called!
    // Py_Finalize();
    return;
}
Example #4
0
 std::time_t parse_rfc_datetime(std::string value)
 {
     boost::replace_all(value, " -", " #");
     std::replace(value.begin(), value.end(), '-', ' ');
     boost::replace_all(value, " #", " -");
     std::tm t;
     memset(&t, 0, sizeof(std::tm));
     int x, zone = 0;
     std::string s;
     std::string::size_type pos;
     while (!value.empty())
     {
         pos = value.find(' ');
         if (pos != std::string::npos)
         {
             s = value.substr(0, pos);
             value.erase(0, pos + 1);
         }
         else
         {
             s = value;
             value.clear();
         }
         std::transform(s.begin(), s.end(), s.begin(), toupper);
         if (parse_timezone(s, zone)) continue;
         if ((x = atoi(s.c_str())) > 0)
         {
             if ((x < 32) && (!t.tm_mday))
             {
                 t.tm_mday = x;
                 continue;
             }
             else
             {
                 if ((!t.tm_year) && (t.tm_mon || (x > 12)))
                 {
                     if (x < 32)
                     {
                         t.tm_year = x + 100;
                     }
                     else if (x < 1000)
                     {
                         t.tm_year = x;
                     }
                     else
                     {
                         t.tm_year = x - 1900;
                     }
                     continue;
                 }
             }
         }
         std::string::size_type first, last;
         if ((first = s.find_first_of(':')) < (last = s.find_last_of(':')))
         {
             t.tm_hour = atoi(s.substr(0, first).c_str());
             t.tm_min = atoi(s.substr(first + 1, last).c_str());
             t.tm_sec = atoi(s.substr(last + 1).c_str());
             continue;
         }
         if (s == "DST")
         {
             t.tm_isdst = true;
             continue;
         }
         if (parse_month(s, x) && (!t.tm_mon))
         {
             t.tm_mon = x;
         }
     }
     if (!t.tm_year)
     {
         t.tm_year = 80;
     }
     if (t.tm_mon > 11)
     {
         t.tm_mon = 11;
     }
     if (!t.tm_mday)
     {
         t.tm_mday = 1;
     }
     t.tm_sec -= (zone + ctime::timezone());
     return mktime(&t);
 }
 /*!
  * @if jp
  * @brief 文字列の先頭の空白文字を削除する
  * @else
  * @brief Erase the head blank characters of string
  * @endif
  */
 void eraseHeadBlank(std::string& str)
 {
   if (str.empty()) return;
   while (str[0] == ' ' || str[0] == '\t') str.erase(0, 1);
 }
Example #6
0
void savegame::set_filename(std::string filename)
{
	filename.erase(std::remove_if(filename.begin(), filename.end(),
	            is_illegal_file_char), filename.end());
	filename_ = filename;
}
Example #7
0
inline std::string rtrim(std::string& s, const std::string& drop = TRIM_SPACE) {
    return s.erase(s.find_last_not_of(drop) + 1);
}
Example #8
0
void prep_query(std::string& str) {
  while (!isdigit(str.front()) && str.front() != '-') str.erase(0, 1);
  while (!isdigit(str.back())) str.erase(str.length() - 1);
}
Example #9
0
Route::Route(std::string &line, HighwaySystem *sys, ErrorList &el, std::unordered_map<std::string, Region*> &region_hash)
{	/* initialize object from a .csv file line,
	but do not yet read in waypoint file */
	con_route = 0;
	mileage = 0;
	rootOrder = -1;  // order within connected route
	if (line.back() == 0x0D) line.erase(line.end()-1);	// trim DOS newlines

	// system
	size_t left = line.find(';');
	if (left == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 1");
		return;
	}
	system = sys;
	if (system->systemname != line.substr(0,left))
	    {	el.add_error("System mismatch parsing " + system->systemname + ".csv line [" + line + "], expected " + system->systemname);
		return;
	    }

	// region
	size_t right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 2");
		return;
	}
	try { region = region_hash.at(line.substr(left+1, right-left-1));
	    }
	catch (const std::out_of_range& oor)
	    {	el.add_error("Unrecognized region in " + system->systemname + ".csv line: [" + line + "], " + line.substr(left+1, right-left-1));
		region = 0;
		return;
	    }

	// route
	left = right;
	right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 3");
		return;
	}
	route = line.substr(left+1, right-left-1);

	// banner
	left = right;
	right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 4");
		return;
	}
	banner = line.substr(left+1, right-left-1);
	if (banner.size() > 6)
	    {	el.add_error("Banner >6 characters in " + system->systemname + ".csv line: [" + line + "], " + banner);
		return;
	    }

	// abbrev
	left = right;
	right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 5");
		return;
	}
	abbrev = line.substr(left+1, right-left-1);
	if (abbrev.size() > 3)
	    {	el.add_error("Abbrev >3 characters in " + system->systemname + ".csv line: [" + line + "], " + abbrev);
		return;
	    }

	// city
	left = right;
	right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 6");
		return;
	}
	city = line.substr(left+1, right-left-1);

	// root
	left = right;
	right = line.find(';', left+1);
	if (right == std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found 7");
		return;
	}
	root = line.substr(left+1, right-left-1);

	// alt_route_names
	left = right;
	right = line.find(';', left+1);
	if (right != std::string::npos)
	{	el.add_error("Could not parse " + system->systemname + ".csv line: [" + line + "], expected 8 fields, found more");
		return;
	}
	char *arnstr = new char[line.size()-left];
	strcpy(arnstr, line.substr(left+1).data());
	for (char *token = strtok(arnstr, ","); token; token = strtok(0, ","))
		alt_route_names.push_back(token);
	delete[] arnstr;
	//yDEBUG*/ std::cout << "returning from Route ctor" << endl;
}
Example #10
0
void removeNewLine ( std::string &str )
{
    str.erase(str.length());
}
Example #11
0
std::string Text::parseAndReplaceAccents(std::string text){

	std::map<std::string, int> replacements;

	replacements["À"] = 192;
	replacements["Á"] = 193;
	replacements["Â"] = 194;
	replacements["Ä"] = 196;

	replacements["È"] = 200;
	replacements["É"] = 201;
	replacements["Ê"] = 202;
	replacements["Ë"] = 203;

	replacements["Ì"] = 204;
	replacements["Í"] = 205;
	replacements["Î"] = 206;
	replacements["Ï"] = 207;

	replacements["Ò"] = 210;
	replacements["Ó"] = 211;
	replacements["Ô"] = 212;
	replacements["Ö"] = 214;

	replacements["Ù"] = 217;
	replacements["Ú"] = 218;
	replacements["Û"] = 219;
	replacements["Ü"] = 220;

	replacements["à"] = 224;
	replacements["á"] = 225;
	replacements["â"] = 226;
	replacements["ä"] = 228;

	replacements["è"] = 232;
	replacements["é"] = 233;
	replacements["ê"] = 234;
	replacements["ë"] = 235;

	replacements["ì"] = 236;
	replacements["í"] = 237;
	replacements["î"] = 238;
	replacements["ï"] = 239;

	replacements["ò"] = 242;
	replacements["ó"] = 243;
	replacements["ô"] = 244;
	replacements["ö"] = 246;

	replacements["ù"] = 249;
	replacements["ú"] = 250;
	replacements["û"] = 251;
	replacements["ü"] = 252;

	replacements["Ç"] = 199;
	replacements["ç"] = 231;
	replacements["Ñ"] = 209;
	replacements["ñ"] = 241;
	replacements["·"] = 183;
	replacements["'"] = 180;
	replacements["¡"] = 161;
	replacements["¿"] = 191;

	replacements["\u201C"] = '"';
	replacements["\u201D"] = '"';

	for(map<std::string, int>::iterator it = replacements.begin(); it != replacements.end(); ++it){
		size_t pos = text.find(it->first);
		while (pos != std::string::npos){
			char sub[2] = {(char) it->second, '\0'};
			text.replace(pos, it->first.length(), std::string(sub));
			pos = text.find(it->first, pos + 1);
		}
	}

	// Replace &#18;&#10; substrings with \n
	const std::string search = "&#18;&#10;";
	const std::string replace = "\n";

	for(size_t pos = 0; ; pos += replace.length()) {
		// Locate the substring to replace
		pos = text.find( search, pos );

		if(pos == string::npos){
			break;
		}

		// Replace by erasing and inserting
		text.erase(pos, search.length());
		text.insert(pos, replace);
	}

	return text;
}
void Config_parser::trim_space(std::string &dest_str)
{
    dest_str.erase(0, dest_str.find_first_not_of(" \t\f\v\n\r"));  
     
    dest_str.erase(dest_str.find_last_not_of(" \t\f\v\n\r")+1);  
}
bool Config_parser::is_space_line(std::string line)
{
	line.erase(0, line.find_first_not_of(" \t\f\v\n\r"));
	return line.length() == 0?true:false;
}
Example #14
0
/**
Convert a Exif GPS tag to a C string
*/
static const char* 
ConvertExifGPSTag(FITAG *tag) {
	char format[MAX_TEXT_EXTENT];
	static std::string buffer;

	if(!tag)
		return NULL;

	buffer.erase();

	// convert the tag value to a string buffer

	switch(FreeImage_GetTagID(tag)) {
		case TAG_GPS_LATITUDE:
		case TAG_GPS_LONGITUDE:
		case TAG_GPS_TIME_STAMP:
		{
			DWORD *pvalue = (DWORD*)FreeImage_GetTagValue(tag);
			if(FreeImage_GetTagLength(tag) == 24) {
				// dd:mm:ss or hh:mm:ss
				int dd = 0, mm = 0;
				double ss = 0;

				// convert to seconds
				if(pvalue[1])
					ss += ((double)pvalue[0] / (double)pvalue[1]) * 3600;
				if(pvalue[3])
					ss += ((double)pvalue[2] / (double)pvalue[3]) * 60;
				if(pvalue[5])
					ss += ((double)pvalue[4] / (double)pvalue[5]);
				
				// convert to dd:mm:ss.ss
				dd = (int)(ss / 3600);
				mm = (int)(ss / 60) - dd * 60;
				ss = ss - dd * 3600 - mm * 60;

				sprintf(format, "%d:%d:%.2f", dd, mm, ss);
				buffer += format;
				return buffer.c_str();
			}
		}
		break;

		case TAG_GPS_VERSION_ID:
		case TAG_GPS_LATITUDE_REF:
		case TAG_GPS_LONGITUDE_REF:
		case TAG_GPS_ALTITUDE_REF:
		case TAG_GPS_ALTITUDE:
		case TAG_GPS_SATELLITES:
		case TAG_GPS_STATUS:
		case TAG_GPS_MEASURE_MODE:
		case TAG_GPS_DOP:
		case TAG_GPS_SPEED_REF:
		case TAG_GPS_SPEED:
		case TAG_GPS_TRACK_REF:
		case TAG_GPS_TRACK:
		case TAG_GPS_IMG_DIRECTION_REF:
		case TAG_GPS_IMG_DIRECTION:
		case TAG_GPS_MAP_DATUM:
		case TAG_GPS_DEST_LATITUDE_REF:
		case TAG_GPS_DEST_LATITUDE:
		case TAG_GPS_DEST_LONGITUDE_REF:
		case TAG_GPS_DEST_LONGITUDE:
		case TAG_GPS_DEST_BEARING_REF:
		case TAG_GPS_DEST_BEARING:
		case TAG_GPS_DEST_DISTANCE_REF:
		case TAG_GPS_DEST_DISTANCE:
		case TAG_GPS_PROCESSING_METHOD:
		case TAG_GPS_AREA_INFORMATION:
		case TAG_GPS_DATE_STAMP:
		case TAG_GPS_DIFFERENTIAL:
			break;
	}

	return ConvertAnyTag(tag);
}
void TransformToPostfixForm(std::string& regex, std::string& postfixRegex)
{
	std::stack<char> regexElementsStack;
	std::string auxElem;
	for (int i = 0; i < regex.length(); i++)
	{
		if (regex[i] == '(')
		{
			regexElementsStack.push(regex[i]);
		}
		else if (regex[i] == ')')
		{
			while (1)
			{
				if (!regexElementsStack.empty())
				{
					auxElem = regexElementsStack.top();
					regexElementsStack.pop();
					if (auxElem.compare("(") == 0)
						break;
					postfixRegex.append(auxElem);
				}
				else
					break;
			}
		}
		else if (regex[i] == '|')
		{
			if(!regexElementsStack.empty())
				auxElem = regexElementsStack.top();
			while ((auxElem.compare("*") == 0 || auxElem.compare("|") == 0 || auxElem.compare(".") == 0) && !regexElementsStack.empty())
			{
				postfixRegex.append(auxElem);
				regexElementsStack.pop();
				auxElem = regexElementsStack.top();
			}
			regexElementsStack.push(regex[i]);
		}
		else if (regex[i] == '.')
		{
			if (!regexElementsStack.empty())
				auxElem = regexElementsStack.top();
			while ((auxElem.compare("*") == 0 || auxElem.compare(".") == 0) && !regexElementsStack.empty())
			{
				postfixRegex.append(auxElem);
				regexElementsStack.pop();
				if(!regexElementsStack.empty())
					auxElem = regexElementsStack.top();
			}
			regexElementsStack.push(regex[i]);
		}
		else if (regex[i] == '*' && !regexElementsStack.empty())
		{
			regexElementsStack.push(regex[i]);
		}
		else
		{
			auxElem = std::string(regex.begin() + i, regex.begin() + i + 1);
			postfixRegex.append(auxElem);
		}
	}

	while (!regexElementsStack.empty())
	{
		auxElem = regexElementsStack.top();
		if (auxElem.compare("(") != 0)
		{
			postfixRegex.append(auxElem);
		}
		regexElementsStack.pop();
	}

	postfixRegex.append("#");
	postfixRegex.append(".");

	std::string::iterator end_pos = std::remove(postfixRegex.begin(), postfixRegex.end(), ' ');
	postfixRegex.erase(end_pos, postfixRegex.end());
}
Example #16
0
std::string trim_left_inplace(std::string s, const std::string& delimiters) {
	return s.erase(0, s.find_first_not_of(delimiters));
}
Example #17
0
void CNetworkInterfaceLinux::GetSettings(NetworkAssignment& assignment, std::string& ipAddress, std::string& networkMask, std::string& defaultGateway, std::string& essId, std::string& key, EncMode& encryptionMode)
{
   ipAddress = "0.0.0.0";
   networkMask = "0.0.0.0";
   defaultGateway = "0.0.0.0";
   essId = "";
   key = "";
   encryptionMode = ENC_NONE;
   assignment = NETWORK_DISABLED;

#if defined(TARGET_LINUX)
   FILE* fp = fopen("/etc/network/interfaces", "r");
   if (!fp)
   {
      // TODO
      return;
   }

   char* line = NULL;
   size_t linel = 0;
   std::string s;
   bool foundInterface = false;

   while (getdelim(&line, &linel, '\n', fp) > 0)
   {
      std::vector<std::string> tokens;

      s = line;
      StringUtils::TrimLeft(s, " \t");
      StringUtils::TrimRight(s," \n");

      // skip comments
      if (s.empty() || s[0] == '#')
         continue;

      // look for "iface <interface name> inet"
      StringUtils::Tokenize(s, tokens, " ");
      if (!foundInterface &&
          tokens.size() >=3 &&
          StringUtils::EqualsNoCase(tokens[0], "iface") &&
          StringUtils::EqualsNoCase(tokens[1], GetName()) &&
          StringUtils::EqualsNoCase(tokens[2], "inet"))
      {
         if (StringUtils::EqualsNoCase(tokens[3], "dhcp"))
         {
            assignment = NETWORK_DHCP;
            foundInterface = true;
         }
         if (StringUtils::EqualsNoCase(tokens[3], "static"))
         {
            assignment = NETWORK_STATIC;
            foundInterface = true;
         }
      }

      if (foundInterface && tokens.size() == 2)
      {
         if (StringUtils::EqualsNoCase(tokens[0], "address")) ipAddress = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "netmask")) networkMask = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "gateway")) defaultGateway = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "wireless-essid")) essId = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "wireless-key"))
         {
            key = tokens[1];
            if (key.length() > 2 && key[0] == 's' && key[1] == ':')
               key.erase(0, 2);
            encryptionMode = ENC_WEP;
         }
         else if (StringUtils::EqualsNoCase(tokens[0], "wpa-ssid")) essId = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "wpa-proto") && StringUtils::EqualsNoCase(tokens[1], "WPA")) encryptionMode = ENC_WPA;
         else if (StringUtils::EqualsNoCase(tokens[0], "wpa-proto") && StringUtils::EqualsNoCase(tokens[1], "WPA2")) encryptionMode = ENC_WPA2;
         else if (StringUtils::EqualsNoCase(tokens[0], "wpa-psk")) key = tokens[1];
         else if (StringUtils::EqualsNoCase(tokens[0], "auto") || StringUtils::EqualsNoCase(tokens[0], "iface") || StringUtils::EqualsNoCase(tokens[0], "mapping")) break;
      }
   }
   free(line);

   // Fallback in case wpa-proto is not set
   if (key != "" && encryptionMode == ENC_NONE)
      encryptionMode = ENC_WPA;

   fclose(fp);
#endif
}
Example #18
0
std::string trim_right_inplace(std::string s, const std::string& delimiters) {
	return s.erase(s.find_last_not_of(delimiters) + 1);
}
Example #19
0
std::function<bool( const item & )>
item_filter_from_string( std::string filter )
{
    if( filter.empty() ) {
        // Variable without name prevents unused parameter warning
        return []( const item & ) {
            return true;
        };
    }

    // remove curly braces (they only get in the way)
    if( filter.find( '{' ) != std::string::npos ) {
        filter.erase( std::remove( filter.begin(), filter.end(), '{' ) );
    }
    if( filter.find( '}' ) != std::string::npos ) {
        filter.erase( std::remove( filter.begin(), filter.end(), '}' ) );
    }
    if( filter.find( "," ) != std::string::npos ) {
        // functions which only one of which must return true
        std::vector<std::function<bool( const item & )> > functions;
        // Functions that must all return true
        std::vector<std::function<bool( const item & )> > inv_functions;
        size_t comma = filter.find( "," );
        while( !filter.empty() ) {
            const auto &current_filter = trim( filter.substr( 0, comma ) );
            if( !current_filter.empty() ) {
                auto current_func = item_filter_from_string( current_filter );
                if( current_filter[0] == '-' ) {
                    inv_functions.push_back( current_func );
                } else {
                    functions.push_back( current_func );
                }
            }
            if( comma != std::string::npos ) {
                filter = trim( filter.substr( comma + 1 ) );
                comma = filter.find( "," );
            } else {
                break;
            }
        }

        return [functions, inv_functions]( const item & it ) {
            auto apply = [&]( const std::function<bool( const item & )> &func ) {
                return func( it );
            };
            bool p_result = std::any_of( functions.begin(), functions.end(),
                                         apply );
            bool n_result = std::all_of(
                                inv_functions.begin(),
                                inv_functions.end(),
                                apply );
            if( !functions.empty() && inv_functions.empty() ) {
                return p_result;
            }
            if( functions.empty() && !inv_functions.empty() ) {
                return n_result;
            }
            return p_result && n_result;
        };
    }
    bool exclude = filter[0] == '-';
    if( exclude ) {
        return [filter]( const item & i ) {
            return !item_filter_from_string( filter.substr( 1 ) )( i );
        };
    }
    size_t colon;
    char flag = '\0';
    if( ( colon = filter.find( ":" ) ) != std::string::npos ) {
        if( colon >= 1 ) {
            flag = filter[colon - 1];
            filter = filter.substr( colon + 1 );
        }
    }
    switch( flag ) {
        case 'c'://category
            return [filter]( const item & i ) {
                return lcmatch( i.get_category().name, filter );
            };
            break;
        case 'm'://material
            return [filter]( const item & i ) {
                return std::any_of( i.made_of().begin(), i.made_of().end(),
                [&filter]( const material_id & mat ) {
                    return lcmatch( mat->name(), filter );
                } );
            };
            break;
        case 'b'://both
            return [filter]( const item & i ) {
                auto pair = get_both( filter );
                return item_filter_from_string( pair.first )( i )
                       && item_filter_from_string( pair.second )( i );
            };
            break;
        default://by name
            return [filter]( const item & a ) {
                return lcmatch( a.tname(), filter );
            };
            break;
    }
}
Example #20
0
void utility::string_utility::LeftTrim(std::string& s)
{
	s.erase(s.begin(), find_if(s.begin(), s.end(), not1(std::ptr_fun<int, int>(std::isspace))));
}
Example #21
0
inline std::string ltrim(std::string& s, const std::string& drop = TRIM_SPACE) {
    return s.erase(0, s.find_first_not_of(drop));
}
Example #22
0
void utility::string_utility::RightTrim(std::string& s)
{
	s.erase(find_if(s.rbegin(), s.rend(), not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
}
Example #23
0
 void cookies::set_cookie(const std::string & host, std::string content)
 {
     std::string::size_type pos = content.find(';');
     if (pos != std::string::npos)
     {
         cookie c;
         std::string s = content.substr(0, pos);
         content.erase(0, pos + 2);
         pos = s.find('=');
         if (pos != std::string::npos)
         {
             c.name = s.substr(0, pos);
             c.value = s.substr(pos + 1);
             std::string key, value;
             while (true)
             {
                 bool eof = false;
                 pos = content.find(';');
                 if (pos == std::string::npos)
                 {
                     eof = true;
                     s = content;
                 }
                 else
                 {
                     s = content.substr(0, pos);
                     content.erase(0, pos + 2);
                 }
                 pos = s.find('=');
                 if (pos != std::string::npos)
                 {
                     key = s.substr(0, pos);
                     value = s.substr(pos + 1);
                 }
                 else
                 {
                     if (_strcmpi(s.c_str(), "secure") == 0)
                     {
                         c.secure = true;
                     }
                     continue;
                 }
                 if (_strcmpi(key.c_str(), "path") == 0)
                 {
                     if (!value.empty())
                     {
                         if (*value.begin() == '"')
                         {
                             value.erase(0, 1);
                         }
                         if (*value.rbegin() == '"')
                         {
                             value.erase(value.size() - 1);
                         }
                         c.path = value.empty() ? std::string("/") : value;
                     }
                 }
                 else if (_strcmpi(key.c_str(), "domain") == 0)
                 {
                     if (!value.empty())
                     {
                         std::transform(value.begin(), value.end(), value.begin(), tolower);
                         c.domain = value;
                     }
                 }
                 else if (_strcmpi(key.c_str(), "expires") == 0)
                 {
                     if (!value.empty())
                     {
                         c.expiry = parse_rfc_datetime(value);
                     }
                 }
                 if (eof) break;
             }
             if (c.path.empty())
             {
                 c.path = "/";
             }
             if (c.domain.empty())
             {
                 c.domain = host;
             }
             boost::unique_lock<boost::shared_mutex> lock(mutex);
             container[c.domain][c.name] = c;
         }
     }
 }
Example #24
0
void trimRight(std::string &str, std::string delim) {
	size_t pos = str.find_last_not_of(delim);
	if(pos != std::string::npos) {
		str.erase(pos + 1, str.length());
	}
}
static bool GetSceneCollectionName(QWidget *parent, std::string &name,
		std::string &file, const char *oldName = nullptr)
{
	bool rename = oldName != nullptr;
	const char *title;
	const char *text;
	char path[512];
	size_t len;
	int ret;

	if (rename) {
		title = Str("Basic.Main.RenameSceneCollection.Title");
		text  = Str("Basic.Main.AddSceneCollection.Text");
	} else {
		title = Str("Basic.Main.AddSceneCollection.Title");
		text  = Str("Basic.Main.AddSceneCollection.Text");
	}

	for (;;) {
		bool success = NameDialog::AskForName(parent, title, text,
				name, QT_UTF8(oldName));
		if (!success) {
			return false;
		}
		if (name.empty()) {
			QMessageBox::information(parent,
					QTStr("NoNameEntered.Title"),
					QTStr("NoNameEntered.Text"));
			continue;
		}
		if (SceneCollectionExists(name.c_str())) {
			QMessageBox::information(parent,
					QTStr("NameExists.Title"),
					QTStr("NameExists.Text"));
			continue;
		}
		break;
	}

	if (!GetFileSafeName(name.c_str(), file)) {
		blog(LOG_WARNING, "Failed to create safe file name for '%s'",
				name.c_str());
		return false;
	}

	ret = GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes/");
	if (ret <= 0) {
		blog(LOG_WARNING, "Failed to get scene collection config path");
		return false;
	}

	len = file.size();
	file.insert(0, path);

	if (!GetClosestUnusedFileName(file, "json")) {
		blog(LOG_WARNING, "Failed to get closest file name for %s",
				file.c_str());
		return false;
	}

	file.erase(file.size() - 5, 5);
	file.erase(0, file.size() - len);
	return true;
}
Example #26
0
void trimLeft(std::string &str, std::string delim) {
	size_t pos = str.find_first_not_of(delim);
	if(pos != std::string::npos) {
		str.erase(0, pos);
	}
}
// read experiment in either from file or from default data folder
void datans::readExperiment(std::string n, std::map<std::string, Experiment> &u, char readFlag)
{
	std::ifstream dataFile;
	std::string tempLine, tempLine2, buf;	 // one for the total line, one for in between tabs
	std::vector<std::string> tempHeadings, tempDataHeadings, tempMeasurement;
	std::vector<shared_ptr<Measurement>> rowMeasurement;
	std::string filePath;

	// reading from data folder
	if (readFlag == 'r')
	{
		dataFile.open(".//data//" + n);
		n.erase(n.end()-4, n.end());
	}

	// filepath parsed from openFileDialogue
	else if (readFlag == 'f')
	{
		dataFile.open(n);
		// reassign n to be just the name
		filePath = n;
		n = fileNameFromPath(n);
	}

	if (dataFile.is_open())
	{
		// read the first line which will be headings
		std::getline(dataFile, tempLine);
		std::stringstream ss(tempLine);
		while (ss >> buf)
		{
			tempHeadings.push_back(buf);
		}

		// create temporary object
		Experiment tempExp(n, tempHeadings);
		tempDataHeadings.resize(tempHeadings.size());
		static int counter{ 0 };

		// position should now be on the second line
		while (std::getline(dataFile, tempLine))
		{
			int colCount{ 0 };
			try {
				// we read the whole line, then each measurement is tab delineated, so split into n strings (each string is a measurement)
				// then create each measurement and push that back into a row. row is then pushed back into the measurement container
				std::stringstream ss(tempLine);
				while (std::getline(ss, tempLine2, '\t'))
				{
					std::stringstream ss2(tempLine2);
					while (ss2 >> buf)
					{
						tempMeasurement.push_back(buf);
					}
					// can only be size 4 or 2
					if (tempMeasurement.size() != 4 || tempMeasurement.size() != 2)
					{
						throw("Measurement should be in one of the specified formats");
					}

					// only execute once to set dataheadings
					if (counter == 0)
					{
						if (tempMeasurement.size() == 4)
						{
							tempDataHeadings[colCount] = "Val    Err    SEerr  Date        ";
						}
						else if (tempMeasurement.size() == 2)
						{
							tempDataHeadings[colCount] = "Val                 Date        ";
						}
						else
						{
							perror("Data should be in format specified");
						}
					}
					else
						// compare other measurements to the first to ensure same type down columns
						// by the size of measurement compared to the length of dataheadings
					{
						if ((tempDataHeadings[colCount].length() < 13 && tempMeasurement.size() == 4) || (tempDataHeadings[colCount].length() > 13 && tempMeasurement.size() == 2))
						{
							throw("Measurements in a column should be of the same type");
						}
					}
					colCount++;
					// try catch to find invalid input; no recovery (user must fix their file)
					try {
						rowMeasurement.push_back(std::move(addMeasurement(tempMeasurement)));
					}
					catch (const char* msg) {
						cerr << msg;
						cerr << "Check format of file " << n << " and try again." << endl;
						std::cin.clear();
						return;
					}
					tempMeasurement.clear();
				}
				tempExp.measurementContainer_.emplace_back(std::move(rowMeasurement));
			}
			catch (const char* msg) {
				cerr << msg << endl;
				std::cin.clear();
			}
		}		
		tempHeadings.clear();


		// if file is from openFileDialogue, save the experiment locally to data folder
		if (readFlag == 'f')
		{
			// for checking file exists and can be wrote to
			int check = tempExp.saveExperiment('s');
			if (check != 1)
			{
				return;
			}
		}

		// move object to the map
		u[n] = std::move(tempExp);
		u[n].dataHeadings_ = tempDataHeadings;
		dataFile.close();
		std::cout << "Experiment " << n << " loaded successfully\n";
		return;
	}
Example #28
0
bool ConvertToString( const std::wstring wstr, std::string& result )
{
    #ifdef MSVC
        // set locale
        RussianLocale locale;

        result.erase();

        size_t bufferLength = 0;
        wcstombs_s( &bufferLength, NULL, 0, wstr.c_str(), -1 );

        char* resultBuffer = (char*)malloc( bufferLength );
        memset( resultBuffer, 0, bufferLength );

        if( wcstombs_s( &bufferLength, resultBuffer, bufferLength, wstr.c_str(), -1 ) )
        {
            std::wcout << L"Error while converting: " + wstr ;
            if( resultBuffer )
            {
                free( resultBuffer );
            }
            return false;
        }
        result = string( resultBuffer );
        if( resultBuffer )
        {
            free( resultBuffer );
        }
        return true;
    #else
// number 1
        const size_t sz = wstr.length();
        if(sz == 0)
        {
            result = std::string();
            return true;
        }

        locale loc = std::locale("ru_RU.UTF-8");

        //typedef std::codecvt<wchar_t, char, mbstate_t> cvt;

        mbstate_t state;
        memset (&state,0,sizeof(state));

        char *cnext;
        const wchar_t *wnext;
        const wchar_t *wcstr = wstr.c_str();


        std::codecvt<wchar_t, char, mbstate_t>::result res;
        size_t resLength = std::use_facet<std::codecvt<wchar_t, char, mbstate_t> >(loc).max_length() * sz;
        // extract current locale??
        char *buffer = new char[resLength + 1];
        std::uninitialized_fill(buffer, buffer + resLength, 0);
        res = std::use_facet< std::codecvt<wchar_t, char, mbstate_t> >(loc).out(state, wcstr, wcstr + sz, wnext, buffer, buffer + resLength, cnext);

        result = string(buffer);
        delete[] (buffer);
        if(res == std::codecvt<wchar_t, char, mbstate_t>::error)
        {
            return false;
        }
        return true;
#endif
}
Example #29
0
File: Trie.cpp Project: arpg/CVars
static std::string remove_spaces( std::string str )
{
  str.erase( str.find_last_not_of( ' ' ) + 1 );
  str.erase( 0, str.find_first_not_of( ' ' ) );
  return str;
}
Example #30
0
/**
Convert a Exif tag to a C string
*/
static const char* 
ConvertExifTag(FITAG *tag) {
	char format[MAX_TEXT_EXTENT];
	static std::string buffer;

	if(!tag)
		return NULL;

	buffer.erase();

	// convert the tag value to a string buffer

	switch(FreeImage_GetTagID(tag)) {
		case TAG_ORIENTATION:
		{
			unsigned short orientation = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch (orientation) {
				case 1:
					return "top, left side";
				case 2:
					return "top, right side";
				case 3:
					return "bottom, right side";
				case 4:
					return "bottom, left side";
				case 5:
					return "left side, top";
				case 6:
					return "right side, top";
				case 7:
					return "right side, bottom";
				case 8:
					return "left side, bottom";
				default:
					break;
			}
		}
		break;

		case TAG_REFERENCE_BLACK_WHITE:
		{
			DWORD *pvalue = (DWORD*)FreeImage_GetTagValue(tag);
			if(FreeImage_GetTagLength(tag) == 48) {
				// reference black point value and reference white point value (ReferenceBlackWhite)
				int blackR = 0, whiteR = 0, blackG = 0, whiteG = 0, blackB = 0, whiteB = 0;
				if(pvalue[1])
					blackR = (int)(pvalue[0] / pvalue[1]);
				if(pvalue[3])
					whiteR = (int)(pvalue[2] / pvalue[3]);
				if(pvalue[5])
					blackG = (int)(pvalue[4] / pvalue[5]);
				if(pvalue[7])
					whiteG = (int)(pvalue[6] / pvalue[7]);
				if(pvalue[9])
					blackB = (int)(pvalue[8] / pvalue[9]);
				if(pvalue[11])
					whiteB = (int)(pvalue[10] / pvalue[11]);

				sprintf(format, "[%d,%d,%d] [%d,%d,%d]", blackR, blackG, blackB, whiteR, whiteG, whiteB);
				buffer += format;
				return buffer.c_str();
			}

		}
		break;

		case TAG_COLOR_SPACE:
		{
			unsigned short colorSpace = *((unsigned short *)FreeImage_GetTagValue(tag));
			if (colorSpace == 1) {
				return "sRGB";
			} else if (colorSpace == 65535) {
				return "Undefined";
			} else {
				return "Unknown";
			}
		}
		break;

		case TAG_COMPONENTS_CONFIGURATION:
		{
			const char *componentStrings[7] = {"", "Y", "Cb", "Cr", "R", "G", "B"};
			BYTE *pvalue = (BYTE*)FreeImage_GetTagValue(tag);
			for(DWORD i = 0; i < MIN((DWORD)4, FreeImage_GetTagCount(tag)); i++) {
				int j = pvalue[i];
				if(j > 0 && j < 7)
					buffer += componentStrings[j];
			}
			return buffer.c_str();
		}
		break;

		case TAG_COMPRESSED_BITS_PER_PIXEL:
		{
			FIRational r(tag);
			buffer = r.toString();
			if(buffer == "1")
				buffer += " bit/pixel";
			else 
				buffer += " bits/pixel";
			return buffer.c_str();
		}
		break;

		case TAG_X_RESOLUTION:
		case TAG_Y_RESOLUTION:
		case TAG_FOCAL_PLANE_X_RES:
		case TAG_FOCAL_PLANE_Y_RES:
		case TAG_BRIGHTNESS_VALUE:
		case TAG_EXPOSURE_BIAS_VALUE:
		{
			FIRational r(tag);
			buffer = r.toString();
			return buffer.c_str();
		}
		break;

		case TAG_RESOLUTION_UNIT:
		case TAG_FOCAL_PLANE_UNIT:
		{
			unsigned short resolutionUnit = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch (resolutionUnit) {
				case 1:
					return "(No unit)";
				case 2:
					return "inches";
				case 3:
					return "cm";
				default:
					break;
			}
		}
		break;

		case TAG_YCBCR_POSITIONING:
		{
			unsigned short yCbCrPosition = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch (yCbCrPosition) {
				case 1:
					return "Center of pixel array";
				case 2:
					return "Datum point";
				default:
					break;
			}
		} 
		break;

		case TAG_EXPOSURE_TIME:
		{
			FIRational r(tag);
			buffer = r.toString();
			buffer += " sec";
			return buffer.c_str();
		}
		break;

		case TAG_SHUTTER_SPEED_VALUE:
		{
			FIRational r(tag);
			LONG apexValue = r.longValue();
			LONG apexPower = 1 << apexValue;
			sprintf(format, "1/%d sec", (int)apexPower);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_APERTURE_VALUE:
		case TAG_MAX_APERTURE_VALUE:
		{
			FIRational r(tag);
			double apertureApex = r.doubleValue();
	        double rootTwo = sqrt((double)2);
			double fStop = pow(rootTwo, apertureApex);
			sprintf(format, "F%.1f", fStop);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_FNUMBER:
		{
			FIRational r(tag);
			double fnumber = r.doubleValue();
			sprintf(format, "F%.1f", fnumber);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_FOCAL_LENGTH:
		{
			FIRational r(tag);
			double focalLength = r.doubleValue();
			sprintf(format, "%.1f mm", focalLength);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_FOCAL_LENGTH_IN_35MM_FILM:
		{
			unsigned short focalLength = *((unsigned short *)FreeImage_GetTagValue(tag));
			sprintf(format, "%hu mm", focalLength);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_FLASH:
		{
			unsigned short flash = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch(flash) {
				case 0x0000:
					return "Flash did not fire";
				case 0x0001:
					return "Flash fired";
				case 0x0005:
					return "Strobe return light not detected";
				case 0x0007:
					return "Strobe return light detected";
				case 0x0009:
					return "Flash fired, compulsory flash mode";
				case 0x000D:
					return "Flash fired, compulsory flash mode, return light not detected";
				case 0x000F:
					return "Flash fired, compulsory flash mode, return light detected";
				case 0x0010:
					return "Flash did not fire, compulsory flash mode";
				case 0x0018:
					return "Flash did not fire, auto mode";
				case 0x0019:
					return "Flash fired, auto mode";
				case 0x001D:
					return "Flash fired, auto mode, return light not detected";
				case 0x001F:
					return "Flash fired, auto mode, return light detected";
				case 0x0020:
					return "No flash function";
				case 0x0041:
					return "Flash fired, red-eye reduction mode";
				case 0x0045:
					return "Flash fired, red-eye reduction mode, return light not detected";
				case 0x0047:
					return "Flash fired, red-eye reduction mode, return light detected";
				case 0x0049:
					return "Flash fired, compulsory flash mode, red-eye reduction mode";
				case 0x004D:
					return "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected";
				case 0x004F:
					return "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected";
				case 0x0059:
					return "Flash fired, auto mode, red-eye reduction mode";
				case 0x005D:
					return "Flash fired, auto mode, return light not detected, red-eye reduction mode";
				case 0x005F:
					return "Flash fired, auto mode, return light detected, red-eye reduction mode";
				default:
					sprintf(format, "Unknown (%d)", flash);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_SCENE_TYPE:
		{
			BYTE sceneType = *((BYTE*)FreeImage_GetTagValue(tag));
			if (sceneType == 1) {
				return "Directly photographed image";
			} else {
				sprintf(format, "Unknown (%d)", sceneType);
				buffer += format;
				return buffer.c_str();
			}
		}
		break;

		case TAG_SUBJECT_DISTANCE:
		{
			FIRational r(tag);
			if(r.getNumerator() == 0xFFFFFFFF) {
				return "Infinity";
			} else if(r.getNumerator() == 0) {
				return "Distance unknown";
			} else {
				double distance = r.doubleValue();
				sprintf(format, "%.3f meters", distance);
				buffer += format;
				return buffer.c_str();
			}
		}
		break;
			
		case TAG_METERING_MODE:
		{
			unsigned short meteringMode = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch (meteringMode) {
				case 0:
					return "Unknown";
				case 1:
					return "Average";
				case 2:
					return "Center weighted average";
				case 3:
					return "Spot";
				case 4:
					return "Multi-spot";
				case 5:
					return "Multi-segment";
				case 6:
					return "Partial";
				case 255:
					return "(Other)";
				default:
					return "";
			}
		}
		break;

		case TAG_LIGHT_SOURCE:
		{
			unsigned short lightSource = *((unsigned short *)FreeImage_GetTagValue(tag));
			switch (lightSource) {
				case 0:
					return "Unknown";
				case 1:
					return "Daylight";
				case 2:
					return "Fluorescent";
				case 3:
					return "Tungsten (incandescent light)";
				case 4:
					return "Flash";
				case 9:
					return "Fine weather";
				case 10:
					return "Cloudy weather";
				case 11:
					return "Shade";
				case 12:
					return "Daylight fluorescent (D 5700 - 7100K)";
				case 13:
					return "Day white fluorescent (N 4600 - 5400K)";
				case 14:
					return "Cool white fluorescent (W 3900 - 4500K)";
				case 15:
					return "White fluorescent (WW 3200 - 3700K)";
				case 17:
					return "Standard light A";
				case 18:
					return "Standard light B";
				case 19:
					return "Standard light C";
				case 20:
					return "D55";
				case 21:
					return "D65";
				case 22:
					return "D75";
				case 23:
					return "D50";
				case 24:
					return "ISO studio tungsten";
				case 255:
					return "(Other)";
				default:
					return "";
			}
		}
		break;

		case TAG_SENSING_METHOD:
		{
			unsigned short sensingMethod = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (sensingMethod) {
				case 1:
					return "(Not defined)";
				case 2:
					return "One-chip color area sensor";
				case 3:
					return "Two-chip color area sensor";
				case 4:
					return "Three-chip color area sensor";
				case 5:
					return "Color sequential area sensor";
				case 7:
					return "Trilinear sensor";
				case 8:
					return "Color sequential linear sensor";
				default:
					return "";
			}
		}
		break;

		case TAG_FILE_SOURCE:
		{
			BYTE fileSource = *((BYTE*)FreeImage_GetTagValue(tag));
			if (fileSource == 3) {
				return "Digital Still Camera (DSC)";
			} else {
				sprintf(format, "Unknown (%d)", fileSource);
				buffer += format;
				return buffer.c_str();
			}
        }
		break;

		case TAG_EXPOSURE_PROGRAM:
		{
			unsigned short exposureProgram = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (exposureProgram) {
				case 1:
					return "Manual control";
				case 2:
					return "Program normal";
				case 3:
					return "Aperture priority";
				case 4:
					return "Shutter priority";
				case 5:
					return "Program creative (slow program)";
				case 6:
					return "Program action (high-speed program)";
				case 7:
					return "Portrait mode";
				case 8:
					return "Landscape mode";
				default:
					sprintf(format, "Unknown program (%d)", exposureProgram);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_CUSTOM_RENDERED:
		{
			unsigned short customRendered = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (customRendered) {
				case 0:
					return "Normal process";
				case 1:
					return "Custom process";
				default:
					sprintf(format, "Unknown rendering (%d)", customRendered);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_EXPOSURE_MODE:
		{
			unsigned short exposureMode = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (exposureMode) {
				case 0:
					return "Auto exposure";
				case 1:
					return "Manual exposure";
				case 2:
					return "Auto bracket";
				default:
					sprintf(format, "Unknown mode (%d)", exposureMode);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_WHITE_BALANCE:
		{
			unsigned short whiteBalance = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (whiteBalance) {
				case 0:
					return "Auto white balance";
				case 1:
					return "Manual white balance";
				default:
					sprintf(format, "Unknown (%d)", whiteBalance);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_SCENE_CAPTURE_TYPE:
		{
			unsigned short sceneType = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (sceneType) {
				case 0:
					return "Standard";
				case 1:
					return "Landscape";
				case 2:
					return "Portrait";
				case 3:
					return "Night scene";
				default:
					sprintf(format, "Unknown (%d)", sceneType);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_GAIN_CONTROL:
		{
			unsigned short gainControl = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (gainControl) {
				case 0:
					return "None";
				case 1:
					return "Low gain up";
				case 2:
					return "High gain up";
				case 3:
					return "Low gain down";
				case 4:
					return "High gain down";
				default:
					sprintf(format, "Unknown (%d)", gainControl);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_CONTRAST:
		{
			unsigned short contrast = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (contrast) {
				case 0:
					return "Normal";
				case 1:
					return "Soft";
				case 2:
					return "Hard";
				default:
					sprintf(format, "Unknown (%d)", contrast);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_SATURATION:
		{
			unsigned short saturation = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (saturation) {
				case 0:
					return "Normal";
				case 1:
					return "Low saturation";
				case 2:
					return "High saturation";
				default:
					sprintf(format, "Unknown (%d)", saturation);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_SHARPNESS:
		{
			unsigned short sharpness = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (sharpness) {
				case 0:
					return "Normal";
				case 1:
					return "Soft";
				case 2:
					return "Hard";
				default:
					sprintf(format, "Unknown (%d)", sharpness);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_SUBJECT_DISTANCE_RANGE:
		{
			unsigned short distanceRange = *((unsigned short *)FreeImage_GetTagValue(tag));

			switch (distanceRange) {
				case 0:
					return "unknown";
				case 1:
					return "Macro";
				case 2:
					return "Close view";
				case 3:
					return "Distant view";
				default:
					sprintf(format, "Unknown (%d)", distanceRange);
					buffer += format;
					return buffer.c_str();
			}
		}
		break;

		case TAG_ISO_SPEED_RATINGS:
		{
			unsigned short isoEquiv = *((unsigned short *)FreeImage_GetTagValue(tag));
			if (isoEquiv < 50) {
				isoEquiv *= 200;
			}
			sprintf(format, "%d", isoEquiv);
			buffer += format;
			return buffer.c_str();
		}
		break;

		case TAG_USER_COMMENT:
		{
			// first 8 bytes are used to define an ID code
			// we assume this is an ASCII string
			const BYTE *userComment = (BYTE*)FreeImage_GetTagValue(tag);
			for(DWORD i = 8; i < FreeImage_GetTagLength(tag); i++) {
				buffer += userComment[i];
			}
			buffer += '\0';
			return buffer.c_str();
		}
		break;

		case TAG_COMPRESSION:
		{
			WORD compression = *((WORD*)FreeImage_GetTagValue(tag));
			switch(compression) {
				case TAG_COMPRESSION_NONE:
					sprintf(format, "dump mode (%d)", compression);
					break;
				case TAG_COMPRESSION_CCITTRLE:
					sprintf(format, "CCITT modified Huffman RLE (%d)", compression);
					break;
				case TAG_COMPRESSION_CCITTFAX3:
					sprintf(format, "CCITT Group 3 fax encoding (%d)", compression);
					break;
				/*
				case TAG_COMPRESSION_CCITT_T4:
					sprintf(format, "CCITT T.4 (TIFF 6 name) (%d)", compression);
					break;
				*/
				case TAG_COMPRESSION_CCITTFAX4:
					sprintf(format, "CCITT Group 4 fax encoding (%d)", compression);
					break;
				/*
				case TAG_COMPRESSION_CCITT_T6:
					sprintf(format, "CCITT T.6 (TIFF 6 name) (%d)", compression);
					break;
				*/
				case TAG_COMPRESSION_LZW:
					sprintf(format, "LZW (%d)", compression);
					break;
				case TAG_COMPRESSION_OJPEG:
					sprintf(format, "!6.0 JPEG (%d)", compression);
					break;
				case TAG_COMPRESSION_JPEG:
					sprintf(format, "JPEG (%d)", compression);
					break;
				case TAG_COMPRESSION_NEXT:
					sprintf(format, "NeXT 2-bit RLE (%d)", compression);
					break;
				case TAG_COMPRESSION_CCITTRLEW:
					sprintf(format, "CCITTRLEW (%d)", compression);
					break;
				case TAG_COMPRESSION_PACKBITS:
					sprintf(format, "PackBits Macintosh RLE (%d)", compression);
					break;
				case TAG_COMPRESSION_THUNDERSCAN:
					sprintf(format, "ThunderScan RLE (%d)", compression);
					break;
				case TAG_COMPRESSION_PIXARFILM:
					sprintf(format, "Pixar companded 10bit LZW (%d)", compression);
					break;
				case TAG_COMPRESSION_PIXARLOG:
					sprintf(format, "Pixar companded 11bit ZIP (%d)", compression);
					break;
				case TAG_COMPRESSION_DEFLATE:
					sprintf(format, "Deflate compression (%d)", compression);
					break;
				case TAG_COMPRESSION_ADOBE_DEFLATE:
					sprintf(format, "Adobe Deflate compression (%d)", compression);
					break;
				case TAG_COMPRESSION_DCS:
					sprintf(format, "Kodak DCS encoding (%d)", compression);
					break;
				case TAG_COMPRESSION_JBIG:
					sprintf(format, "ISO JBIG (%d)", compression);
					break;
				case TAG_COMPRESSION_SGILOG:
					sprintf(format, "SGI Log Luminance RLE (%d)", compression);
					break;
				case TAG_COMPRESSION_SGILOG24:
					sprintf(format, "SGI Log 24-bit packed (%d)", compression);
					break;
				case TAG_COMPRESSION_JP2000:
					sprintf(format, "Leadtools JPEG2000 (%d)", compression);
					break;
				case TAG_COMPRESSION_LZMA:
					sprintf(format, "LZMA2 (%d)", compression);
					break;
				default:
					sprintf(format, "Unknown type (%d)", compression);
					break;
			}

			buffer += format;
			return buffer.c_str();
		}
		break;
	}

	return ConvertAnyTag(tag);
}