/**********************************************************************
*
*               Projet   : DilibPro
*               Module   : Sgml
*               Fichier  : SgmlCharSetEntity.c
*               Auteur   : J. DUCLOY
*               Date     : Novembre 93
*   $Id: SgmlCharSetEntity.c,v 1.2 2005/06/22 13:09:09 parmentf Exp $
*
***********************************************************************
*
* Copyright (c) 1994 CNRS/CRIN & INRIA Lorraine
* 
***********************************************************************/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "StrSearch.h"
#include "CharSet.h"
#include "SgmlCharSet.h"


SgmlCharSetEntityReductor *SgmlCharSetEntityReductor_Create()
{
  SgmlCharSetEntityReductor *r;

  r=(SgmlCharSetEntityReductor *)malloc(sizeof(SgmlCharSetEntityReductor));
  r->accent=NULL;
  r->trans=NULL;
  r->defaultStr=NULL;
  return r;
}

void SgmlCharSetEntityReductor_SetDefault(SgmlCharSetEntityReductor *r,
					  char *entity)
{
  r->defaultStr=entity;
  return;
}

void SgmlCharSetEntityReductor_AddAccent(SgmlCharSetEntityReductor *r,
					 char *accent)
{
  if(!r->accent)
    {
      r->accent=StrSearchTableCreate(10,2);
    }
  StrSearchAdd(r->accent,accent,"");
  return;
}

void SgmlCharSetEntityReductor_AddTrans(SgmlCharSetEntityReductor *r,
					char *entity, 
					char *target)
{
  if(!r->trans)
    {
      r->trans=StrSearchTableCreate(30,10);
    }
  StrSearchAdd(r->trans,entity,target);
  return;
}

char *SgmlCharSetEntityReductor_Reduce(SgmlCharSetEntityReductor *r,
				       char *entity)
{
  int l;
  char *value;
  l=strlen(entity);
  entity[l-1]='\0';
  
  if ((r->accent)&&(value=StrSearch(r->accent,entity+2)))
    {
      entity[0]=entity[1];
      entity[1]=0;
    }
  else
    {
      if((r->trans)&&(value=StrSearch(r->trans,entity+1)))
	{
	  strcpy(entity,value);
	}
      else
	{
	  if(r->defaultStr)
	    {
	      strcpy(entity,r->defaultStr);
	    }
	  else entity[l-1]=';';
	}
    }
  l=strlen(entity);
  return entity+l;
}

char *SgmlCharSetEntityReductor_Convert(SgmlCharSetEntityReductor *r, char *s)
{
  char *s1;
  static char* s2=NULL;
  char *s3;
  char *s4;
  static int l=0;
  int l1;
  char c;

  if(s)
     {
       s1=s;
       if((l1=strlen(s1)))
	 {
	   if(l1>l)
	     {
	       if(l>0)free(s2);
	       l=l1;
	       s2=malloc(l+1);
	     }
	 }

       s3=s2;
       while((c=*s1++))
	 {
	   *s3++ =c;
	   if(c=='&')
	     {
	       s4=s3-1;
	       while((c=*s1++)&&(c!=';'))*s3++=c;
	       if(c){*s3++=c;*s3=0;}
	       else return NULL;
	       s3=SgmlCharSetEntityReductor_Reduce(r,s4);
	     }
	 }
       *s3='\0';
       return s2;
     }
  return NULL;
}


