/**********************************************************************
*
*  projet   : DilibPro
*  module   : Sgml
*  fichier  : SgmlLineExt.c
*  Auteur   : Jacques DUCLOY
*  Date     : July 94
*
***********************************************************************/
#include "SgmlLineExt.h"
#include "Buffer.h"
#include <string.h>

SgmlLineExtractor *SgmlLineExtractorCreate(l1)
     int l1;
{
  SgmlLineExtractor *ext1;
  ext1=(SgmlLineExtractor *) malloc (sizeof(SgmlLineExtractor));
  ext1->lineLength=l1;
  ext1->hyphenChar='-';
  return ext1;
}

static Buffer *internalString=NULL;

SgmlLineExtractor *SgmlLineExtractorInit(ext1, str1)
     SgmlLineExtractor *ext1;
     char *str1;

{
  ext1->inputString=str1;
  ext1->nextLine=str1;
  if(!internalString)
    internalString= BufferCreate(ext1->lineLength, ext1->lineLength);
  return ext1;
}

char *SgmlLineExtractorComposeLine(ext1,lastSpace)
     SgmlLineExtractor *ext1;
     char *lastSpace;
{
  char *retString;

  if(ext1->hyphenChar&&(*(lastSpace-1)==ext1->hyphenChar))
    {
      retString=BufferStrncpy
	(internalString, 
	 ext1->nextLine,
	 lastSpace-ext1->nextLine);
      ext1->nextLine=lastSpace-1;
   }
else
  {
    retString=BufferStrncpy
      (internalString, 
       ext1->nextLine,
       lastSpace-ext1->nextLine);
    ext1->nextLine=lastSpace+1;
  }
     return retString;
}

char *SgmlLineExtractorNext(ext1)
     SgmlLineExtractor *ext1;
{
  char *lastSpace;
  char *currentPoint;
  char *retString;
  char *posSemiColon;
  char c;
  int lineOffset;

  if((currentPoint=ext1->nextLine))
    {
      lineOffset=0;
      lastSpace=NULL;
      
      while ((c=*currentPoint++))
	{
	  switch(c)
	    {
	    case ' ':
	      lineOffset++;
	      lastSpace=currentPoint-1;
	      break;
	    case '&':
              if((posSemiColon=strchr(currentPoint,';')))
		{
                  lineOffset++;
		  currentPoint=posSemiColon+1;
		}
	      else
		{
		  lineOffset++;
		}
              break;
	    default:
	      lineOffset++;
	      break;
	    }
          if(lineOffset>ext1->lineLength)
	    {
	      if(c==' ')
		{
		  return SgmlLineExtractorComposeLine(ext1,currentPoint-1);
		}
	      else
		{
		  if(lastSpace)
		    {
                      return SgmlLineExtractorComposeLine(ext1,lastSpace);
		    }
		  else
		    {
		      BufferStrncpy
			(internalString, 
			 ext1->nextLine,
			 currentPoint-2-ext1->nextLine);
		      retString=BufferStrcat(internalString,"-");
		      ext1->nextLine=currentPoint-2;
		      return retString;
		    }
		}
	    }
	}
      /* on sort sur fin de chaine */
      retString=ext1->nextLine;
      ext1->nextLine=NULL;
      return(retString);
    }
  else return NULL;
}
