/* +---------------------------------------------------------------------------+
   |          The Mobile Robot Programming Toolkit (MRPT) C++ library          |
   |                                                                           |
   |                   http://mrpt.sourceforge.net/                            |
   |                                                                           |
   |   Copyright (C) 2005-2008  University of Malaga                           |
   |                                                                           |
   |    This software was written by the Perception and Robotics               |
   |      research group, University of Malaga (Spain).                        |
   |    Contact: Jose-Luis Blanco  <jlblanco@ctima.uma.es>                     |
   |                                                                           |
   |  This file is part of the MRPT project.                                   |
   |                                                                           |
   |     MRPT is free software: you can redistribute it and/or modify          |
   |     it under the terms of the GNU General Public License as published by  |
   |     the Free Software Foundation, either version 3 of the License, or     |
   |     (at your option) any later version.                                   |
   |                                                                           |
   |   MRPT is distributed in the hope that it will be useful,                 |
   |     but WITHOUT ANY WARRANTY; without even the implied warranty of        |
   |     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         |
   |     GNU General Public License for more details.                          |
   |                                                                           |
   |     You should have received a copy of the GNU General Public License     |
   |     along with MRPT.  If not, see <http://www.gnu.org/licenses/>.         |
   |                                                                           |
   +---------------------------------------------------------------------------+ */
#ifndef UTILSDEFS_H
#define UTILSDEFS_H

/* ------------------------------------
          Disable some warnings
   ------------------------------------ */
#if defined(_MSC_VER)
	// (Compiler: Visual C++) Disable warning for too long debug names:
	#pragma warning(disable:4786)
	// (Compiler: Visual C++) Disable warning for unreachable code (I don't know why some of these errors appear in the STANDARD LIBRARY headers with Visual Studio 2003!):
	#pragma warning(disable:4702)
	// (Compiler: Visual C++) Conversion double->float
	#pragma warning (disable:4244)
	#pragma warning (disable:4305)
	#pragma warning (disable:4267)
	// Visual C++ does not implement decl. specifiers: throw(A,B,...)
	#pragma warning( disable : 4290 )
#endif

#if defined(__BORLANDC__)
	// (Compiler: Borland C++) Disable a warning for inline functions
	#pragma warn -8027
        // (Compiler: Borland C++) Disable a warning for override of virtual functions, while in reality there are many virtual function with different parameters
	#pragma warn -8012
	#pragma warn -8022
#endif

// For the new more secure library in VC++8
#if defined(_MSC_VER) && (_MSC_VER>=1400)
	#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
		#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
	#endif
#endif



#include <MRPT/config.h>
#include <MRPT/UTILS/MRPT_OS.h>

// If we are building a DLL, do not link against the .lib files:
#if defined(MRPT_BUILT_AS_DLL) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	define MRPT_SKIP_AUTOINCLUDE_LIBS
#endif

#define _IAMINUTILSDEFS_H
#include <MRPT/UTILS/utils_impexp.h>  // DLL import/export definitions
#undef _IAMINUTILSDEFS_H

/* ------------------------------------------------
    Automatically tell the linker to include
	 the correct MRPT ".lib" file into the
	 user's application.
   ----------------------------------------------- */
// Borland C++
#if defined(__BORLANDC__) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	if defined(_DEBUG)
#		pragma comment (lib,"libMRPTd_bcc.lib")
#	else
#		pragma comment (lib,"libMRPT_bcc.lib")
#	endif
#endif

// Microsoft Visual C++ 6.0
#if defined(_MSC_VER) && (_MSC_VER==1200) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	if defined(_DEBUG)
#		pragma comment (lib,"libMRPTd_MSVC6.lib")
#	else
#		pragma comment (lib,"libMRPT_MSVC6.lib")
#	endif
#endif

