/* @(#)termcap.c	19.1 (ES0-DMD) 02/25/03 13:58:13 */
/*===========================================================================
  Copyright (C) 1995 European Southern Observatory (ESO)
 
  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetss Ave, Cambridge, 
  MA 02139, USA.
 
  Corresponding concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++

.TYPE		Module
.IDENTIFICATION termcap.c
.AUTHOR    	Francois Ochsenbein [ESO-IPG]
.LANGUAGE  	C
.KEYWORDS	Termcap
.ENVIRONMENT	TermWindows
.VERSION   1.0	01-Jul-1986:	Creation
.VERSION   2.0	10-Jun-1987:
		For version '2', only functions required to CREATE the
		TERMCAP Area are here.
		The characters may be 8 bits.
.VERSION  2.2	23-Jun-1987: Adapted UNIX
.VERSION  2.3	23-Nov-1987: Removed Bug which occured in tu_x1,
		and caused crashes for some terminals (due to reallocation
		of memory)
.VERSION  3.0	15-May-1988: Version '3'. Use stritem function to locate
		the device name in the list.
.VERSION  3.1 	28-Mar-1989: Removed bug in stritem (if 2nd string is of length 0)
.VERSION  3.2	09-May-1989: Modified f_gets to eliminate bad messages in
		case of unknown terminal.
.VERSION  3.3	14-Jul-1989: Modified error logging in tu_load.
.VERSION  3.4	24-Aug-1989: Don't modify term structure when terminal not
		found (may be looked in a new file)

.COMMENTS	The main program loads the TermCapFile into a binary
		structure in SYS$LOGIN.

		This module provides tools to read the TERMCAP file and to 
		prepare a TERM structure (defined in TERMINAL.H) which 
		receives the TermCapabilities in a form usable by ZT Libraries.
		For usage in TermWindows, this module is NOT required
		if it is assumed that a binary copy of the TERM already exists.

\begin{TeX}

\bigskip
\bigskip

{\bf Description of TERMCAPS}


          TERMCAP is the file EMACS uses to acquire the  terminal  specific
     commands  and escape sequences for updating the display.  This file is
     an ASCII text file that can be modified with any text editor.

          The TERMCAP method of updating a display was developed by William
     Joy  at  the  University of California at Berkeley for UNIX
     \footnote{UNIX is a trademark of Bell Laboratories}
     It is
     employed by many UNIX programs, some of which  run  on  VMS.   Because
     EMACS  uses  a  nearly identical method of reading the TERMCAP file as
     other programs, the same TERMCAP file can be  shared  between  several
     screen manipulation programs.

          The TERMCAP file contains a series of entries that  describe  the
     capabilities  of  various terminals.  Each entry is composed of fields
     separated by colons (`:').  There can be several lines per  entry  (by
     placing  a  `\b'  at  the end of each line, except the last line of the
     entry).

          The first field is the name of the terminal to which the  ensuing
     fields  apply.   This  field  can  specify  several  synonyms  for the
     terminal;  the synonyms are separated by  vertical  bars  (`$|$').   The
     field, as with all fields, are terminated by a colon.  Note that EMACS
     distinguishes between upper and lower case alphabetics in  this  field
     (and  in  all  fields;   hence  the  reason  for quotes on the DEFINE
     EMACS\_TERM command.)

          The remainder of the fields are specified  as  two  letter  field
     names.  These may be followed by a field value.  For instance:

\begin{quote}
               {\tt up=\b Eu:}\\
		{\tt li\#24:}\\
               {\tt ul:}
\end{quote}

     are all valid fields.   The field name can be separated from the field
     value  by either a `=' (the equal-sign designates a string), or `\#'
     (the sharp designates a number), or a `:' (the column designates
	a booloean value).
{\em Note added by Fran\c cois Ochsenbein:}
	The `@' instead of `=' or `\#' means that 
{\em the capability does not exist.}

          The two letter field names that EMACS uses are described  in  the
     following  table.  Note that some TERMCAP entries may have more (which
     are ignore by EMACS). 

{\em Note added by Fran\c cois Ochsenbein:}
All capabilities are not described here; the
usage of various other capabilities are explained in each 
module making use of TERMCAP.\\
Let's just mention here {\tt V}$x$ for video attributes,
{\tt G}$x$ for graphic characters, 
{\tt F}$x$ for function keys, 
{\tt k}$x$ for keypad keys, 
and {\tt K}$x$ for special keys.


$$\begin{tabular}{|llp{33em}|} \hline
 Field          &Padding   &Meaning \\
	\hline
{\tt al=}  	&P*   	&Adds a new line to the  screen,  pushing
                                   lines below it down.\\
{\tt am}  	&   	&Boolean value (automatic margin, \ie 
                           cursor wraps from right margin to next line).\\
{\tt    bc=}	&	&Moves   the   cursor   left   (typically
                                   backspace or \^{ }H).\\
{\tt    cb= }	&P 	&Erase text from the left margin to the cursor.\\
{\tt    cd=}	&P	&Erases  text  from  the  cursor  to  the
                                   end of the display.\\
{\tt    ce=}	&P 	&Erases  text  from  the  cursor  to  the
                                   rightmost column in the display.\\
 {\tt   cl=}	&P* 	&Erases all text  on  all  lines  on  the
                                   display.\\
 {\tt   cm=}	&P   	&Moves the cursor;  see below.\\
 {\tt   co\#}	& 	&Specifies  the  number  of  columns  per
                                   line.\\
 {\tt   cs= }	&P 	&Defines a scrolling region.\\
 {\tt   cu= }	&P 	&Erase text from the top of the display to the cursor.\\
 {\tt   dc= }	&P* 	&Deletes the  current  character,  moving
                                   all  characters  at  the  right  of  the
                                   deleted character left by one.\\
 {\tt   dl=}	&P*   	&Deletes the  current  line,  moving  all
                                   lines below it up by one.\\
 {\tt   dm=}	&	&Enters Delete Character mode.\\
{\tt    do=}	&	&Moves   the   cursor   down (line-feed on hard 
				terminals).\\
 {\tt   ed=}	& 	&Exits Delete Character mode.\\
 {\tt   ei=}	&  	&Exits  Insert  Character  mode.    (Each
                                   character  sent  to  the  terminal  will
                                   replace the character under (or  to  the
                                   right of) the cursor.\\
 {\tt   ho=}	&P  	&Move the cursor to home position
				( the top left corner).\\
 {\tt   ic=}	&P   	&Inserts one character space, moving  all
                                   characters  to  the  right of the cursor
                                   right by one space.\\
 {\tt   im=}	&P    	&Enter  Insert  Character  mode.    (Each
                                   character sent to the terminal will move
                                   all  characters  to  the  right  of  the
                                   cursor right by one.\\
 {\tt   ip=}	&P* 	&Inserts  padding  after  the   character
                                   being inserted.\\
 {\tt   is=}	&P	&Initialize the display.\\
 {\tt   ke=}	&  	&Exit keypad mode (disable the keypad).\\
 {\tt   kn\#}	&  	&Number of keypad keys.
			 Cursor arrows are {\tt kl=}(left),
			{\tt kr=}(right), {\tt ku=}(up),
			{\tt kd=}(down), {\tt kh=}(home).\\
 {\tt   ks=}	&  	&Start keypad mode (enable the keypad).\\
 {\tt   li\#}	& 	&Specifies  the  number  of  lines on the display.\\
 {\tt   nd=}	& 	&Moves the cursor right by one character.\\
 {\tt   pc=}	&  	&Definition of the padding char (NUL is default).\\
 {\tt   rc=}	&  	&Restore saved cursor position and attributes.\\
 {\tt   sc=}	&	&Save cursor position and attributes.\\
 {\tt   se=}	& 	&Exit {\sl stand-out} mode.  (All  subsequent
                                   characters will appear normally.)\\
 {\tt   sf=}	&P 	&Scroll forward (up) the display. The cursor
				remains at the same position.\\
 {\tt   so=}	&   	&Enter {\sl stand-out} mode.  (All subsequent
                                   characters  will  appear  highlighted in
                                   some fashion.   This  may  be  blinking,
                                   bold, reverse video, ...)\\
 {\tt   sr=}	&P 	&Scroll Reverse (down) the display.\\
 {\tt   tc=}	&   	&This field means that sequences are
			to be found with the name provided after the `='.\\
 {\tt   te=}	& 	&This string is sent to the terminal when
                                   EMACS exits or redraws the display.\\
 {\tt   ti=}	&  	&This string is sent to the terminal when
                                   EMACS starts up or redraws the display.\\
 {\tt   ue= }	&  	&Exit {\sl underscore} mode (synonym is {\tt Vu}).\\
 {\tt   ul }	&	&Terminal       underlines        without
                                   overstriking.\\
 {\tt   up=}	&P*	&Moves   the   cursor   up   one    line,
                                   maintaining the same column.\\
 {\tt   us= }	& 	&Enter {\sl underscore} mode.\\
 {\tt   vb=}	&   	&Flashes the screen (for a visible bell).\\
	\hline
\end{tabular}$$

     For each of the field names mentioned in the table 
	that end with `=',  you  should
     include  the sequence of characters that effect the behavior listed to
     the right of the name.  Fields with P or P* next to them  can  have  a
     time  delay  whenever  the  field is output (to permit terminals to do
     internal processing).  If a delay is needed then you may put a  number
     (indicating  milliseconds)  immediately  to  the right of the `=', but
     before the first character of the  string.   Additionally,  for  `dc',
     `dl',  `al', `cl', `ip', and `up', you can put an `*' after the number
     but before the first character of the string.  The `*' states that the
     delay  is  to  be  repeated  for  each  time the string is sent to the
     terminal.  (For example:  if EMACS needs to insert 3 blank lines, then
     it  will `execute the delay' between each of the issuances of the `al'
     string.)


          The string values for each name can have  the  following  special
     character sequences:

$$\begin{tabular}{|ll|} \hline

{\tt      \b E } 	& ASCII Escape character.\\
{\tt      \^{ }x } 	& The ASCII control character `x'.\\
{\tt      \b nnn } 	& The ASCII character represented by octal nnn.\\
{\tt      \b n     } 	& The Control-J (linefeed) character.\\
{\tt      \b r   } 	& Control-M (Carriage-return).\\
{\tt      \b t   } 	& Tab (Control-I).\\
{\tt      \b b   } 	& Backspace (Control-H).\\
{\tt      \b f   } 	& Formfeed (Control-L).\\
{\tt      \b\^\   } 	& A single caret (\^{ }).\\
{\tt      \b\b   } 	& A single backslash (\b).\\
{\tt      \b:   } 	& The column character (:).\\
\hline
\end{tabular}$$



          Note:  You must use \b072 or \b: to represent a colon (`:') 
		in a field.


          The value of the `cm' field has a special interpretation.   EMACS
     treats it as a function that is called with two parameters:  first the
     line, and then the column that the cursor is to  go  to.   Within  the
     string, the following character sequences have a special meaning:

$$\begin{tabular}{|lp{33em}|} \hline

{\tt      \%d } &	Replaced with the line or column number.\\
{\tt      \%2 } &       Replaced with the line or column  number  using  a
 	               two digit, zero filled field.\\
{\tt      \%3 } & 	Replaced with the line or column  number  using  a
                         three digit, zero filled field.\\
{\tt      \%. } &  	Use the ASCII character corresponding to the  line
                         or column number (line or column 1 would produce a
                         Control-A).\\
 {\tt     \%+x } &  	Use the ASCII character corresponding to the  line
                         or   column  number  plus  the  ASCII  number  for
                         character `x'.\\
 {\tt     \%>xy } &  	If the line or column number is  greater  than  an
                         ASCII  `x', then add an ASCII `y' to it.  (`x' and
                         `y' are characters.)\\
 {\tt     \%r   } & 	Output the column, then line.  (Emacs defaults  to
                         line and then column.)\\
 {\tt     \%i   } &  	Add one to  both  the  columns  and  line  numbers
                         (Emacs defaults to zero biased lines and columns).\\
 {\tt     \%\%  } &	Output a single `\%'.\\
{\tt      \%n   } & 	Exclusive-or the line and column number with octal
                         140.\\
\hline
\end{tabular}$$


          For example:

\begin{center}
                  {\tt cm=\b E[\%d;\%dm}
\end{center}

     translates to ESCAPE, left bracket, the line number, a semicolon,  the
     column number, then a lowercase M.



{\bf \^{ }S And \^{ }Q Handling}

          If your terminal (or communications link) uses \^{ }Q and  \^{ }S  
	(X-on,
     X-off)  for  synchronization,  then  you  should  set  xon-protocol as
     follows:

\begin{quote}
{\tt (set-terminal-characteristic "xon-protocol" 1) }
\end{quote}


          This will tell Emacs to intercept and act  on  these  characters;
     \^{ }S will be recognized as telling Emacs to stop sending characters, and
     \^{ }Q will tell Emacs to continue sending them.  Any bindings that  these
     characters  have  will  behave unpredictably.  Any MLisp functions you
     write can use the global variable xon-mode to determine if  it  should
     ignore or act on \^{ }Q and \^{ }S.


          If you set xon-mode to 1, then you  must  also  have  TTSYNC  and
     HOSTSYNC set with the Set Terminal VMS command.


          When xon-mode is set, then you will have to rebind any  functions
     that  are  bound  to  the \^{ }S and \^{ }Q keys (typically search-forward an
     quote-character).  The  conventional  rebindings  are  \^{ }\^{ } -s  and  
	\^{ }\^{ }-
     (Control-uparrow-s,  and  Control-uparrow-q),  although  some  of  the
     oltimers use Control-\b\  and Control-H.
\end{TeX}

----------------------------------------------------------------------------*/

