/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "XMString.h"


XMString::XMString(const char* s,const char* font):
	str_(0)
{

	if(!s) return;

	if(font == 0) font = "normal";


	if(*s == '\n')
	{
		str_ = XmStringSeparatorCreate();
		*this += XMString(s+1,font);
		return;
	}


	if(strchr(s,'\n'))
	{

		XmString xms1;
		XmString xms2;
		XmString line;
		XmString separator;
		char     *p;
		char     *t = XtNewString(s);	/* Make a copy for strtok not to */
                                 	/* damage the original string    */

		separator = XmStringSeparatorCreate();
		p         = strtok(t,"\n");
		xms1      = XmStringCreateLtoR(p,(char*)font);

		while (p = strtok(NULL,"\n"))
		{
			line = XmStringCreateLtoR(p,(char*)font);
			xms2 = XmStringConcat(xms1,separator);
			XmStringFree(xms1);
			xms1 = XmStringConcat(xms2,line);
			XmStringFree(xms2);
			XmStringFree(line);
		}

		XmStringFree(separator);
		XtFree(t);

		str_ =  xms1;
	}
	else str_ = XmStringCreateLtoR((char*)s,(char*)font);
}

XMString::XMString(const string& s,const char* font):
	str_(0)
{
	*this = XMString(s.c_str(),font);
}

XMString::~XMString()
{
	if(str_)
		XmStringFree(str_);
}

XMString::XMString(XmString s):
	str_(XmStringCopy(s))
{
}

XMString::XMString(const XMString& other):
	str_(other.str_?XmStringCopy(other.str_):0)
{
}

XMString& XMString::operator=(const XMString& other)
{
	if(str_) XmStringFree(str_);
	str_ = 0;
	if(other.str_) str_ = XmStringCopy(other.str_);
	return *this;
}

XMString XMString::operator+(const XMString& other) const
{
	if(!other.str_) return *this;
	if(!str_) return other;

	XMString x;
	x.str_ = XmStringConcat(str_,other.str_);
	return x;
}

XMString& XMString::operator+=(const XMString& other)
{
	*this = *this + other;
	return *this;
}

XMString::operator string() const
{
	if(str_ == 0) return string();
	
	XmStringContext  context;
	char             *text;
	XmStringCharSet   charset;
	XmStringDirection dir;
	Boolean           separator;
	int               done = FALSE;

	string result;

	XmStringInitContext (&context, str_);
	while (!done)
		if(XmStringGetNextSegment (context, &text, &charset, &dir, &separator))
		{
			if(separator) /* Stop when next segment is a separator */
				done = TRUE;

			result += text;

			XtFree(charset);
			XtFree(text);
		}
		else
			done = TRUE;

	XmStringFreeContext (context);

	return result;

}
