/*   -*- coding: utf-8 -*-  */
#include <stdio.h>
#include "SxmlNode.h"
#include "Buffer.h"

SxmlNode *inputDoc;
SxmlNode *personNode;
char *wicriRef;

    int getopt();
    extern char *optarg;

int main (int argc, char **argv)
{
  Buffer *bufIdno;
  int cOption;

  wicriRef=NULL;
  bufIdno=NewBuffer();

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

  while ((inputDoc=SxmlInputNextDocumentElement()))
    {
      SxmlNode *c1;
      SxmlNode *c2;
      SxmlNode *c3;
      char *keyPerson;
      SxmlNode *firstOrg;
      SxmlNode *personNode;
      SxmlNode *inputAffName;
      SxmlNode *c2Item;
      SxmlNode *country;

      c1=SxmlGetFirstChildByTagName(inputDoc,"c1");
      c2=SxmlGetFirstChildByTagName(inputDoc,"c2");
      c3=SxmlGetFirstChildByTagName(inputDoc,"c3");

      if (SxmlIsLeaf(c1))keyPerson=SxmlLeafText(c1);
      else
	{
	  keyPerson=SxmlLeafText(SxmlFirstChild(SxmlFirstChild(c1)));
	}
      if (!(firstOrg=SxmlFirstChild(c3))) continue;

      personNode=SxmlElementCreate("person");
      SxmlAppendChild(personNode, SxmlLeafCreate("name", keyPerson));

      if (wicriRef)
	{
	  SxmlNode *idnoNode;
	  BufferStrcpy(bufIdno,wicriRef);
	  BufferStrcat(bufIdno,":");
	  BufferStrcat(bufIdno,keyPerson);
	  SxmlAppendChild(personNode, idnoNode=SxmlLeafCreate("idno", BufferString(bufIdno)));
	  SxmlSetAttribute(idnoNode, "type", "interwiki");
	}

      if ((country=SxmlGetFirstChildByTagName(c3,"country")))
	{
	  SxmlNode *orgNode;
	  SxmlAppendChild(personNode, orgNode=SxmlElementCreate("org"));
	  SxmlAppendChild(orgNode, SxmlClone(country));
	}
      else
	{
	  SxmlReset (c3);

	  while ((inputAffName=SxmlNextNode(c3)))
	    {
	      SxmlNode *affNode;
	      SxmlNode *orgNameTarget;
	      SxmlListAttributes *lAtt;
	      
	      if (SxmlNodeHasName(inputAffName, "affiliation"))
		{
		  SxmlAppendChild(personNode, affNode=SxmlElementCreate( "affiliation"));
		  SxmlAppendChild(affNode, orgNameTarget=SxmlLeafCreate("orgName", SxmlLeafText(inputAffName)));	     
		  lAtt=SxmlGetListAttributes(inputAffName);
		  if (lAtt)SxmlSetListAttributes(affNode, SxmlClone(lAtt)); 
		}
	    }
	}
      printf ("%s\t", keyPerson);
      SxmlPrint (personNode);
      putchar('\n');
      SxmlReset (c2);
      while ((c2Item=SxmlNextNode(c2)))
	{
	  char *graphPerson;
	  graphPerson=SxmlLeafText(c2Item);
	  printf ("%s\t", graphPerson);
	  SxmlPrint (personNode);
	  putchar('\n');
	}
      SxmlFree(personNode);      
    }
  exit(EXIT_SUCCESS);
}