#define	DEBUG		0	/* For debugging only 		*/

#define	PM_LEVEL 	LEVEL_TU

#define		TW_MACROS	0	/* Don't use TermWindows Macros */
#define		TW_import	0	
#define 	TW_STRUCT	0	/* Do not use window Structures		*/
#include	<twset.h>

#define	ESC		033	/* Code for ASCII escape character	*/
#define strbspan_(str,mask,table) 	oscbspan(str,strlen(str),mask,table)
#define strbspan(str,mask)		strbspan_(str,mask,main_ascii)

#define FINISH		goto FIN

#ifdef  call
#undef  call
#endif
#define call(x)		if (!(status = x))		FINISH	\
				/* Exit on error			*/

MID_STATIC INDEX  ind = {0};
static int fn;			/* TermCap File Number */
static TERM *terms;
char *osmsg();

/* MID_RSTATIC char	defaults[]=":bc:nd:do:up:cm:nl=\r\n:ff=\f:_H=^H:li#60:co#132:";*/
MID_RSTATIC char	defaults[]=":nd= :nl=\r\n:ff=\f:_H=^H:li#60:co#132:";

		/* Macros just to improve readibility	*/

#define		NCAPS			(terms->ns)
#define		CAPLIST			(terms->caplist)
#define		CAPSIZE			(terms->size)
#define		CAPTOP			(terms->captop)