#if defined(_MSC_VER)
#	if defined(_DEBUG)
#		pragma comment (lib,"wxbase28d.lib")
#		pragma comment (lib,"wxjpegd.lib")
#		pragma comment (lib,"wxpngd.lib")
#		pragma comment (lib,"wxtiffd.lib")
#		pragma comment (lib,"wxzlibd.lib")
#		pragma comment (lib,"wxmsw28d_adv.lib")
#		pragma comment (lib,"wxmsw28d_aui.lib")
#		pragma comment (lib,"wxmsw28d_core.lib")
#		pragma comment (lib,"wxmsw28d_gl.lib")
#	else
#		pragma comment (lib,"wxbase28.lib")
#		pragma comment (lib,"wxjpeg.lib")
#		pragma comment (lib,"wxpng.lib")
#		pragma comment (lib,"wxtiff.lib")
#		pragma comment (lib,"wxzlib.lib")
#		pragma comment (lib,"wxmsw28_adv.lib")
#		pragma comment (lib,"wxmsw28_aui.lib")
#		pragma comment (lib,"wxmsw28_core.lib")
#		pragma comment (lib,"wxmsw28_gl.lib")
#	endif
#endif


// Microsoft Visual C++ 2003
#if defined(_MSC_VER) && ((_MSC_VER==1300) || (_MSC_VER==1310)) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	if defined(_DEBUG)
#		pragma comment (lib,"libMRPTd_MSVC7.lib")
#	else
#		pragma comment (lib,"libMRPT_MSVC7.lib")
#	endif
#endif

// Microsoft Visual C++ 2005
#if defined(_MSC_VER) && (_MSC_VER==1400) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	if defined(_DEBUG)
#		pragma comment (lib,"libMRPTd_MSVC8.lib")
#	else
#		pragma comment (lib,"libMRPT_MSVC8.lib")
#	endif
#endif

/* ------------------------------------------------
    Automatically tell the linker to include
	 the ANN library into the user's application
	 as well.
   ----------------------------------------------- */
#if (defined(_MSC_VER) || defined(__BORLANDC__) ) && !defined(MRPT_SKIP_AUTOINCLUDE_LIBS)
#	if defined(_DEBUG)
#		pragma comment (lib,"libANNd.lib")
#	else
#		pragma comment (lib,"libANN.lib")
#	endif
#endif


// A cross-compiler definition for "deprecated"-warnings
#if defined(__GNUC__) && (__GNUC__ - 0 > 3 || (__GNUC__ - 0 == 3 && __GNUC_MINOR__ - 0 >= 2))
   /* gcc >= 3.2 */
#   define MRPT_DEPRECATED_PRE
#   define MRPT_DEPRECATED_POST __attribute__ ((deprecated))
# elif defined(_MSC_VER) && (_MSC_VER >= 1300)
  /* msvc >= 7 */
#   define MRPT_DEPRECATED_PRE  __declspec(deprecated)
#   define MRPT_DEPRECATED_POST
# else
#  define MRPT_DEPRECATED_PRE
#  define MRPT_DEPRECATED_POST
# endif



// Utils C++ headers:
#include <stdlib.h>
//#include <stdio.h>
#include <math.h>
//#include <float.h>
//#include <stdarg.h>
//#include <memory.h>
//#include <string.h>

// C++ STD Library:
#include <algorithm>
#include <iostream>
#include <fstream>
//#include <vector>
//#include <deque>
//#include <queue>
//#include <map>
//#include <set>
//#include <string>
#include <exception>
#include <stdexcept>
//#include <limits>
//#include <iomanip>
//#include <locale>
//#include <sstream>
//#include <cassert>
#include <sstream>

// The  modifier is not defined on GCC
#if defined(__GNUC__)
	#include <stdint.h>
#endif

#if defined(__BORLANDC__) || defined(_MSC_VER)
   typedef signed __int64 int64_t;
   typedef unsigned __int64 uint64_t;

   typedef signed __int32 int32_t;
   typedef unsigned __int32 uint32_t;

   typedef signed __int16 int16_t;
   typedef unsigned __int16 uint16_t;

   typedef signed __int8 int8_t;
   typedef unsigned __int8 uint8_t;
#endif


//  Defintions of data types:
// ---------------------------------------------------------
/** A type for passing a vector of longs.
*/
typedef std::vector<int64_t> vector_long;

/** A type for passing a vector of ints.
*/
typedef std::vector<int32_t> vector_int;

/** A type for passing a vector of floats.
*/
typedef std::vector<float> vector_float;

/** A type for passing a vector of doubles.
*/
typedef std::vector<double> vector_double;

/** A type for passing a vector of 16-bits unsigned numbers.
*/
typedef std::vector<uint16_t> vector_word;

