#include <MPI.h>

// create the channel ID
int setupMPI()
{
    int chid; // the channel ID
	chid = ChannelCreate(0);
	return(chid);
}


void writeData(int *buffer, unsigned int number_of_words)
{
	unsigned int itr = 0;

	for(itr = 0; itr < number_of_words; itr++)
	{
		buffer[itr] = itr;
	}

}

void sendDataSender(pid_t parent_pid, int chid, int *send_msg, unsigned int number_of_words)
{
	int coid; // create connection id
	coid = ConnectAttach (0, parent_pid, chid, 0, 0);

	unsigned int number_of_bytes = number_of_words * sizeof(int);

	// after sending the data client waits for server's response if send_staus = 0
	// then message has be recevied
	int send_status;

	// for storing the response from the receiver
	char response_buffer[300];

	if (coid == -1)
	{
		fprintf (stderr, "Couldn't ConnectAttach to 0/%X/%d!\n",parent_pid, chid);
		perror (NULL);
		exit (EXIT_FAILURE);
	}

	send_status = MsgSend (coid, send_msg, number_of_bytes, response_buffer, sizeof(response_buffer));

	if (send_status == -1)
	{
		fprintf (stderr, "Error during MsgSend\n");
		perror (NULL);
		exit (EXIT_FAILURE);
	}

	if (strlen (response_buffer) > 0)
	{
		printf ("Receiver: \"%s\"\n", response_buffer);
	}
}


void receiveDataReceiever(int chid, int *receive_buffer, unsigned int number_of_words)
{
	int recid;
	char reply_buff[300];
	unsigned int number_of_bytes = number_of_words * sizeof(int);
	recid = MsgReceive(chid, receive_buffer, number_of_bytes, NULL);
	printf("Got a message with id %X\n", recid);
	strcpy(reply_buff, "Received");
	MsgReply(recid,EOK, reply_buff, sizeof(reply_buff));

}