/*	MONITOR(TERMCAP); */	/* CG.	status is defined locally*/

/*===========================================================================*/
static int strloc(str, c)
/*+++++++
.PURPOSE Locate the first occurence of character `c'
.RETURNS Index within str of char c; length of str if not found.
---------*/
	char *str;	/* IN: string to scan	*/
	char c;		/* IN: char to locate	*/
{
	register char *p;

  for (p=str; *p; p++)
  	if (*p == c)	break;
  return(p-str);
}

/*===========================================================================*/
static int stritem( s1, s2, sep)
/*++++++++++++++++++++++++
.PURPOSE Locates a substring within a string, which must be followed / preceded
	by separator(s) characters
.RETURNS Index within first string of second string. The index
	  is the length of the first string for mismatch.
.REMARKS Locate is made case-sensitive. 
.METHOD  Use index, then check preceding / following char.
-----------*/
     char *s1;	/* IN: address of first string (source)	*/
     char *s2;	/* IN: address of 2nd string  (object to find)	*/
     char *sep;	/* IN: list of separators	*/
{   
	register char *p1, *pe;
	register int i;

  i = strlen(s2);
  if (i == 0)	i = 1;
  
  for (p1 = s1, pe = p1 + strlen(p1); *p1; )
  {	p1 += oscindex(p1, pe-p1, s2, i);
	if_not(*p1)	break;		/* Not Found */
  	if (p1 > s1)			/* Check preceding char */
  	{	p1--;
  		if_not (*(sep + strloc(sep, *(p1++))))
		{	p1 += i;
			continue;
		}
  	}
	p1 += i;			/* Check following char	*/
	if_not(*p1)	break;		/* Located at end : OK	*/
	if(*(sep + strloc(sep, *p1)))	/* Separator found	*/
			break;
  }

  return(p1-s1);
}