/** A type for passing a vector of 32-bits unsigned numbers.
*/
typedef std::vector<uint32_t> vector_uint;

/** A type for passing a vector of strings.
*/
typedef std::vector<std::string> vector_string;

/** A type for passing a vector of boolean values.
*/
typedef std::vector<bool> vector_bool;

/** A type for passing a vector of bytes.
*/
typedef std::vector<uint8_t> vector_byte;

/** A type for vectors of size_t's.
*/
typedef std::vector<size_t> vector_size_t;


namespace UTILS
{
	// Forward definition: (Required for Visual C++ 6 implementation of THROW_EXCEPTION...)
	namespace SystemUtils
	{
		std::string  extractFileName(const std::string &filePath);
	}

} // End of namespace

using namespace UTILS;

/** Forward definitions for numerical test functions:
  */
namespace UTILS
{
    class CFileStream;

	namespace MATH
	{
	    bool isNan(float v);
	    bool isNan(double v);
	    bool isFinite(float v);
	    bool isFinite(double v);
	}
}




/** A std::string version of C sprintf.
  *  You can call this to obtain a std::string using printf-like syntax.
  *  Based on very nice code by Paul Senzee, published at http://senzee.blogspot.com/2006/05/c-formatting-stdstring.html
  *  Function implemented in SystemUtils.cpp
  */
std::string format(const char *fmt, ...) MRPT_printf_format_check(1,2);


/** A macro for obtaining the name of the current function:
  */
#if defined(__BORLANDC__)
		#define	__CURRENT_FUNCTION_NAME__	__FUNC__
#elif defined(_MSC_VER) && (_MSC_VER>=1300)
		#define	__CURRENT_FUNCTION_NAME__	__FUNCTION__
#elif defined(_MSC_VER) && (_MSC_VER<1300)
		// Visual C++ 6 HAS NOT A __FUNCTION__ equivalent.
#define	__CURRENT_FUNCTION_NAME__	::UTILS::SystemUtils::extractFileName(__FILE__).c_str()
#else
		#define	__CURRENT_FUNCTION_NAME__	__PRETTY_FUNCTION__
#endif


/** \def THROW_EXCEPTION(msg)
 * \param msg This can be a char*, a std::string, or a literal string.
 * Defines a unified way of reporting exceptions
 * \sa MRPT_TRY_START, MRPT_TRY_END, THROW_EXCEPTION_CUSTOM_MSG1
 */
#define THROW_EXCEPTION(msg)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << "\n\n =============== MRPT EXCEPTION =============\n";\
		auxCompStr << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		auxCompStr << msg << "\nCALL STACK:\n";\
		throw std::logic_error( auxCompStr.str() );\
	}\

/** \def THROW_EXCEPTION_CUSTOM_MSG1
  * \param e The caught exception.
  *	\param msg Is a char* or literal string.
  */
#define THROW_EXCEPTION_CUSTOM_MSG1(msg,param1)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << "\n\n =============== MRPT EXCEPTION =============\n";\
		auxCompStr << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		auxCompStr << format(msg,param1);\
		auxCompStr << "\nCALL STACK:\n";\
		throw std::logic_error( auxCompStr.str() );\
	}\


/** \def THROW_TYPED_EXCEPTION(msg,exceptionClass)
 * Defines a unified way of reporting exceptions of type different from "std::exception"
 * \sa MRPT_TRY_START, MRPT_TRY_END
 */
#define THROW_TYPED_EXCEPTION(msg,exceptionClass)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << "\n\n =============== MRPT EXCEPTION =============\n";\
		auxCompStr << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		auxCompStr << msg << "\nCALL STACK:\n";\
		throw exceptionClass( auxCompStr.str() );\
	}\

/** \def THROW_EXCEPTION_CUSTOM_MSG1
  * \param e The caught exception.
  *	\param msg Is a char* or literal string.
  */
#define THROW_TYPED_EXCEPTION_CUSTOM_MSG1(msg,param1,exceptionClass)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << "\n\n =============== MRPT EXCEPTION =============\n";\
		auxCompStr << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		auxCompStr << format(msg,param1);\
		auxCompStr << "\nCALL STACK:\n";\
		throw exceptionClass( auxCompStr.str() );\
	}\


