extern struct win *fore;
/*
 * BRLTTY - Access software for Unix for a blind person
 *          using a soft Braille terminal
 *
 * Version 0.22 BETA, 22 September 1995
 *
 * Copyright (C) 1995 by Nikhil Nair & James Bowden.  All rights reserved.
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU General Public License, as published by the Free Software
 * Foundation.  Please see the file COPYING for details.
 *
 * This software is maintained by Nikhil Nair <nn201@cam.ac.uk>.
 */

/* scr.c - The screen reading library
 * N. Nair, 21 July 1995
 */

#define SCR_C 1
#define TOGGLE_OFF                5000

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <syslog.h>
#include "scr.h"

#if defined (__XABT) || defined (__XSCREADER)
   char VCS_FILE[50];
#endif

scrstat scr;
int scr_fd;

int my_initscr ()
{
  scr_fd = open (VCS_FILE, O_RDONLY);	/* open vcsa device for read-only */
  if (scr_fd == -1)
    return 1;
  return 0;
}

scrstat getstat ()
{
  unsigned char buffer[4];
  static scrstat stat;

  lseek (scr_fd, 0, SEEK_SET);	/* go to start of file */
  read (scr_fd, buffer, 4);		/* get screen status bytes */
  stat.rows = buffer[0];
  stat.cols = buffer[1];
  stat.posx = buffer[2];
  stat.posy = buffer[3];
  return stat;
}

char *getscr (int left, int top, int width, int height, char *buffer, int mode)
{
  scrstat stat;			/* screen statistics */
  off_t start;			/* start offset */
  size_t linelen;		/* number of bytes to read for one */
				/* complete line */
  char linebuf[512];		/* line buffer; larger than is needed */
  int i, j;			/* loop counters */

  stat = getstat ();
  if (left < 0 || top < 0 || width < 1 || height < 1 \
      || mode < 0 || mode > 1 || left + width > stat.cols \
      || top + height > stat.rows)
    return NULL;
#ifdef __XABT
#  define X 1
#else
#  define X 2
#endif
  start = 4 + (top * stat.cols + left) * X + mode;
  linelen = X * width - 1;
  for (i = 0; i < height; i++)
    {
      lseek (scr_fd, start + i * stat.cols * X, SEEK_SET);
      read (scr_fd, linebuf, linelen);
      for (j = 1; j < width; linebuf[j++] = linebuf[j * X]);
      memcpy (buffer + i * width, linebuf, width);
    }
  return buffer;
}

/****************************************************************\
* getscrinfo - Gets info on size of screen and cursor possition. *
\****************************************************************/

void getscrinfo ()
{
	if (my_initscr ())
	{
#if defined __JABT || defined __XABT
		play_sample ("screen_error.au", TOGGLE_OFF);
		wait (NULL);
#endif
		syslog (LOG_USER | LOG_ERR, "%s: Can't initialise screen reading: %s", VCS_FILE, strerror (errno));
		exit (1);
	} /* if */
	scr = getstat ();	/* get rows, cols, cursorpos */
} /* getscrinfo */

