/*
 * Author:
 *         Kendy Kutzner <kutzner@ira.uka.de>
 *
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * $Id: testclient.cc,v 1.14 2005/11/21 10:46:57 kutzner Exp $
 *
 */

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "libigor.h"

#define TESTMSGLEN 10

// global socket
int s;


void topen(){
	s = igor_socket();
	printf("socket(%i): %s\n", s, igor_strerror(s));
}

void tbind(){
	struct igor_apptype at;
	at.apptype = "foo";
	at.len = strlen(at.apptype);
	at.mustbehashed = 1;
	int bindres = igor_bind(s, &at);
	printf("bind(%i): %s\n", bindres, igor_strerror(s));
}

void tsend(){
	struct sa_igor sa;
	sa.address = "bar";
	sa.len = strlen(sa.address);
	sa.mustbehashed = 1;
	void * msg;
	msg = malloc(TESTMSGLEN);
	memset(msg, 'x', TESTMSGLEN-1);
	((char*)msg)[TESTMSGLEN-1] = '\0';
	int sendtores = igor_sendto(s, msg, strlen((char*)msg)+1/*include trailing null*/, 1, &sa);
	printf("sendto(%i): %s\n", sendtores, igor_strerror(s));
}

void trecv(){
	size_t len;
	bool upcall;
	struct sa_igor src;
	struct sa_igor dst;
	src.len=0;
	dst.len=0;
	void * msg = NULL;
	int recvres = igor_recvfromto(s, &msg, &len, &upcall, &dst, &src);
	printf("recv(%i): %s\n", recvres, igor_strerror(s));
	printf("the received msg has len %i and says '%%s'\n", len/*, (char*)msg*/);
}

void tclose(){
	int closeres = igor_close(s);
	printf("close(%i): %s\n", closeres, igor_strerror(s));
}

int main(int argc, char * argv[]){
	switch (argc){
		case 1:
			topen();
			tbind();
			tsend();
			trecv();
			tclose();
			return 0;
		case 2:
			switch (*(argv[1])){
				case 'S':
					topen();
					tbind();
					while (true){
						tsend();
					}
				case 'R':
					topen();
					tbind();
					while (true){
						trecv();
					}
			}
	}
}