/** \def THROW_STACKED_EXCEPTION
 * \sa MRPT_TRY_START, MRPT_TRY_END
 */
#define THROW_STACKED_EXCEPTION(e)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << e.what() ; \
		auxCompStr << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		std::string str;\
		auxCompStr.str(str); \
		if (str.size()>3000) { std::cerr << "TOO MANY STACKED EXCEPTIONS!: " << std::endl << str << std::endl; abort(); } \
		throw std::logic_error( str );\
	}\

/** \def THROW_STACKED_EXCEPTION_CUSTOM_MSG
  * \param e The caught exception.
  *	\param msg Is a char* or std::string.
  */
#define THROW_STACKED_EXCEPTION_CUSTOM_MSG1(e,msg)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << e.what() ; \
		auxCompStr << msg << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << "(User msg above)\n";\
		throw std::logic_error( auxCompStr.str() );\
	}\

/** \def THROW_STACKED_EXCEPTION_CUSTOM_MSG
  * \param e The caught exception.
  *	\param stuff Is a printf-like sequence of params, e.g: "The error happens for x=%i",x
  */
#define THROW_STACKED_EXCEPTION_CUSTOM_MSG2(e,stuff,param1)	\
	{\
		std::ostringstream auxCompStr;\
		auxCompStr << e.what(); \
		auxCompStr << format( stuff, param1 ) << "\n" << __CURRENT_FUNCTION_NAME__ << ", line " << __LINE__ << ":\n";\
		throw std::logic_error( auxCompStr.str() );\
	}\

/** For use in CSerializable implementations */
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(V) THROW_EXCEPTION(format("Cannot parse object: unknown serialization version number: '%i'",static_cast<int>(version)))


#if MRPT_HAS_ASSERT
	/**
	 * Defines an assertion mechanism.
	 * \note Do NOT put code that must be always executed inside this statement, but just comparisons. This is because users might require ASSERT_'s to be ignored for optimized releases.
	 * \sa MRPT_TRY_START, MRPT_TRY_END
	 */
#	define ASSERT_(f) \
	{ \
	if (!(f)) \
		{ \
			::std::string tmpStr("Assert condition failed: "); \
			tmpStr+= #f; \
			THROW_EXCEPTION( tmpStr.c_str() ); \
		} \
	}

/** Throws an exception if the number is NaN, IND, or +/-INF, or return the same number otherwise.
  */
#define MRPT_CHECK_NORMAL_NUMBER(val) \
	{ \
		double	v=(val); \
		if (UTILS::MATH::isNan(v)) THROW_EXCEPTION("Check failed (value is NaN)"); \
		if (!UTILS::MATH::isFinite(v)) THROW_EXCEPTION("Check failed (value is not finite)"); \
	}

#else
#	define ASSERT_(f)
#	define MRPT_CHECK_NORMAL_NUMBER(val)
#endif



/** Can be used to avoid "not used parameters" warnings from the compiler
 */
#define MRPT_UNUSED_PARAM(a)		(void)(a)

#if MRPT_HAS_STACKED_EXCEPTIONS
	/** The start of a standard MRPT "try...catch()" block that allows tracing throw the call stack after an exception.
	  * \sa MRPT_TRY_END,MRPT_TRY_END_WITH_CLEAN_UP
	  */
#	define MRPT_TRY_START	\
	try { \

	/** The end of a standard MRPT "try...catch()" block that allows tracing throw the call stack after an exception.
	  * \sa MRPT_TRY_START,MRPT_TRY_END_WITH_CLEAN_UP
	  */
#	define MRPT_TRY_END	\
	} \
	catch (std::exception &e) \
	{ \
		THROW_STACKED_EXCEPTION(e); \
	} \
	catch (...) \
	{ \
		THROW_EXCEPTION("Unexpected runtime error!"); \
	} \

	/** The end of a standard MRPT "try...catch()" block that allows tracing throw the call stack after an exception, including a "clean up" piece of code to be run before throwing the exceptions.
	  * \sa MRPT_TRY_END,MRPT_TRY_START
	  */
