/* Copyright 1998  by David Austin */

/* userspace version hacked by tridge@linuxcare.com  November 2000 */

/* includes */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <getopt.h>
#include <sys/io.h>
#include "scrolly.h"

/* defines */

#define LPT 0x378 /* the address of the parallel port */
#define bash_port(data)   outb(~((char) (data)), LPT)

/* parts of the parallel port we use */

#define SRCLK 0x01
#define LOAD  0x02
#define SRDTA 0x04
#define RESET 0x08

static int opt_repeats=20;

void output_row(unsigned char *rp) 
{
	static int row_count = 0; /* the number of the next row to be output */
	int i;
	u8 mask;
  
	mask = 0x80 >> row_count;

	for (i = ROW_LENGTH - 1; i >= 0; i--) {
		if (rp[i] & mask)  { /* clock a 1 through */
			bash_port(SRDTA);
			bash_port(SRDTA + SRCLK);
		} else { /* clock a 0 through*/
			bash_port(0x00);
			bash_port(SRCLK);
		}
	}

	/* If we just sent the first row then do a reset+load */
	if (row_count == 0) {
		bash_port(RESET);
		bash_port(RESET + LOAD);
		bash_port(0x00);
	} else {    
		bash_port(LOAD);
		bash_port(0x00);
	}

	row_count = (row_count+1) % NUM_ROWS;
}

static void output_rows(u8 *row)
{
	int j=8;
	while (j--) {
		output_row(row);
		sched_yield();
	}
}

void display_msg(char *str)
{
	u8 screen[ROW_LENGTH*10];
	int w, i=0, j;

	memset(screen, 0, sizeof(screen));
	w = fill_string(screen, str);
	for (i=w; i<sizeof(screen); i+=w) {
		int len = w;
		if (len > sizeof(screen)-i) len = sizeof(screen)-i;
		memcpy(screen+i, screen, len);
	}

	/* Start the refresh */
	for (i=0; 1; i = (i+1) % w) {
		for (j=0; j<opt_repeats; j++) output_rows(screen+i);
	}
}

enum {OPT_HELP, OPT_REPEATS};

static struct option long_options[] = {
  {"repeats",     1,     0,    OPT_REPEATS},
  {0,0,0,0}};

static void usage(void)
{
	printf("scrolly [options] <string>\n");
}

int main(int argc, char *argv[])
{
	int opt;

	while ((opt = getopt_long(argc, argv, 
				  "", long_options, NULL)) 
	       != -1) {
		switch (opt) {
		case OPT_REPEATS: 
			opt_repeats = strtol(optarg, NULL, 0); 
			break;
		}
	}

	iopl(3);
	outb(0x80, (LPT + 3)); /* set all pins as outputs */

	argv += optind;
	argc -= optind;

	if (argc < 1) {
		usage();
		exit(1);
	}

	display_msg(argv[0]);

	return 0;
}

