#include <exec/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dlg/msg.h>
#include <proto/dlg.h>
#include <proto/dos.h>

#include <link/util.h>

#include <pragmas/dlg.h>

extern struct Library *DLGBase;

BOOL MakeBody(char *sourcefile,char *destfile,char *prebuff,char *transarray,
  char **dbody)
{
unsigned char *sbody=NULL,temp;
char copyflag=TRUE,*tdbody;
int extrabuff=0;
ULONG msgsize;
long scounter,dcounter;

if(FileSize(sourcefile,&msgsize)==-1)
  {
  return(FALSE);
  }

/* Calculate length of pre buffer */

if(prebuff)
  extrabuff+=strlen(prebuff);

if(*dbody)
  free(*dbody);

if(!(*dbody=(char *)malloc(msgsize-(long)sizeof(struct Msg_Header)+
  1L+(long)extrabuff+320L)))
  {
  return(FALSE);
  }

tdbody=*dbody;

if(!FileToBuf(&sbody,sourcefile,msgsize,1L,(long)sizeof(struct Msg_Header)))
  return(FALSE);

copyflag=TRUE;
dcounter=0L;

if(prebuff)
  {
  strcpy(tdbody,prebuff);
  dcounter+=(long)strlen(prebuff);
  }

for(scounter=0L;sbody[scounter]!='\0';scounter++)
  {

  if(transarray)
    {
    temp=transarray[sbody[scounter]];
    sbody[scounter]=temp;
    }

  if(sbody[scounter]==1)
    {
    copyflag=FALSE;
    continue;
    }
  if(copyflag==FALSE && (sbody[scounter]==10 || sbody[scounter]==13))
    {
    copyflag=1;
    continue;
    }
  if(sbody[scounter]==10 || sbody[scounter]==13)
    {
    if((!strncmp(sbody+scounter+1,"--- ",4)) || (!strncmp(sbody+scounter+2,
      "--- ",4)) || (!strncmp(sbody+scounter+3,"--- ",4)))
      {
      long tcounter;

      tcounter=scounter+3;
      while(1)
        {
        if(sbody[tcounter]==10 || sbody[tcounter]==13)
          {
          if((!strncmp(sbody+tcounter+1," * Origin:",10)) ||
            (!strncmp(sbody+tcounter+2," * Origin:",10)) || 
            (!strncmp(sbody+tcounter+3," * Origin:",10)))
            {
            copyflag=2;
            break;
            }
          break;
          }
        tcounter++;
        if(sbody[tcounter]=='\0')
          break;
        }
      }
    }
  if(copyflag)
    {
    tdbody[dcounter]=sbody[scounter];
    dcounter++;
    }
  if(copyflag==2)
    break;
  }

tdbody[dcounter]='\0';

/* Write the destination buffer to a file if one exists */

if(destfile)
  {
  BPTR fh;

  DeleteFile(destfile);
  if(fh=Open(destfile,MODE_NEWFILE))
    {
    Write(fh,tdbody,dcounter);
    Close(fh);
    }
  }

return(TRUE);
}