#	define MRPT_TRY_END_WITH_CLEAN_UP(stuff)	\
	} \
	catch (std::exception &e) \
	{ \
		{stuff} \
		THROW_STACKED_EXCEPTION(e); \
	} \
	catch (...) \
	{ \
		{ stuff } \
		THROW_EXCEPTION("Unexpected runtime error!"); \
	} \

#else
#	define MRPT_TRY_START
#	define MRPT_TRY_END
#	define MRPT_TRY_END_WITH_CLEAN_UP(stuff)
#endif

// Generic constants and defines:
// ---------------------------------------------------------

#ifndef M_PI
/** The PI constant
 */
	#define M_PI 3.1415926535897932384626433832795
#endif

#ifndef M_2PI
/** The 2*PI constant
 */
	#define M_2PI 6.283185307179586476925286766559
#endif

#define M_PIf  3.14159265358979f
#define M_2PIf 6.28318530717959f

/** Degrees to radians
 */
__inline double DEG2RAD(const double &x)
{
	return x*M_PI/180.0;
}
/** Degrees to radians
 */
__inline float DEG2RAD(const float &x)
{
	return x*M_PIf/180.0f;
}
/** Degrees to radians
 */
__inline float DEG2RAD(const int &x)
{
	return x*M_PIf/180.0f;
}

/** Radians to degrees
 */
__inline double RAD2DEG(const double &x)
{
	return x*180.0/M_PI;
}
/** Radians to degrees
 */
__inline float RAD2DEG(const float &x)
{
	return x*180.0f/M_PIf;
}

/** Returns the sign of X as "1" or "-1"
 */
#define sign(X)		(((X)<0) ? (-1):(1))

/** Returns the closer integer (int) to x
 */
#define round(X)	static_cast<int>(floor(X+0.5))

/** Inline function for the square of a number.
 */
template<class T>
inline T square(const T& x)    { return x*x; }

//  We want to avoid defining "max" & "min" as #define's since it create conflicts
//    with methods, variables, etc... with the same name in some compilers.
// Use std::max & std::min for all compilers by default, but for MSVC6 it does not exist:
#if defined(_MSC_VER) && (_MSC_VER<1300)
#	ifndef max
		namespace std
		{
			template<class T> inline const T max(const T& A,const T& B) { return A>B ? A:B; }
			template<class T> inline const T min(const T& A,const T& B) { return A<B ? A:B; }
		}
#	else
#		define  MAX3_MSVC6_VERSION
#	endif
#endif


// Min & Max:
#ifndef MAX3_MSVC6_VERSION
	template<typename T> inline const T  min3(const T& A, const T& B,const T& C) { return std::min<T>(A, std::min<T>(B,C) ); }
	template<typename T> inline const T  max3(const T& A, const T& B,const T& C) { return std::max<T>(A, std::max<T>(B,C) ); }
#else
#	define max3(A,B,C) max(A,max(B,C))
#	define min3(A,B,C) min(A,min(B,C))
#endif

namespace UTILS
{
	// --------------------------
	// Functors:
	//  Ret: NO  In:1-3
	// --------------------------

	/** A generic functor type for functions accepting 1 input arguments and returning nothing.
	*/
	typedef void (*TFunctor_noRet_1inputs)(const void *);

	/** A generic functor type for functions accepting 2 input arguments and returning nothing.
	*/
	typedef void (*TFunctor_noRet_2inputs)(const void *,const void *);

	/** A generic functor type for functions accepting 3 input arguments and returning nothing.
	*/
	typedef void (*TFunctor_noRet_3inputs)(const void *,const void *,const void *);

	// --------------------------
	// Functors:
	//  Ret: double  In:1-3
	// --------------------------

	/** A generic functor type for functions accepting 1 input arguments and returning a double value.
	*/
	typedef double (*TFunctor_retDouble_1inputs)(const void *);

	/** A generic functor type for functions accepting 2 input arguments and returning a double value.
	*/
	typedef double (*TFunctor_retDouble_2inputs)(const void *,const void *);

	/** A generic functor type for functions accepting 3 input arguments and returning a double value.
	*/
	typedef double (*TFunctor_retDouble_3inputs)(const void *,const void *,const void *);

	// --------------------------
	// Functors:
	//  Ret: vector  In: vector
	// --------------------------