/*==========================================================================
 *			f_gets
 *==========================================================================*/
static int f_gets (buf, len)
/*+++
.PURPOSE Interface to file reading
.RETURNS OK / NOK / EOF
.REMARKS On return, always terminated by EOS.
---------*/
	char	*buf;	/* OUT: text, EOS-terminated	*/
	int	len;	/* IN: Size of buffer		*/
{
	register int status;

  status = osaread(fn, buf, len);
  if (status >= len)
	ERR_ED_STR2("Too long TermCapFile record: ", buf, 30);
  if (status >= 0)	status = OK;
#if DEBUG
  printf("Read from TermCapFile: %s\n",buf);
#endif 

  return(status);
}

/*==========================================================================
 *			tu_encode
 *==========================================================================*/
static int tu_encode (str)
/*++++++++++++++
.PURPOSE Encode capabilities followed by the `=' sign, i.e.
\begin{TeX}
\begin{itemize}
	\item interpretation of delays into number of ms 
		(limited to 255)
	\item interpretation of \b ooo (octal codes)
	\item replacement of the \% format by FORMAT char (0x`FE')
	\item replacement of the starting `:' by the length of the coded
		capability.
\end{itemize}
\end{TeX}
.RETURNS Length of capability
.REMARKS An existing delay is flagged by `d' (no repetition), 
	or `D' (repeated delay indicated by P*) in place of the `='.
-----------------------*/
	char *str;		/* MOD: The cap string to encode	*/
{
	register char *p1, *p2;
	register int delay;
	MID_STATIC char delay_flag = '=';

  ENTER("+tu_encode");

  TRACE_ED_STR2("Coding capability ",str,4);

  p1 = str;
  if (*p1 != ':')  {	ERR_ED_STR2("Bad TermCapability=>",str,4);
			FINISH;
		   }
  p1 += 1;
  if (*p1)	p1 += 2;	/* Not Followed by EOS	*/

  *str = 0;
  switch(*(p1))		/* Test char following the cap_code	*/
  { case '@' : 			/* Nothing to code	*/
	p1++;
    case ':' : 	case EOS:	/* Nothing to code	*/
	goto FIN;
    case '=' : break;
    default  : 			/* Do not code, but compute length	*/
	delay = oscloc(p1, 80, ':');	/* Length */
	*str = delay - 1, p1 += delay;
	goto FIN;
  }

	/* Here, only if cap_code followed by `='. p1 and p2 are used
		as pointers to input / output string	*/
  p1 = str+4, p2 = p1;

	/* Compute the delays, i.e. digits followed by optional `*'	*/
  delay_flag = '=';
  for( delay = 0; isdigit(*p1); p1++) 
  {	delay *= 10;
	delay += (*p1 - '0');
	delay_flag = 'd';
  }
  if(*p1 == '*') 	p1++, delay_flag = 'D';

  for(; *p1 != ':'; p2++)	/* The `:' indicates the end */
  {	switch(*p1)	
	{ case '^':	/* Control Char	*/ 
		*p2 = (*(++p1)) & 037;
		p1++; break;
	  case '\\': 	/* Escape - Look next char	*/
		p1++, *p2 = 0;
		switch(*p1)
		{ case 'E': case 'e':	*p2 = ESC; p1++; break;
		  case 'n': *p2 = '\n'; p1++;  break;	/* Newline	*/
		  case 'r': *p2 = '\r'; p1++;  break;	/* <Return>	*/
		  case 't': *p2 = '\t'; p1++;  break;	/* Horiz. Tab	*/
		  case 'b': *p2 = '\b'; p1++;  break;	/* Backspace	*/
		  case 'f': *p2 = '\f'; p1++;  break;	/* Form Feed	*/
		  case '0': case '1': case '2': 	/* Octal number */
			case '3':
			while(isdigit(*p1))
			{	*(unsigned char *)p2 *= 8; 
				*(unsigned char *)p2 += *(p1++) - '0';
			}
			/*	*p2 &= 0177; */	/* Convert to ASCII	*/
			break;
		  default: 	/* case '^': case '\\': and others	*/
			*p2 = *(p1++); break;
		} break;
	  case '%': 	/* May be a format	*/
		if (*(++p1) == '%')	*p2 = *(p1++);	/* `%' sign	*/
			else		*p2 = FORMAT;
		break;
	  default:	/* Normal char		*/
		*p2 = *(p1++);
	}
  }

	/* Write the length of the coded string	*/
  *str = p2 - str - 4;

 	/* Insert the delay --- limited to 255 ms !	*/
  if (delay)
  {	*(str+3) = delay_flag;
	*(unsigned char *)p2   = MIN(delay, 255);
  }

#if DEBUG
  TRACE_ED_STR2("Coded:",str+4,*str);
  if(*(str+3) != '=') 	TRACE_ED_I("Delay is ",*(str + 4 + *str));
#endif

  FIN:
  EXIT(p1 - str);
}
	
