
/*
   ParallelFetchString.c
 */

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

#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)

#include "stdio.h"
#include "../shared/shared.h"

#undef __FUNCT__
#define __FUNCT__ "ParallelFetchString"

void ParallelFetchString(char** pstring,FILE* fid){

	/*output: */
	char* string=NULL;
	int   string_size;
	extern int my_rank;
	extern int num_procs;

	/*We have to read a string from disk. First read the dimensions of the string, then the string: */
	if(my_rank==0){  
		if(fread(&string_size,sizeof(int),1,fid)!=1)throw ErrorException(__FUNCT__," could not read length of string ");
	}

	MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 

	/*Now allocate string: */
	if(string_size){
		string=(char*)xmalloc((string_size+1)*sizeof(char));
		string[string_size]='\0';

		/*Read string on node 0, then broadcast: */
		if(my_rank==0){  
			if(fread(string,string_size*sizeof(char),1,fid)!=1)throw ErrorException(__FUNCT__,"  could not read string ");
		}
		MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
	}
	else{
		string=(char*)xmalloc(sizeof(char));
		string[0]='\0';
	}


	/*Assign output pointers: */
	*pstring=string;
}
#endif //#if defined(_PARALLEL_) && defined(_HAVE_PETSC_)