	/** A generic functor type for functions accepting 1 vector and returning 1 vector.
	*/
	typedef void (*TFunctor_retVecDbl_inpVecDbl)(const vector_double &in, vector_double &out);

	/** A generic functor type for functions accepting 1 vector and returning 1 vector.
	*/
	typedef void (*TFunctor_retVecFlt_inpVecFlt)(const vector_float &in, vector_float &out);

	/** A generic functor type for functions accepting 1 vector and returning 1 vector.
	*/
	typedef void (*TFunctor_retVecInt_inpVecInt)(const vector_int &in, vector_int &out);

	// --------------------------
	// Functors:
	//  Ret: double  In: vectors
	// --------------------------

	/** A generic functor type for functions accepting 1 vector and returning 1 double.
	*/
	typedef double (*TFunctor_retDbl_inp1VecDbl)(const vector_double &in1);

	/** A generic functor type for functions accepting 2 vectors and returning 1 double.
	*/
	typedef double (*TFunctor_retDbl_inp2VecDbl)(const vector_double &in1,const vector_double &in2);

	/** A generic functor type for functions accepting 3 vectors and returning 1 double.
	*/
	typedef double (*TFunctor_retDbl_inp3VecDbl)(const vector_double &in1,const vector_double &in2,const vector_double &in3);


	/** For performing type casting from a pointer to its numeric value.
	*/
	#if defined(_MSC_VER) && (_MSC_VER>=1300)
		typedef unsigned long long POINTER_TYPE;
	#else
		typedef unsigned long POINTER_TYPE;
	#endif


	/** A template function for printing out the contents of a std::vector variable.
		*/
	template <class T>
	std::ostream& operator << (std::ostream& out, const std::vector<T> &d)
	{
		out << "[";
		for (typename std::vector<T>::const_iterator it = d.begin();it!=d.end();it++)
		{
			out << *it;
			if (it!=d.end()-1)
				out << ",";
		}
		out << "]";
		return out;
	}

	/** A template function for printing out the contents of a std::vector variable.
		*/
	template <class T>
	std::ostream& operator << (std::ostream& out, std::vector<T> *d)
	{
		out << "[";
		for (typename std::vector<T>::const_iterator it = d->begin();it!=d->end();it++)
		{
			out << *it;
			if (it!=d->end()-1)
				out << ",";
		}
		out << "]";
		return out;
	}

	/** Loads one row of a text file as a numerical std::vector.
	  * \return false on EOF or invalid format.
	  * The body of the function is implemented in MATH.cpp
		*/
	bool loadVector( CFileStream &f, std::vector<int> &d);

	/** Loads one row of a text file as a numerical std::vector.
	  * \return false on EOF or invalid format.
	  * The body of the function is implemented in MATH.cpp
		*/
	bool loadVector( CFileStream &f, std::vector<double> &d);


	/** A template function for the operator + between a scalar and a std::vector.
		*/
	template <class T>
	std::vector<T>  operator + (const std::vector<T> &a, T b)
	{
		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_res++)
			*it_res = *it_a + b;

