#include <sys/types.h>
#include <fcntl.h>

#ifdef LINUX
#include <linux/socket.h>
#else
#include <socket.h>
#endif
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <sys/time.h>
#ifdef LYNXOS
#include <bsd/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#endif
#ifdef vmpc
#include  <cetiatimer.h>
#endif //vmpc

#define PORT 12345

main(int argc, char **argv)
{
	int listenfd, connfd;
	int cliLen;
	struct sockaddr_in cliAddr, servAddr;
	pid_t child_pid;
	int port;
	if(argc == 2)
	  port = (u_short)atoi(argv[1]); 
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servAddr, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	if(argc < 2)
	  port = PORT;
	servAddr.sin_port=htons(port);
	
	bind(listenfd, (struct sockaddr *)&servAddr, sizeof(servAddr));
	
	listen(listenfd,5); //5 possible queued connections
	for(;;)
	{
		cliLen=sizeof(cliAddr);
		connfd=accept( listenfd, (struct sockaddr *)&cliAddr, &cliLen);
		if( (child_pid=fork()) == 0)
		{
			close(listenfd);
			//process the request
			procreq(connfd);
			exit(0);
		}
		close(connfd);
	}
}


int procreq(int sockfd)
{
	int i,n, fd;
	char line[4096];
	char end=0xe;
#ifdef vmpc
    FILE *fdt;
    struct itimerval interval;
    if ((fd=open("/dev/tim0",O_RDWR)) < 0) {
           printf("Open failed0\n");
            return;
    }
  interval.it_value.tv_sec = 0;
  interval.it_value.tv_usec = 250;
  interval.it_interval.tv_sec = 0;
  interval.it_interval.tv_usec = 250;

  ioctl(fd,TIMER_INIT,&interval); 
#endif 
	for(;;)
	{
	  	if( (n = recv (sockfd, &line, 4096, 0)) ==0)
		{
		  printf("connection closed by other end\n");
		  return 0;
		  }
	      write(sockfd, &end, 1);
	      //for (i=0; i<n; i++)printf("%01x ", line[i]);
		fflush(stdout);
	      printf ("received %d chars \n", n);
#ifdef vmpc
       ioctl(fd,TIMER_WAIT);
//       fprintf(fdt, "%lu %lu\n", end.tv_sec, end.tv_usec); fprintf(fdt, "%lu %lu\n", end.tv_sec, end.tv_usec);
#endif   		
	}
	return (n);
#ifdef vmpc  
  close(fd);
//  fclose(fdt);
#endif
}






