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

   This program merges Pascal and Francis records from Corpus

*/


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

SxmlNode *docInput;
SxmlNode *docMainRecord;
SxPathResult *indexPathNO;
SxPathResult *recordPathIdnoCorpus;

int main ()
{
  indexPathNO=SxPathFirstCompile("inist/server/NO");
  recordPathIdnoCorpus=SxPathFirstCompile("TEI/teiHeader/fileDesc/publicationStmt/idno[@type='wicri:Area/PascalFrancis/Corpus']");
  while ((docInput=SxmlInputNextDocumentElement()))
     {  
       SxmlNode *fNode;
       SxmlNode *lNode;
       SxmlNode *docMainRecord;
       SxmlNode *firstRecord;
       char *f;
       fNode =SxmlGetFirstChildByTagName(docInput,"f");
       lNode =SxmlGetFirstChildByTagName(docInput,"l");
       
       f=SxmlLeafText(fNode);
       if (strcmp(f, "1")==0)
	 {
	   docMainRecord=SxmlFirstChild(SxmlFirstChild(lNode));
	 }
       else 
	 {
	   SxmlNode *inistNO;
	   SxmlNode *otherRecord;
	   SxmlNode *otherNO;
	   SxmlNode *otherIdno;
	   docMainRecord=SxmlFirstChild(SxmlFirstChild(lNode));
	   firstRecord=SxmlFirstChild(SxmlFirstChild(lNode));
	   inistNO=SxPathFirstResultNode(indexPathNO, firstRecord);
	   if (SxmlLeafText(inistNO)[0]=='P')
	     {
	       docMainRecord=firstRecord;
	       otherRecord=SxmlFirstChild(SxmlNextSibling(SxmlParent(firstRecord)));
	     }
	   else
	     {
	       otherRecord=firstRecord;
	       docMainRecord=SxmlFirstChild(SxmlNextSibling(SxmlParent(firstRecord)));
	     }
	   TeiHandlerInit(docMainRecord);
	   otherNO=SxPathFirstResultNode(indexPathNO, otherRecord);
	   TeiAppendIdno("stanalyst", SxmlLeafText(otherNO));
	   otherIdno=SxPathFirstResultNode(recordPathIdnoCorpus, otherRecord);
	   SxmlAppendChild (Tei_publicationStmt, SxmlClone(otherIdno));
	 }
       SxmlPrint(docMainRecord);
       putchar('\n');
     }
  exit (EXIT_SUCCESS);
}
