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

SxmlNode *inputDoc;
SxmlNode *figureNode;
char *implicitOffset;
Buffer *bufLat;

    int getopt();
    extern char *optarg;

int main (int argc, char **argv)
{
  int cOption;
  
  bufLat=NewBuffer();
  implicitOffset="se";

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

  while ((inputDoc=SxmlInputNextDocumentElement()))
    {
      SxmlNode *c1;
      SxmlNode *c2;
      char *keyFigure;
      SxmlNode *figureNode;
      SxmlNode *linkNode;
      SxmlNode *inputHeadNode;
      SxmlNode *inputGeoNode;
      SxmlNode *headNode;
      SxmlNode *geoNode;

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

      keyFigure=SxmlLeafText(SxmlFirstChild(SxmlFirstChild(c1)));
      printf ("%s\t", keyFigure);

      figureNode=SxmlElementCreate("figure");
      SxmlAppendChild(figureNode, linkNode=SxmlElementCreate("link"));
      SxmlElementSetEmpty(linkNode);
      SxmlSetAttribute(linkNode,"target",keyFigure);

      inputGeoNode=SxmlGetFirstChildByTagName(c2,"geo");

      if ((inputHeadNode=SxmlGetFirstChildByTagName(c2,"head")))
	{
	  headNode=SxmlClone(inputHeadNode);
	}
      else
	{
	  headNode=SxmlLeafCreate("head", keyFigure);
	}
      SxmlAppendChild(figureNode,headNode);
      if (!(SxmlGetAttribute(headNode,"offset")))
	SxmlSetAttribute(headNode,"offset", implicitOffset);

      if(inputGeoNode)
	{
	  char *posSpace;
	  char *coord;
	  geoNode=SxmlClone(inputGeoNode);
	  SxmlAppendChild(figureNode, geoNode);
	  coord=SxmlLeafText(inputGeoNode);
	  posSpace=strchr(coord, ' ');
	  BufferStrncpy(bufLat, coord, posSpace-coord);

	  SxmlSetAttribute(geoNode,"latitude", BufferString(bufLat));
	  SxmlSetAttribute(geoNode,"longitude", posSpace+1);

	}

      SxmlPrint (figureNode);
      SxmlFree(figureNode);
      putchar('\n');
      
    }
  exit(EXIT_SUCCESS);
}
