/*!\file: DakotaMPI_Bcast
 * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
 * from cpu 0 to all other cpus.
 */ 

#ifdef HAVE_CONFIG_H
	#include <config.h>
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

#include "./Dakotax.h"

void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){

	int i;
	extern int my_rank;

	/*inputs and outputs: */
	double* variables=NULL;
	char**  variables_descriptors=NULL;
	int     numvariables;
	int     numresponses;

	/*intermediary: */
	char* string=NULL;
	int   string_length;


	/*recover inputs from pointers: */
	variables=*pvariables;
	variables_descriptors=*pvariables_descriptors;
	numvariables=*pnumvariables;
	numresponses=*pnumresponses;

	/*numvariables: */
	MPI_Bcast(&numvariables,1,MPI_INT,0,MPI_COMM_WORLD); 
	
	/*variables:*/
	if(my_rank!=0)variables=xNew<double>(numvariables);
	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,MPI_COMM_WORLD); 

	/*variables_descriptors: */
	if(my_rank!=0){
		variables_descriptors=xNew<char*>(numvariables);
	}
	for(i=0;i<numvariables;i++){
		if(my_rank==0){
			string=variables_descriptors[i];
			string_length=(strlen(string)+1)*sizeof(char);
		}
		MPI_Bcast(&string_length,1,MPI_INT,0,MPI_COMM_WORLD); 
		if(my_rank!=0)string=xNew<char>(string_length);
		MPI_Bcast(string,string_length,MPI_CHAR,0,MPI_COMM_WORLD); 
		if(my_rank!=0)variables_descriptors[i]=string;
	}

	/*numresponses: */
	MPI_Bcast(&numresponses,1,MPI_INT,0,MPI_COMM_WORLD); 

	/*Assign output pointers:*/
	*pnumvariables=numvariables;
	*pvariables=variables;
	*pvariables_descriptors=variables_descriptors;
	*pnumresponses=numresponses;
}