/*==========================================================================
 *			tu_append
 *==========================================================================*/
static int tu_append (buffer, len)
/*+++++++++
.PURPOSE Append into the TERMCAP list the specified buffer.
.RETURNS OK / NOK
.REMARKS Not traced.
---------*/
	char *buffer;		/* IN: Buffer to copy		*/
	int  len;		/* IN: Length of buffer		*/
{
 	register int n;

  if (len <= 0) 	return(OK);

				/* Test for 2 consecutive : */
  if ( (*buffer == ':') && (CAPTOP > 0)) 
  	if (*(CAPLIST + CAPTOP -1) == ':')	len--,  buffer++;

		/* Test if area large enough, with one spare byte	*/
  if ( (CAPTOP + len) >= CAPSIZE) 		/* Reallocate		*/
  {	/* TRACE("Reallocation of Termcap Area");*/
	n = CAPSIZE + MAX (MEM_AMOUNT,len);	/* Required memory 	*/
	CAPLIST = MEM_EXP(char, CAPLIST, n);
	if (!CAPLIST)	return(NOK);		/* Allocation failed	*/
	CAPSIZE = n;
  }
				/* Copy caplist to area		*/
  CAPTOP += oscopy(CAPLIST + CAPTOP, buffer, len);

  return(OK);
}

