#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <string>

#include <libdbox.h>
#include <mtoolrfc.h>
#include <stringtools.h>

void rfcmessaget::copyheaderid(char *dest, const char *id,
                               size_t maxlen) const
 {
  while(maxlen!=0 && *id!=0 && *id!=':' && id<endoffile)
   {
    *dest=*id;
    dest++;
    id++;
    maxlen--;
   }

  *dest=0;
 }

void rfcmessaget::copyheaderid(std::string &dest, const char *id) const
 {
  dest="";
  while(*id!=0 && *id!=':' && id<endoffile)
    dest+=*(id++);
 }

void rfcmessaget::copyheadertext(char *dest, const char *text,
                                 size_t maxlen) const
 {
  bool newline=FALSE;

  while(maxlen!=0 && *text!=0 && text<endoffile)
   {
    if(newline)
     {
      if(!(*text==' ' || *text=='\t'))
        break;

      newline=FALSE;

      if(maxlen!=0)
       {
        *(dest++)=' ';
        maxlen--;
       }
     }

    if(*text=='\n')
      newline=TRUE;
    else if(*text=='\r')
     {
      if((text+1)==endoffile || text[1]!='\n')
        newline=TRUE;
     }
    else if(maxlen!=0)
     {
      *(dest++)=*text;
      maxlen--;
     }

    text++;
   }

  *dest=0;
 }

void rfcmessaget::copyheadertext(std::string &dest, const char *text) const
 {
  bool newline=FALSE;

  dest="";

  while(*text!=0 && text<endoffile)
   {
    if(newline)
     {
      if(!(*text==' ' || *text=='\t'))
        break;

      newline=FALSE;

      dest+=' ';
     }

    if(*text=='\n')
      newline=TRUE;
    else if(*text=='\r')
     {
      if((text+1)==endoffile || text[1]!='\n')
        newline=TRUE;
     }
    else 
      dest+=*text;

    text++;
   }
 }

bool rfcmessaget::parseline(const char **start, 
                            const char **id, 
                            const char **text) const
 {
  const char *d=*start;
  if(*d=='\r' || *d=='\n')
   {
    *id=*text=(char *)NULL;
    if(*d=='\r' && d<endoffile) d++;
    if(*d=='\n' && d<endoffile) d++;
    *start=d;
    return FALSE;
   }

  *id=d;

  if(d==endoffile) return TRUE;

  while(*d!=':')
   {
    if(d==endoffile || *d==0) return TRUE;
    d++;
   }

  d++;
  while(*d==' ' || *d=='\t')
   {
    if(d==endoffile) return TRUE;
    d++;
   }

  *text=d;

  bool newline=FALSE;

  while(TRUE)
   {
    if(d==endoffile || *d==0) return TRUE;

    if(newline && !(*d==' ' || *d=='\t'))
      break;

    newline=FALSE;

    if(*d=='\r')
     {
      if((d+1)==endoffile || d[1]!='\n')
        newline=TRUE;
     }
    else if(*d=='\n')
      newline=TRUE;

    d++;
   }

  *start=d;

  return FALSE;
 }

bool rfcmessaget::parse()
 {
  const char *d=data, *id, *text;

  len=0xffffffff;
  endofmail=endoffile;

  bool error;

  while(TRUE)
   {
    error=parseline(&d, &id, &text);

    headerlen=d-data;
    len=(endoffile-d);

    if(error) return TRUE;

    if(id==NULL) return FALSE;
   }
 }



syntax highlighted by Code2HTML, v. 0.9.1