/*
** termsbr.c -- termcap support
**
** This code is Copyright (c) 2002, by the authors of nmh.  See the
** COPYRIGHT file in the root directory of the nmh distribution for
** complete copyright information.
*/

#include <h/mh.h>

#include <termios.h>

#ifdef HAVE_TERMCAP_H
# include <termcap.h>
#endif

/* <sys/ioctl.h> is need anyway for ioctl()
#ifdef GWINSZ_IN_SYS_IOCTL
*/
# include <sys/ioctl.h>
/*
#endif
*/

#ifdef WINSIZE_IN_PTEM
# include <sys/stream.h>
# include <sys/ptem.h>
#endif

#if BUFSIZ<2048
# define TXTSIZ 2048
#else
# define TXTSIZ BUFSIZ
#endif

static long speedcode;

static int initCO = 0;

static int CO = 80;      /* number of colums */


static void
read_termcap(void)
{
	char *term;

#ifndef TGETENT_ACCEPTS_NULL
	char termbuf[TXTSIZ];
#endif

	struct termios tio;
	static int inited = 0;

	if (inited++)
		return;

	if (!(term = getenv("TERM")))
		return;

/*
** If possible, we let tgetent allocate its own termcap buffer
*/
#ifdef TGETENT_ACCEPTS_NULL
	if (tgetent(NULL, term) != TGETENT_SUCCESS)
		return;
#else
	if (tgetent(termbuf, term) != TGETENT_SUCCESS)
		return;
#endif

	speedcode = cfgetospeed(&tio);

	if (!initCO && (CO = tgetnum("co")) <= 0)
		CO = 80;
}


int
sc_width(void)
{
#ifdef TIOCGWINSZ
	struct winsize win;
	int width;

	if (ioctl(fileno(stderr), TIOCGWINSZ, &win) != NOTOK
			&& (width = win.ws_col) > 0) {
		CO = width;
		initCO++;
	} else
#endif /* TIOCGWINSZ */
		read_termcap();

	return CO;
}