/*==========================================================================
 *			tu_x1
 *==========================================================================*/
static int tu_x1 ()
/*++++++++++
.PURPOSE Encodes the capabilities and generates the index by capability
.RETURNS OK/NOK
.REMARKS The first encountered capability wins if duplicates
	exist --- however, input sequences are stored several times
	when duplicates exist.
-----------------*/
{
	register int i,j;
	INDEX 	*idx;		/* Starting address of index by capability */
	int 	flag, status;
	
#if DEBUG
	MID_STATIC char cap3[] = "xx: ";
#endif

  ENTER("tu_x1");

  status = NOK;
  NCAPS = 0;			/* No sequences		*/

	/* Scan the caplist - each cap starts and ends with `:'	*/

  for ( i = 0, j = 0; isgraph(*(CAPLIST+i)) ;  i += j)
  {	idx = (INDEX *) (CAPLIST + terms->index);	
  					/* May have been reallocated...	*/
	j = i + 1;
	ind.cap[0] = *(CAPLIST+j++);	/* First char of capcode	*/
	ind.cap[1] = *(CAPLIST+j);	/* Second char of capcode	*/
	ind.icap   = i;			/* Index of capcode		*/

	flag = 0;			/* Check if entry aleady exists	*/
	if( (ind.cap[0] != 'k') && (ind.cap[0] != 'K') && (ind.cap[0] != 'F'))
	{	for (j=0; (j<NCAPS) && (flag == 0); j++)
			flag = ((idx[j].cap[0] == ind.cap[0]) && 
				(idx[j].cap[1] == ind.cap[1]));
	}
	j = tu_encode(i + CAPLIST);
	if (j < 3)			/* Don't add to index	*/
	{	flag = 1;
		if (j <= 0)	FINISH;
	}
	if(flag)	continue;	/* Already exists	*/

	NCAPS++;			/* Add a new entry	*/
	call(tu_append((char *)&ind,sizeof(ind)));
			/* Encode the capabilities		*/
  }

		/* Sorting via a simple interchange		*/
#if DEBUG
  TRACE_ED_I("Sorting capabilities ",NCAPS);
#endif
  status = OK;
  if (NCAPS < 2) 	FINISH;

  flag = NCAPS-1;	

  idx = (INDEX *) (CAPLIST + terms->index);

  for (i=0; i<flag; i++)
  {	for (j=i+1; j < NCAPS; j++)	
	{	if (idx[i].cap[0] < idx[j].cap[0]) continue;
		if (idx[i].cap[0] == idx[j].cap[0]) 
			if (idx[i].cap[1] <= idx[j].cap[1]) continue;
		ind = idx[i]; idx[i] = idx[j]; idx[j] = ind;
	}
  }

#if DEBUG
  TRACE("Sorted Capabilities");
  for (i=0; i<NCAPS; i++)
  {	cap3[0] = idx[i].cap[0], cap3[1] = idx[i].cap[1];
  	TRACE_ED_STR2(cap3, 4+CAPLIST+idx[i].icap, *(CAPLIST+idx[i].icap));
  }
#endif

  FIN:
  EXIT(status);
}

