/*\file PrintfFunction.c
 *\brief: this function is used by the _printf_ macro, to take into account the 
 *fact we may be running on a cluster. 
 */

#include <stdarg.h>
#include <stdio.h>
#include "../shared/shared.h"
#include "../include/include.h"

int PrintfFunction(const char* format,...){
	/*http://linux.die.net/man/3/vsnprintf*/

	/*string to be printed: */
	char *buffer = NULL;
	int   n,size = 100;
	int   my_rank;
	//variable list of arguments
	va_list args;

	/*recover my_rank:*/
	my_rank=IssmComm::GetRank();

	while(true){

		/*allocate buffer for given string size*/
		buffer=xNew<char>(size);

		/* Try to print in the allocated space. */
		va_start(args, format);
		n=vsnprintf(buffer,size,format,args);
		va_end(args);

		/* If that worked, return the string. */
		if(n>-1 && n<size) break;

		/* Else try again with more space. */
		if(n>-1)   /* glibc 2.1 */
		 size=n+1; /* precisely what is needed */
		else       /* glibc 2.0 */
		 size*=2;  /* twice the old size */

		xDelete<char>(buffer);
	}

	/*Ok, if we are running in parallel, get node 0 to print*/
	if(my_rank==0)_printString_(buffer);

	/*Clean up and return*/
	xDelete<char>(buffer);
	return 1;
}
int PrintfFunction(const string & message){
	int  my_rank;

	/*recover my_rank:*/
	my_rank=IssmComm::GetRank();

	if(my_rank==0){
		printf("%s\n",message.c_str());
	}
	return 1;
}
int PrintfFunction2(const string & message){
	int  my_rank;

	/*recover my_rank:*/
	my_rank=IssmComm::GetRank();

	if(my_rank==0){
		printf("%s",message.c_str());
	}
	return 1;
}
