#ifndef MODULE
#define MODULE
#endif
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/errno.h>
#include <linux/cons.h>

#include <rtl_sched.h>
#include <rtl_fifo.h>
#include "control.h"

RT_TASK tasks[2];

static char *data[] = {"Frank ", "Zappa "};

/* t -- the fifo number */
void fun(int t) {
	while (1) {
/* 		conpr(t - 1 ? "0" : "1"); */
		rtf_put(t, data[t - 1], 6);
		rt_task_wait();
	}
}


int my_handler(unsigned int fifo)
{
	struct my_msg_struct msg;
	int err;
	RTIME now;

//	conpr("h");
	while ((err = rtf_get(3, &msg, sizeof(msg))) == sizeof(msg)) {
		switch (msg.command) {
			case START_TASK:
				now = rt_get_time();
				rt_task_make_periodic(&tasks[msg.task], now, msg.period);
				break;
			case STOP_TASK:
				rt_task_suspend(&tasks[msg.task]);
				break;
			default:
				return -EINVAL;
		}
	}
	if (err != 0) {
		return -EINVAL;
	}
	return 0;
}


#define DEBUG 
int init_module(void)
{
	int c[3];
	rtf_destroy(1);
	rtf_destroy(2);
	rtf_destroy(3);
 	c[0] = rtf_create(1, 4000);
	c[1] = rtf_create(2, 4000);
	c[2] = rtf_create(3, 100);		/* input control channel */
	printk("Fifo return 1=%d 2=%d 3=%d\n",c[0],c[1],c[2]);
	rt_task_init(&tasks[0], fun, 1, 3000, 4);
	rt_task_init(&tasks[1], fun, 2, 3000, 5);
	rtf_create_handler(3, &my_handler); 
	return 0;
}


void cleanup_module(void)
{
#ifdef DEBUG
	printk("%d\n", rtf_destroy(1));
	printk("%d\n", rtf_destroy(2));
	printk("%d\n", rtf_destroy(3));
#else 
	rtf_destroy(1);
	rtf_destroy(2);
	rtf_destroy(3);
#endif
	rt_task_delete(&tasks[0]);
	rt_task_delete(&tasks[1]);
}
