#include <stdio.h>
#include "common.h"
#include "module.h"
#include "allocate.h"
#include "hash.h"
#include "error.h"
#include "lnames.h"
#include "list.h"

extern HASHREC ** PublicHash;

char * LnameList[MAXLNAMEITEMS];  // LNAMES are kept in an array, on
																	// a per-module basis
static int NumLnameItems;					// Number of items in the array

/* Read LNAMES from the omf record
 */
static void ReadLnames(BOOL is32, BYTE *buffer, 
			int size, char *name, BOOL toMangle)
{
  char *Lname;
  // A record of size zero simply bumps the index by one
  if (size == 0) {
		LnameList[NumLnameItems++] = 0;
		return;
	}
  while(size > 0) {

		// Read the name
    Lname= ReadName(&buffer, &size, toMangle);

		if (NumLnameItems >= MAXLNAMEITEMS)
			fatal("Too many LNAME in module %s",name);
		LnameList[NumLnameItems++] = Lname;
  }
    
  CheckSize(size);
}
/*
 * Pre-pass initialize
 */
void LnameInit(uint pass)
{
	NumLnameItems = 0;
}
/*
 * Per module rundown, just deallocate the lname
 */
void LnameModuleRundown(uint pass)
{
  int i;
#ifdef DEBUG
  if (pass == 1)
    printf("Lnames:\n");
#endif
  for (i=0; i < NumLnameItems; i++) {
#ifdef DEBUG
		if (pass == 1)
      printf("  %s\n",LnameList[i]);
#endif DEBUG
    DeallocateMemory(LnameList[i]);
  }
	NumLnameItems = 0;
}
/*
 * Return an lname corresponding to an index.  OMF indexes all start at one
 * rather than 0
 */
char * GetLname(int index)
{
  if (index > NumLnameItems)
		fatal("Missing LNAME index %d",index);
  return(LnameList[index-1]);
}
/*
 * Post-pass rundown
 */
void LnameRundown(uint pass)
{
}
/*
 * Load public lnames
 */
void LnameDefinitions(BOOL is32,BYTE *buffer, 
			int size, char *name, uint pass)
{
    ReadLnames(is32,buffer, size,name, FALSE);
}
/*
 * Load private lnames
 */
void LocalLnameDefinitions(BOOL is32,BYTE *buffer, 
			int size, char *name, uint pass)
{
    ReadLnames(is32,buffer, size,name, TRUE);
}