		return res;
	}

	/** A template function for the operator - between a scalar and a std::vector.
		*/
	template <class T>
	std::vector<T>  operator - (const std::vector<T> &a, T b)
	{
		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_res++)
			*it_res = *it_a - b;

		return res;
	}

	/** A template function for the operator * between a scalar and a std::vector.
		*/
	template <class T>
	std::vector<T>  operator * (const std::vector<T> &a, T b)
	{
		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_res++)
			*it_res = *it_a * b;

		return res;
	}

	/** A template function for dividing a std::vector by a scalar number.
		*/
	template <class T>
	std::vector<T>  operator / (const std::vector<T> &a, T b)
	{
		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a;
		typename std::vector<T>::iterator		it_res;

		if (b==0)
			THROW_EXCEPTION("Division by zero: execution aborted!");

		for (it_a=a.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_res++)
			*it_res = *it_a / b;

		return res;
	}

	/** A template function for adding std::vector's having the same number of elements.
		*/
	template <class T>
	std::vector<T>  operator + (const std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a,it_b;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_b=b.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_b++, it_res++)
			*it_res = *it_a + *it_b;

		return res;
	}

	/** A template function for substracting std::vector's having the same number of elements.
		*/
	template <class T>
	std::vector<T>  operator - (const std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a,it_b;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_b=b.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_b++, it_res++)
			*it_res = *it_a - *it_b;

		return res;
	}

	/** A template function for scalar product (element by element, like .* in MATLAB) of std::vector's having the same number of elements.
		*/
	template <class T>
	std::vector<T>  operator * (const std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a,it_b;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_b=b.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_b++, it_res++)
			*it_res = (*it_a) * (*it_b);

		return res;
	}

	/** A template function for scalar division (element by element, like ./ in MATLAB) of std::vector's having the same number of elements.
		*/
	template <class T>
	std::vector<T>  operator / (const std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>	res(a.size());
		typename std::vector<T>::const_iterator	it_a,it_b;
		typename std::vector<T>::iterator		it_res;

		for (it_a=a.begin(), it_b=b.begin(), it_res=res.begin(); it_a!=a.end(); it_a++, it_b++, it_res++)
			*it_res = (*it_a) / (*it_b);

		return res;
	}

	/** A template for the operator += applied to std::vector's having the same number of elements.
		*/
	template <class T>
	void  operator += (std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>::iterator			it_a;
		typename std::vector<T>::const_iterator		it_b;

		for (it_a=a.begin(), it_b=b.begin(); it_a!=a.end(); it_a++, it_b++)
			*it_a += *it_b;
	}

	/** A template for the operator -= applied to std::vector's having the same number of elements.
		*/
	template <class T>
	void  operator -= (std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>::iterator			it_a;
		typename std::vector<T>::const_iterator		it_b;

		for (it_a=a.begin(), it_b=b.begin(); it_a!=a.end(); it_a++, it_b++)
			*it_a -= *it_b;
	}

	/** A template for the operator *= applied to std::vector's having the same number of elements.
		*/
	template <class T>
	void  operator *= (std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>::iterator			it_a;
		typename std::vector<T>::const_iterator		it_b;

		for (it_a=a.begin(), it_b=b.begin(); it_a!=a.end(); it_a++, it_b++)
			*it_a *= *it_b;
	}

	/** A template for the operator /= applied to std::vector's having the same number of elements.
		*/
	template <class T>
	void  operator /= (std::vector<T> &a, const std::vector<T> &b)
	{
		ASSERT_(a.size()==b.size());

		typename std::vector<T>::iterator			it_a;
		typename std::vector<T>::const_iterator		it_b;

		for (it_a=a.begin(), it_b=b.begin(); it_a!=a.end(); it_a++, it_b++)
		{
			if (*it_b==0)
				THROW_EXCEPTION("Division by zero: execution aborted!")
			*it_a /= *it_b;
		}
	}

	/** A template for the operator += applied to a std::vector and a scalar.
		*/
	template <class T>
	void  operator += (std::vector<T> &a, T b)
	{
		for (typename std::vector<T>::iterator	it=a.begin();it!=a.end();it++)  *it += b;
	}

	/** A template for the operator -= applied to a std::vector and a scalar.
		*/
	template <class T>
	void  operator -= (std::vector<T> &a, T b)
	{
		for (typename std::vector<T>::iterator	it=a.begin();it!=a.end();it++)  *it -= b;
	}

	/** A template for the operator *= applied to a std::vector and a scalar.
		*/
	template <class T>
	void  operator *= (std::vector<T> &a, T b)
	{
		for (typename std::vector<T>::iterator	it=a.begin();it!=a.end();it++)  *it *= b;
	}

	/** A template for the operator /= applied to a std::vector and a scalar.
		*/
	template <class T>
	void  operator /= (std::vector<T> &a, T b)
	{
		if (b==0)	THROW_EXCEPTION("Division by zero: execution aborted!")
		for (typename std::vector<T>::iterator	it=a.begin();it!=a.end();it++)  *it /= b;
	}

	/** A template for counting how many elements in an array are non-Zero.
		*/
	template <class T>
	size_t  countNonZero(const std::vector<T> &a)
	{
		typename std::vector<T>::const_iterator	it_a;
		size_t		count=0;
		for (it_a=a.begin(); it_a!=a.end(); it_a++) if (*it_a) count++;
		return count;
	}

} // end of namespace



#endif

