/**********************************************************************
*
*  projet   : DilibPro
*  module   : Index
*  fichier  : IndexSelect.c
*  Auteur   : Jacques DUCLOY
*  Date     : Fevrier 94
*  $Id: IndexSelect.c,v 1.2 2005/06/22 13:04:05 parmentf Exp $

Introduction option r pour récupérer la clé interne du record
*
***********************************************************************/
 
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "StrSearch.h"
#include "SgmlPath.h"
#include "Index.h"

Index *hfd1;
int              flagRecordKey;
int               flagSkip;
SgmlPathProg     *pathSkip;
SgmlPathIterator *iterSkip;

void usage()
{
  fprintf (stderr,"usage: IndexSelect [-S] [-s path] -h hfd [-k key]...\n");
  exit(1);
}

void resul(char *str)
{
  SgmlNode *n;
  SgmlNode *e;
  char *posTab;

  if ((posTab=strchr(str,'\t')))
    {
      posTab[0]='\0';
      posTab++;
    }
  if(flagRecordKey)
    {
       if((n=IndexReadSgmlRecord(hfd1, str)))
	 {
	   SgmlPrint(n);
	 }
    }
  else
    {
      if((n=IndexReadSgml(hfd1, str)))
	{   
	  if(flagSkip)
	    {
	      SgmlPathIteratorInit(iterSkip,n);
	      while ((e=SgmlPathNext(iterSkip)))
		{
		  if (posTab)printf("%s\t%s\n",SgmlLeafGetData(e),posTab);
		  else printf("%s\n",SgmlLeafGetData(e));
		}
	    }
	  else
	    {
	      SgmlPrint(n);
	      if (posTab)printf("\t%s\n", posTab);
	      else putchar('\n');
	    }
	}
  }
}

void IndexSelect_Error(char *mess1, char *mess2)
{
  fprintf(stderr, "IndexSelect: *** ERROR ***\n");
  fprintf(stderr, "%s%s\n", mess1, mess2);
  usage();
}


extern char *optarg;   
extern int   optind;
int getopt();

int main(int argc, char **argv)
{
 int cod_arg;
 int flagInput;
 Buffer *buf;
 char *input;
 
 flagRecordKey=0;
 flagSkip=0;
 flagInput=0;

  while (((cod_arg = getopt(argc,argv,"ih:k:rs:S"))!=EOF))
    {
      switch(cod_arg)
	{
	case 'r':
	  flagRecordKey=1;
	  break;
	case 's':
	  flagSkip=1;
	  if ((pathSkip=SgmlPathCompile(optarg)))
	    {
	      iterSkip=SgmlPathIteratorCreate(pathSkip);
	    }
	  else IndexSelect_Error(optarg," : path incorrect");
	  break;
	case 'S':
	  flagSkip=1;
	  pathSkip=SgmlPathCompile("l/e");
	  iterSkip=SgmlPathIteratorCreate(pathSkip);
	  break;
	case 'k':
	  resul(optarg);
	  break;
	case 'i':
	  flagInput=1;
	  break;
	case 'h':
	  hfd1=IndexOpenRead(optarg);
	  break;
	default:
	  usage();
	}
    };

  if (flagInput==1)
    {
      buf=BufferCreate(132,132);
      while ((input = BufferGets(buf)))
	{
	  resul(input);
	};
    };

  return 0;
}