/*==========================================================================
 *			tu_x2
 *==========================================================================*/
static int tu_x2 ()
/*+++++++++++
.PURPOSE Generates the index by sequences (made with short integers)
.RETURNS OK/NOK
.REMARKS To be meaningful, capabilities should be coded.
	Only those caps beginning with `k', `K' or `F' are retained
	(functions that are read on the terminal)
-----------*/
{
	register int i;
	register char *p1, *p2;
	INDEX *idx1;		/* Starting address of index by capability */
	short int  *idx;	/* Starting address of index by sequence */
	short int temp;
	char 	flag;
	int	status;

  ENTER("tu_x2");

  status = NOK;
  
	/* Simply use the index by capcodes ---
	   Keep only capcodes starting with 'k', 'K' or 'F'	*/

  terms->nsr = 0;		/* No readable sequence		*/
  terms->specials = 0;

  for (i=0; i<NCAPS; i++)
  {	idx1 = (INDEX *) (CAPLIST + terms->index);
	flag = idx1[i].cap[0];
	if (flag == 'k' || flag == 'K' || flag == 'F')
	{	call(tu_append((char *)&idx1[i].icap, sizeof(short int)));
		(terms->nsr)++;
	}
  }

	/* Sort ... */
#if DEBUG
  TRACE_ED_I("Sorting capabilities: ",(terms->nsr));
#endif

  status = OK;
  if ((terms->nsr) < 2) 	FINISH;

  flag = 1;	/* Indicates sort not complete	*/
  idx  = (short int *) (CAPLIST + terms->indexr);

  while(flag)
  {	flag = 0;
	for (i=0; i<(terms->nsr) -1; i++)
	{	p1 = CAPLIST + idx[i] + 4;
		p2 = CAPLIST + idx[i+1] + 4;
		while (*p1 == *p2)	p1++, p2++;
		if (*p1 <= *p2) continue;
		temp = idx[i]; idx[i] = idx[i+1]; idx[i+1] = temp;
		flag = 1;
	}
  }

	/* Flag in `specials' chars that start escape sequences	*/

  for (i=0; i<(terms->nsr); i++)
  {	p1 = CAPLIST + idx[i] + 4;
	if (*(unsigned char *)p1 < 32)	terms->specials |= 
		MASK(*(unsigned char *)p1);
  }

#if DEBUG
	for (i=0; i<(terms->nsr); i++)
		TRACE_ED_STR2("Caps sorted by sequence: ",
			CAPLIST + idx[i] + 1 ,2);
#endif

  FIN:
  EXIT(status);
}

/*==========================================================================
 *			tu_build
 *==========================================================================*/
static int tu_build ()
/*++++++++
.PURPOSE Generates the 2 indexes (by capcode - by sequences), and
	encodes the caps.
.RETURNS OK/NOK
.REMARKS 
----------*/
{
	int	status;
	
  ENTER("tu_build");
  status = NOK;

  *(CAPLIST + CAPTOP++) = EOS;	/* Terminate the string	*/

	/* Adjust the captop to a correct boundary	*/

  CAPTOP = ((CAPTOP + sizeof(char *)-1)/sizeof(char *)) * sizeof(char *);

	/* Save this position in term.index	*/
  terms->index = CAPTOP;

	/* Encode capabilities and generate the index by capabilities	*/
  call(tu_x1());

	/* Generate the index by sequences	*/
  CAPTOP = ((CAPTOP + sizeof(char *)-1)/sizeof(char *)) * sizeof(char *);
  terms->indexr = CAPTOP;
  call(tu_x2());
  status = OK;

  FIN:
  EXIT(status);
}

/*==========================================================================
 *			tu_fetch
 *==========================================================================*/
