/**********************************************************************
 *
 *  projet   : DilibDam
 *  module   : Index
 *  fichier  : IndexRead.c
 *  Auteur   : Jacques DUCLOY
 *  Date     : Fevrier 94
 *  $Id: IndexRead.c,v 1.4 2005/06/22 13:02:13 parmentf Exp $
 *
 **********************************************************************
 *
 * Copyright (c) 1994 CNRS/CRIN & INRIA Lorraine
 * 
 **********************************************************************/
 
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "StrSearch.h"
#include "SgmlPath.h"
#include "Index.h"

/*SgmlNode* DamRecordToSgml();*/

/**
   Reads an index Hfd, whose @a name is given, and creates an Index.
   
   @param name name of the index Hfd, without the @p .hfd ending.
   
   @return the Index created.
 */
Index *IndexOpenRead(char *name)
{
  Index *curIndex;
  curIndex            = (Index *) malloc(sizeof(Index));
  if((curIndex->hfd       = DamHfdOpenReadKey(name)))
    {
      curIndex->desc      = SgmlGetSonTag(curIndex->hfd->desc,"index");
      curIndex->tagKey    = SgmlLeafGetData(
				    SgmlGetSonTag (curIndex->desc,"tag"));
      curIndex->hidPath   = malloc(strlen(curIndex->hfd->descFile)+1);
      curIndex->curPath   = NULL;
      strcpy(curIndex->hidPath, curIndex->hfd->name);
      strcat(curIndex->hidPath,".hid");
      curIndex->hidTable = StrSearchGetTable(curIndex->hidPath, 100);
    }
  else 
    {
      free(curIndex);
      curIndex=NULL;
    }
  return curIndex;
}

SgmlNode *IndexReadSgmlRecord(Index *curIndex, char *entryName)
{
  char *firstKeyBloc;
  char *hfdKeyBloc;
  char *recPath;
  if ((firstKeyBloc=StrSearchKeyLessEqual(curIndex->hidTable, entryName)))
    {
      hfdKeyBloc=StrSearchValue(curIndex->hidTable);
      recPath=DamHfdGetPath(curIndex->hfd,hfdKeyBloc);
      if (DamHfdOpenPathCont(curIndex->hfd,recPath,curIndex->tagKey))
	{
	  return DamFileGetSgmlRecordCont(curIndex->hfd->damFile,entryName);
	}
    }
  return NULL;
}

DamRecord *IndexReadRecord(Index *curIndex, char *entryName)
{
  char *firstKeyBloc;
  char *hfdKeyBloc;
  char *recPath;
  if ((firstKeyBloc=StrSearchKeyLessEqual(curIndex->hidTable, entryName)))
    {
      hfdKeyBloc=StrSearchValue(curIndex->hidTable);
      recPath=DamHfdGetPath(curIndex->hfd,hfdKeyBloc);
      if (DamHfdOpenPathCont(curIndex->hfd,recPath,curIndex->tagKey))
	{
	  return DamFileGetRecordCont(curIndex->hfd->damFile,entryName);
	}
    }
  return NULL;
}


SgmlNode *IndexReadSgml(Index *curIndex, char *entryName)
{
  SgmlNode *n1;
  if ((n1=IndexReadSgmlRecord(curIndex, entryName)))
    return SgmlLast(n1);
  else return NULL;
}


