/*  DBXFACE.C	20-Jan-05 17:31:41 by Kevin D. Quitt

20-Jan-05 17:31, [Rockyroad]d:\isiarm\Sample Utilities\DBserve\dbxface.c, Edit by kdq
    Initial implementation, split from demoserv

*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>

#ifdef	WIN32
#undef	WIN32
#define	WIN32	1
#endif

#ifdef	VMS
#undef	VMS
#define	VMS	1
#endif

#ifdef	LINUX
#undef	LINUX
#define	LINUX	1
#endif

#if	WIN32
#include <fcntl.h>
#include <io.h>
#include <conio.h>
#include <Winsock2.h>
#include <time.h>
#include <process.h>    /* _beginthread, _endthread */
#elif	VMS
#include <in.h>
#include <inet.h>
#include <netdb.h>
#include <types.h>
#include <socket.h>
#include <tcp.h>
#include <unixio.h>
#include <ucx$inetdef.h>
#include <iodef.h>
#include <unixlib.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <time.h>
#endif

#include    "dbxface.h"
#include    "strutil.h"


char	*datafile   = "nanodata.dat";   /* Default data file name	    */


/*  Process an event.  The default is we do nothing
*/
int	databaseEvent( unsigned long event, char *unitID )
  {
    (void)event;
    (void)unitID;

    return  FALSE;
  }


int databaseLookup( char *code, char *outline, size_t outsize )
  {
    FILE   *in;
    char    tcode[ 128 ];
    char    data[ 512 ];
    int	    len, rlen;                 
    int	    found   = FALSE;
    char   *record;
    int	    isTouch = FALSE;


    if ( !code  ||  !outline )
	return	0;
    *outline	= 0;

    in	= fopen( datafile, "rb" );
    if ( !in )
	return	0;


/*  Get the passed barcode, remove trailing whitespace, then append a tab.
*/
    strcpy( tcode, code );
    len	= strip( tcode );
    if ( !len )
	return	0;

    strcat( tcode, "\t" );
    len++;


/*  Entries in nanodata.dat consist of the barcode (case sensitive)
    followed by a tab character, followed by the exact text.

    Compare the barcode (including tab character) to start of lines in the 
    file.
*/
    while ( !found  &&  !feof( in )  &&  !ferror( in ))
      {
	fgets( data, sizeof data, in );
	if ( feof( in )  ||  ferror( in ))
	    break;

	if ( isspace( data[ 0 ]))
	    continue;

	rlen	= strip( data );
	if ( !rlen )
	    continue;

	if ( !strncmp( tcode, data, len ))
	  {
	    record  = data + len;
	    rlen    -= len;
	    if ( rlen  <=  0 )		/* Anything in the data record?	    */
		continue;

	    strncpy( outline, record, outsize );
	    found   = TRUE;
	  }
      }

    fclose( in );

    if ( found )
	return	strlen( outline ) + 1;	/* Including terminating NUL	    */

    return  0;
  }
