#include <linux/module.h>
#include <linux/kernel.h>
#include <rtl_fifo.h>
#include <linux/rtl.h>
#include <asm/rt_irq.h>
#include <asm/rt_time.h>
#include <rtl_sched.h>
#include <asm/io.h>
#include <linux/cons.h>
#include "common.h"

#define TIMEOUT 100000
#define SKIP 1000
#define PERIOD 500

RT_TASK mytask;
RTIME min_response;
RTIME max_response;
struct sample samp;
int skip;

void fun(int t) {
	register int i;
	register int orig;
	int flags;

	RTIME before, after, response;
	while (1) {
		for (skip = 0; skip < SKIP; skip++) {

			r_save_flags(flags);
			r_cli();

			outb_p(0, LPT_PORT);
			orig = inb_p(LPT_PORT + 1);
			
			outb(0xff, LPT_PORT);
			before = rt_get_time();

			i = 0;
			while ((inb(LPT_PORT + 1) == orig) && ++i < TIMEOUT);
/* 			while ((inb(LPT_PORT + 1) == orig) && rt_get_time() < before + TIMEOUT); */
			after = rt_get_time();
			
			if (i >= TIMEOUT) {
				rtl_printf("timeout!!!\n");
				r_restore_flags(flags);
				rt_task_wait();
				return;
			}

			response = after - before;
			if (response < min_response) {
				min_response = response;
			}
			if (response > max_response) {
				max_response = response;
			}

			r_restore_flags(flags);

			rt_task_wait();
		}
		samp.min = min_response;
		samp.max = max_response;
		rtf_put(0, &samp, sizeof(samp));
	}
}


int init_module(void)
{
	RTIME now = rt_get_time();
	min_response = 1000000000;
	max_response = 0;

	rtf_create(0, 4000);

	rt_task_init(&mytask, fun, 1, 3000, 4);
	rt_task_make_periodic(&mytask, now + 3000, PERIOD);

	return 0;
}

void cleanup_module(void)
{
	rt_task_delete(&mytask);
	
	rtf_destroy(0);

}

