#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include "lindaapi.h"

#define PORT 10000

#define SERIAL_REGIST_TUPLE_NO 1

void
mainLoop(int tid, int write_id, int fd)
{
	void *addr;
	struct stat sb;

	if (fstat(fd, &sb) == -1) {
		perror("fstat");
		exit(1);
	}
	addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
	if (addr==NULL) {
		perror("mmap");
		exit(1);
	}

	printf("file size=%lld\n", sb.st_size);

	psx_out(tid, write_id, (unsigned char *)addr, sb.st_size);
	psx_sync_n();

	return;
}

int get_serial_id(int tid) {
	char *data;
	int serial;
	int seq;

	seq = psx_in(tid, 65535);
	do {
	    psx_sync_n();
	    data = (char *)psx_reply(seq);
	} while(data==0);
	serial = atoi(data + LINDA_HEADER_SIZE);
	psx_free(data);

	return serial;
}

void send_serial_id(int tid, int serial_id) {
	int safe_id = htonl(serial_id);

	psx_out(tid, SERIAL_REGIST_TUPLE_NO, (unsigned char *)&safe_id, sizeof(safe_id));
	psx_sync_n();
}

int
main(int argc, char *argv[]) {
	int tspace;
	int serial;
	int xml_id;
	char *linda_serv = (char *)"localhost";
	if (argc > 1)
		linda_serv = argv[1];
	init_linda();
	tspace = open_linda_java(linda_serv, PORT);
	printf("open socket (tupple space id) = %d\n", tspace);
	serial = get_serial_id(tspace);
	xml_id = serial * 10;
	mainLoop(tspace, xml_id, fileno(stdin));
	sleep(1);
	send_serial_id(tspace, serial);
	printf("send xml_id = %d, seciral = %d\n",xml_id, serial);
	exit(EXIT_SUCCESS);
}

/* end */