static int tu_fetch (device)
/*++++++++++++++
.PURPOSE Search the TERMCAP file for a specified device, and append the
	caplist into CAPLIST.
.RETURNS NOK if device not found, OK otherwise
.REMARKS 
------------------*/
	char *device;		/* IN: EOS-terminated device name 	*/
{
	int i, j, l, status;
	char buffer[1024];

  ENTER("tu_fetch");

  TRACE_ED_STRING("Looking for Device=>",device);

  while ((status = f_gets(buffer,sizeof(buffer))) == OK)
  {	if (buffer[0] == '#') 
	 	continue;			/* Comment line	*/   
  	if (isspace(buffer[0])) continue;	/* Not useful	*/   
	i = stritem(buffer,device,":|"); 
				/* Followed / preceded by : or | */
	if (buffer[i]) 	break;
  }
  if (status != OK) 	FINISH;		/* Device not found	*/

	/* Now, load the caplist, which starts right now, at the :
	 * Note that the `\' indicates a continuation on the next line	*/

  i = strloc(buffer, ':');	/* Starting scanning point */

  for (; status == OK; status = f_gets(buffer,sizeof(buffer)))
  {	if (buffer[0] == '#')		/* Line commented out	*/
		continue;
  	if (i == 0)	i = oscspan(buffer,sizeof(buffer), _SPACE_, main_ascii);
	if (i<=0) 	break;		/* List must start with blank or so */
	j = strbspan(buffer,_SPACE_);	/* Offset of last char */
	l = j-i;			/* Length of the termlist	*/
	if (buffer[j] != '\\') l++;
	call(tu_append(&buffer[i],l));
					/* Test for continuation char \	*/
	if (buffer[j] != '\\') break;
	i = 0;
  }
  if (status == NOK)	FINISH;

  status = OK;
  TRACE_ED_STR2("CapList: ",CAPLIST,CAPTOP);

  FIN:
  if (status != OK)	status = NOK;
  EXIT(status);
}

/*==========================================================================
 *			tu_scan
 *==========================================================================*/
static int tu_scan (device)
/*+++++++++++
.PURPOSE Open the specified TERMCAP file for the named device, expanding
	the ``tc='' references.
.RETURNS NOK if device not found, OK otherwise
.REMARKS 
---------------*/
	char *device;		/* IN: EOS-terminated device name 	*/
{
	char 	*p, *tc_device;
	int	status;

  /* ENTER("tu_scan"); */

  TRACE_ED_STRING("Look for device: ", device);
  status = NOK;

  	/* Now, fetch the successive entries		*/
  tc_device = device;

  while(1)
  {	if (tu_fetch(tc_device) != OK) 
	{	ERR_ED_STRING("This device is unknown: ",tc_device);
		FINISH;;
	}	
	*(CAPLIST + CAPTOP) = EOS;	/* Terminate the string	*/
			/* Locate last field 	*/
	p = CAPLIST + oscbloc(CAPLIST, CAPTOP, '=');
	tc_device = p;
	if (*(--p) != 'c') break;	/* Should match "tc="	*/
	if (*(--p) != 't') break;	/* Should match "tc="	*/
		/* An expansion is required - Reset the captop size in
		 * the term, and get the alternate device name		*/
	tc_device++;	/* Starting char of alternate device name	*/
	*(CAPLIST + CAPTOP - 1) = EOS;	/* Replace the :	*/
	CAPTOP = p - CAPLIST;	/* Last field is deleted	*/
	osaseek(fn, 0L, 0);
  }

  status = OK;
  osaclose(fn);

  FIN:
  return(status);
}

/*==========================================================================
 *			tu_load
 *==========================================================================*/
int tu_load (file_name, device, term)
/*++++++++++++
.PURPOSE Load to TERM structure the specified device.
.RETURNS NOK if device or file not found, OK otherwise
.REMARKS Appends some defautt capabilities.
----------------*/
	char *file_name;	/* IN: EOS-terminated TERMCAP file name	*/
	char *device;		/* IN: EOS-terminated device name 	*/
	TERM *term;		/* MOD: Area to receive capabilities */
{
	int	status;

  ENTER("tu_load");

  TRACE_ED_STRING("TermCapFile: ", file_name);
  status = NOK;

  terms = term;

	/* First, open the TERMCAP file	*/

  fn = osaopen(file_name,READ);
  if (fn <= 0)	ERR_ED_STRING("Bad TermCap File: ", file_name);
  else		status = tu_scan(device);
  if (!status)	FINISH;

  tu_append(defaults, sizeof(defaults)-1);

  status &= tu_build();	

#if DEBUG
	TRACE_ED_STR2("CapList       ",terms->caplist, terms->captop);
#endif

  FIN:
  EXIT(status);
}

