/*
 * Atari Joystick Driver for Linux
 * by Robert de Vries (robert@and.nl) 19Jul93
 */

#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/atarikb.h>
#include <linux/atari_joystick.h>
#include <asm/segment.h>

static struct joystick_status joystick[2];

void joystick_interrupt(char *buf)
{
    int j;
/*    ikbd_joystick_disable(); */

    j = buf[0] & 0x1;
    joystick[j].dir   = buf[1] & 0xF;
    joystick[j].fire  = (buf[1] & 0x80) >> 7;
    joystick[j].ready = 1;
    wake_up_interruptible(&joystick[j].wait);

/*    ikbd_joystick_event_on(); */
}

static void release_joystick(struct inode *inode, struct file *file)
{
    int minor = MINOR(inode->i_rdev);

    joystick[minor].active = 0;
    joystick[minor].ready = 0;

    if ((joystick[0].active == 0) && (joystick[1].active == 0))
	ikbd_joystick_disable();
}

static int open_joystick(struct inode *inode, struct file *file)
{
    int minor = MINOR(inode->i_rdev);

    if (minor > 1)
	return -ENODEV;
    if (joystick[minor].active)
	return -EBUSY;
    joystick[minor].active = 1;
    joystick[minor].ready = 0;
    ikbd_joystick_event_on();
    return 0;
}

static int write_joystick(struct inode *inode, struct file *file, char *buffer, int count)
{
    return -EINVAL;
}

static int read_joystick(struct inode *inode, struct file *file, char *buffer, int count)
{
    int minor = MINOR(inode->i_rdev);
    int i;

    if (count < 2)
	return -EINVAL;
    if (!joystick[minor].ready)
	return -EAGAIN;
    put_fs_byte(joystick[minor].fire, buffer++);
    put_fs_byte(joystick[minor].dir, buffer++);
    for (i = 0; i < count; i++)
	put_fs_byte(0, buffer++);
    joystick[minor].ready = 0;

    return i;
}

static int joystick_select(struct inode *inode, struct file *file, int sel_type, select_table *wait)
{
    int minor = MINOR(inode->i_rdev);

    if (sel_type != SEL_IN)
	return 0;
    if (joystick[minor].ready)
	return 1;
    select_wait(&joystick[minor].wait, wait);
    return 0;
}

struct file_operations joystick_fops = {
	NULL,		/* joystick_seek */
	read_joystick,
	write_joystick,
	NULL,		/* joystick_readdir */
	joystick_select,
	NULL,		/* joystick_ioctl */
	NULL,		/* joystick_mmap */
	open_joystick,
	release_joystick
};

unsigned long joystick_init(unsigned long kmem_start)
{
    joystick[0].active = joystick[1].active = 0;
    joystick[0].ready = joystick[1].ready = 0;
    joystick[0].wait = joystick[1].wait = NULL;

    if (register_chrdev(11, "joystick", &joystick_fops))
	printk("unable to get major 11 for joystick devices\n");
    printk("Atari joystick driver installed.\n");

    return kmem_start;
}
