/* Example of interrupt handle LinCon8k slot.

   Author: Moki Matsushima

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */

/* File level history (record changes for this file here.)

   v 0.0.0  1 Sep 2013 by Moki Matsushima
     create, blah blah... */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>
#include "msw.h"

#define MYSLOT SLOT4
//#define MYSLOT SLOT2

static unsigned sig_counter;

void sig_handler(int sig)
{
	printf("\rGot single %d for %u times", sig, ++sig_counter);
}

int main()
{
	slot_signal_t sig;

	static struct sigaction act, act_old;

	/* open device file */
	if(Open_Slot(MYSLOT)){
		printf("open Slot %d failed!\n",MYSLOT);
		return FAILURE;
	}
	if(Open_Slot(SLOT9)){
		printf("open Slot %d failed!\n",SLOT9);
		return FAILURE;
	}

	/* set action for signal */
	act.sa_handler = sig_handler;
	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask, SIGALRM);
	if (sigaction(SIGALRM, &act, &act_old)) {
		puts("Failure of signal action.");
		return FAILURE;
	}

	/* signal condiction */
	if(setSignal(MYSLOT,SIGALRM,getpid())){
		Close_Slot(MYSLOT);
		sigaction(SIGALRM, &act_old, NULL);
		puts("Failure of signal condiction.");
		return FAILURE;
	}

	if(MYSLOT == SLOT10)
	{
		//printf("ENABLE Timeout INT\n");
		outb( 9, 17, 10);
		outb( 9, 19, 10);
		outb( 9, 16, 10);
		outb( 9, 18, 10);

	}
	else
	{
		printf("ENABLE SLOT%d INT\n",MYSLOT);
	}



	int irqa, irqb, v9003a, v9003b;

	/* wait for exit */
	//puts("press <Enter> to exit\n");
	//while (getchar() != 10);
	while(1)
	{
		if(MYSLOT != SLOT10)
		{
			outb(MYSLOT, 1, 2);
        		inb(9, 9);
	        	outb(MYSLOT, 1, 0);
	        	inb(9, 9);
			usleep(500);
		}

		if(sig_counter >= 500)	//break when get 500 signal.
			break;
	}

	if(MYSLOT == SLOT10)
	{
		//printf("DISABLE Timeout INT\n");
		outb( 9, 17, 0);
		outb( 9, 19, 0);
		outb( 9, 16, 0);
		outb( 9, 18, 0);
		outb( 9, 34, 0);
	}

	Close_Slot(MYSLOT);
	Close_Slot(SLOT9);
	sigaction(SIGALRM, &act_old, NULL);
	puts("\nEnd of program.");
	return sig_counter % 500;
}
