/**********************************************************************
*
*  projet   : Infometrics
*  module   : Cluster
*  fichier  : IndexClusterSetFromHisto.c
*  Auteur   : Jacques DUCLOY
*  Date     : 05.02.98
*
***********************************************************************/
#include "Sgml.h"
#include <stdlib.h>
#include "StrSearch.h"

   int getopt();
    extern char *optarg;

static  int maxElem;
int main(argc, argv)
  int   argc;
char **argv;
{
  int cod_arg;
  StrSearchTable *clustersTable;
  DamFile *fClu;
  SgmlNode *nClu;

  maxElem=100;
  clustersTable=StrSearchTableCreate(100,10);
  fClu= DamFileCreate();
  while ((cod_arg = getopt(argc,argv,"f:m:"))!=EOF)
    {switch(cod_arg)
      {
      case 'f':
	DamFileOpen(fClu,optarg);
	while ((nClu=DamFileNextSgmlRecord(fClu)))
	  {
	    char *key;
	    key=SgmlLeafGetData(SgmlGetSonTag(SgmlFirst(nClu),"code"));
	    StrSearchAdd(clustersTable,
			 strdup(key),
			 (char *)SgmlCut( SgmlFirst(nClu)));
	  }
	break;
      case 'm':
	maxElem=atoi(optarg);
	break;
      }
    }
  while ((SgmlInputNextRecord()))
    {
      SgmlNode *newList;
      SgmlNode *oldList;
      SgmlNode *elemInput;
      SgmlNode *newClu;
      int n;
      char *key;
      key=SgmlLeafGetData(SgmlGetSonTag(SgmlInputDocument,"k"));
      newClu=(SgmlNode *)StrSearch(clustersTable, key);
      n=maxElem;
      newList=SgmlCreateMark("l");
      if ((oldList=SgmlGetSonTag(SgmlInputDocument,"l"))
	  &&(elemInput=SgmlFirst(oldList)))
	{
	  while (n--)
	    {
	      SgmlNode *elemOutput;
	      SgmlAddSon 
		(newList, 
		 elemOutput=SgmlCreateLeaf
		 ("e",
		  SgmlLeafGetData(SgmlGetSonTag(elemInput,"a"))));
	      SgmlSetAtt( elemOutput, "p", 
			  SgmlLeafGetData(SgmlGetSonTag(elemInput,"f")));
	      if(!(elemInput=SgmlNext(elemInput))) break;
	    }
	}
      SgmlAddSon (newClu,newList);
      SgmlAddSon (newClu,
		  SgmlCreateLeaf
		    ("f",
		     SgmlLeafGetData(SgmlGetSonTag(SgmlInputDocument,"car"))));
				
      SgmlPrint (newClu);
      SgmlFree (newClu);
      putchar ('\n');
    }
  exit (0);
  return 0;
}
