 /*
 * test.c
 *
 *  Created on: Apr 24, 2012
 *      Author: xw795
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>


#define SIZE 3			// message size

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
	int fd_in, fd;
	int sock;
	int bind_server, sock_option;
	int boolval = 1;
	char code[SIZE];
	socklen_t fromlen;
	struct sockaddr_in server;
	struct sockaddr_in addr;
	int flag=0;
	unsigned long *ptr;
	unsigned long *VIC2SoftInt;

	if(argc < 2)
	{
		fprintf(stderr, "Error, no port provided\n");
		exit(0);
	}

	fd_in= open("/dev/rtf/1", O_RDWR);
	fd = open("/dev/mem", O_RDWR);
	ptr = mmap(NULL,getpagesize(),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0x800C0000);

	VIC2SoftInt = ptr + 0x06;

	sock = socket(AF_INET, SOCK_DGRAM, 0);   // create socket
	if(sock < 0)
	{
		error("Opening socket");
	}

	bzero(&server, sizeof(server));
	server.sin_family = AF_INET;    // setting
	server.sin_addr.s_addr = INADDR_ANY;

	server.sin_port = htons(atoi(argv[1]));    // convert the port number

	bind_server = bind(sock, (struct sockaddr *)&server, sizeof(server));  // bind the socket to this IP

	if(bind_server < 0)
	{
		error("binding");
	}

	sock_option = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &boolval, sizeof(boolval));  // setting of socket
	if(sock_option < 0)
	{
		printf("error setting socket options\n");
		exit(-1);
	}

	fromlen = sizeof(struct sockaddr_in);

	while(1)
	{
		if(flag==0)
		{	
			recvfrom(sock, code, strlen(code), 0,(struct sockaddr *)&addr, &fromlen);
			write(fd_in,code,sizeof(code));
			*VIC2SoftInt = *VIC2SoftInt | 0x80000000;
			flag=1;
		}
		if(flag==1)
		{
			printf("code = %c%c%c\n",code[0],code[1],code[2]);
			write(fd_in,code,sizeof(code));	
			*VIC2SoftInt = *VIC2SoftInt | 0x80000000;			
			if(strncmp(code,"ABC",3)==0)
			{
				
				printf("Password is correct.\n");
				exit(0);
			}
			else
			{
				printf("Password is wrong.\n");
				exit(0);
			}
			bzero(code,SIZE);

		}
	}
	return 0;
}