/* FIELDMAP.C - field position routines 
 * Copyright 1998-2001 Stephen C. Grubb  (www.sgpr.net) .
 * This code is covered under the GNU General Public License (GPL);
 * see the file ./Copyright for details. */

#include <ctype.h>
#include "tdhkit.h"

/* there are 2 field map instances here, for cases where we need to
   insulate db accesses from script processing. */

static int imap = 0;  /* indicates which map instance is in use */

static char currec[2][80] = { "", "" };
static char names[2][MAXITEMS][NAMEMAXLEN+1];
static int nitems[2] = { 0, 0 };
static char LoadDelim[2] = " ";

int
TDH_fieldmap( recordid, item )
char *recordid, *item;
{
int i;

if( recordid[0] == '\0' ) return( -1 ); /* no recordid specified - scg 11/8/02 */

if( strcmp( recordid, currec[imap] ) != 0 ) {
	return( -2 ); /* record not found */
	/* n = TDH_readfdf( recordid, names[imap], NULL, NULL );
	 * if( n <= 0 ) return( -2 ); (( record not found ))
	 * strcpy( currec[imap], recordid );
	 * nitems[imap] = n;
	 */
	}
if( strcmp( item, "" )==0 ) return( nitems[imap] );
for( i = 0; i < nitems[imap]; i++ ) {
	if( strcmp( item, names[imap][i] )==0 ) { 
		/* printf( "[%d %s %d]", imap, item, i ); */
		return( i ); 
		}
	}

return( -1 ); /* record ok but item not found */
}

/* ============================ */
/* LOADFIELDMAP - fill the names list from a buffer containing the names, space delimited */
int
TDH_loadfieldmap( recordid, buf )
char *recordid;
char *buf;
{
int i, ix;
ix = 0;
i = 0;
while( 1 ) {
	if( isspace( (int) LoadDelim[0] )) strcpy( names[imap][i], GL_getok( buf, &ix ) );
	else GL_getseg( names[imap][i], buf, &ix, LoadDelim ); 
	if( strlen( names[imap][i] ) == 0 ) break;
	if( i >= (MAXITEMS-1) ) return( 1070 ); /* too many header items */
	i++;
	}
nitems[imap] = i;
if( nitems[imap] < 1 ) return( 1071 ); /* no header items found */
strcpy( currec[imap], recordid );

return( 0 );
}

/* =================================== */
/* LOADFIELDMAPF - same as above but fill takes a field array */
int
TDH_loadfieldmapf( recordid, fields, n )
char *recordid;
char *fields[];
int n;
{
int i;
for( i = 0; i < n; i++ ) {
	strcpy( names[imap][i], fields[i] );
	if( i >= (MAXITEMS-1) ) return( 1070 ); /* too many header items */
	}
nitems[imap] = i;
if( nitems[imap] < 1 ) return( 1071 ); /* no header items found */
strcpy( currec[imap], recordid );
return( 0 );
}


/* ======================================= */
/* ALTFMAP - select the alternate (DB) field map */
int
TDH_altfmap( map )
int map; 	/* 1 = use alt map  0 = don't */
{
imap = map;
return( 0 );
}

/* ======================================== */
/* FIELDN - return name of field n, where first is 0 */
char *
TDH_fieldn( n )
int n;
{
if( n < 0 || n > nitems[imap] ) return( NULL );
return( names[imap][n] );
}


/* ========================================= */
/* SETFMDELIM - set the delim character for loadfieldmap() */
int
TDH_setfmdelim( c )
char c;
{
sprintf( LoadDelim, "%c", c );
return( 0 );
}
