/*   -*- coding: utf-8 -*-  */

/**********************************************************************
*
*  module   : Nlm
*  fichier  : NlmNcbiFindNew.c 
*  Auteur   : Jacques DUCLOY
*  Date     : mars 2020
*
***********************************************************************/

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>
#include "SxPath.h"
#include "HfdIndex.h"

    int getopt();
    extern char *optarg;

SxmlNode *docInput;

SxPathResult *teiPathPublicationStmt;
SxmlNode *inputPublicationStmt;
char *backArea;

int main (int argc, char **argv)
{
  int cOption;
  HfdIndex  *indexBackRbid;
  Buffer    *bufPath;

  while((cOption=getopt(argc,argv,"b:"))!=EOF)
    {switch (cOption)
        {
	case 'b' :
	  backArea=optarg;
          break;
	}
    }

  bufPath=BufferFromString(backArea);
  BufferStrcat(  bufPath, "/Data/Main/Exploration/RBID.i");
  indexBackRbid=HfdIndexOpenRead(BufferString(bufPath));

  teiPathPublicationStmt=SxPathFirstCompile("TEI/teiHeader/fileDesc/publicationStmt");

  while ((docInput=SxmlInputNextDocumentElement()))
     { 
       SxmlNode *rbidNode;
       char *rbid;
       char *pmcRbid;
       char *pubmedRbid;
       pmcRbid=NULL;
       pubmedRbid=NULL;
       inputPublicationStmt=SxPathFirstResultNode(teiPathPublicationStmt, docInput);
       rbidNode=SxmlGetFirstChildTagAtt(inputPublicationStmt, "idno", "type", "RBID");
       while (rbidNode)
	 {
	   rbid=SxmlLeafText(rbidNode);
	   if (strncmp(rbid,"PMC:",4)==0) pmcRbid=rbid;
	   else if (strncmp(rbid,"pubmed:",7)==0) pubmedRbid=rbid;
	   rbidNode=SxmlGetNextSiblingTagAtt(rbidNode, "idno", "type", "RBID");
	 }
       if (pmcRbid || pubmedRbid)
	 {
	   if (pmcRbid) 
	     {
	       if (HfdIndexReadSxml(indexBackRbid, pmcRbid)) continue;
	     }
	   if (pubmedRbid) 
	     {
	       if (HfdIndexReadSxml(indexBackRbid, pubmedRbid)) continue;
	     }
	   SxmlPrint( docInput);
	   putchar('\n');
	 }
     }
  exit(EXIT_SUCCESS);
}
