/**********************************************************************
 *
 *  module   : HfdIndex
 *  fichier  : HfdIndexRead.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 "StrDict.h"
#include "SxPath.h"
#include "HfdIndex.h"


/**
   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.
 */
HfdIndex *HfdIndexOpenRead(char *hfdPath)
{
  HfdIndex *curIndex;
  curIndex            = (HfdIndex *) malloc(sizeof(HfdIndex));
  if((curIndex->hfd       = HfdOpenReadKey(hfdPath)))
    {
      curIndex->desc      = SxmlGetFirstChildByTagName(curIndex->hfd->desc,"index");
      curIndex->tagKey    = SxmlLeafText( SxmlGetFirstChildByTagName (curIndex->desc,"tag"));
      curIndex->hidPath   = malloc(strlen(hfdPath)+5); 
      curIndex->curPath   = NULL;
      strcpy(curIndex->hidPath, hfdPath); 
      strcat(curIndex->hidPath,".hid");
      curIndex->hidTable = StrDictFromFile(curIndex->hidPath);
    }
  else 
    {
      free(curIndex);
      curIndex=NULL;
    }
  return curIndex;
}

void HfdIndexClose(HfdIndex *curIndex)
{
  free (curIndex->hidPath);
  StrDictFreeStr(curIndex->hidTable);
  free (curIndex);
}

SxmlNode *HfdIndexReadSxmlRecord(HfdIndex *curIndex, char *entryName)
{
  char *firstKeyBloc;
  char *hfdKeyBloc;
  char *recPath;


  if ((firstKeyBloc=StrDictKeyLessEqual(curIndex->hidTable, entryName)))
    {
      hfdKeyBloc=StrDictValue(curIndex->hidTable);
      recPath=HfdHcbGetPath(curIndex->hfd,hfdKeyBloc);
      if (HfdOpenPathCont(curIndex->hfd,recPath,curIndex->tagKey))
	{
	  return HfdFileGetSxmlRecordCont(curIndex->hfd->hfdFile,entryName);
	}
    }
  return NULL;
}

HfdRecord *HfdIndexReadRecord(HfdIndex *curIndex, char *entryName)
{
  char *firstKeyBloc;
  char *hfdKeyBloc;
  char *recPath;
  if ((firstKeyBloc=StrDictKeyLessEqual(curIndex->hidTable, entryName)))
    {
      hfdKeyBloc=StrDictValue(curIndex->hidTable);
      recPath=HfdHcbGetPath(curIndex->hfd,hfdKeyBloc);
      if (HfdOpenPathCont(curIndex->hfd,recPath,curIndex->tagKey))
	{
	  return HfdFileGetRecordCont(curIndex->hfd->hfdFile,entryName);
	}
    }
  return NULL;
}

SxmlNode *HfdIndexReadSxml(HfdIndex *curIndex, char *entryName)
{
  SxmlNode *n1;
  if ((n1=HfdIndexReadSxmlRecord(curIndex, entryName)))
    {
      return SxmlLastChild(n1);
    }
  else return NULL;
}
