/*\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"

#include "mex.h"

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

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

	while(true){

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

		/* Try to print in the allocated space. */
		va_start(args, format);
#ifndef WIN32
		n=vsnprintf(buffer,size,format,args);
#else
		n=vsnprintf(buffer,size,format,args);
#endif
		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;
}
