/* PR-QWK - QWK Importer for UMS
 * Copyright (C) 1998 J.Ross Nicoll
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include <exec/memory.h>
#include <exec/types.h>

#include <proto/alib.h>
#include <proto/exec.h>

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

#include "pr-qwk.h"

/* Stuff for prototypes */
#define Prototype extern
#include "PR-QWK-protos.h"

Prototype APTR CallocPoolVec(ULONG, ULONG);
Prototype APTR AllocPoolVec(ULONG);
Prototype APTR ReallocPoolVec(APTR, ULONG);
Prototype STRPTR strdupPoolVec(STRPTR);
Prototype VOID FreePoolVec(APTR);

APTR CallocPoolVec(ULONG size, ULONG num)
{
   APTR ptr = AllocPoolVec((size * num));
   if(ptr != NULL) memset(ptr, 0, (size * num));

   return(ptr);
}

/* ----------------------------------------------------------------------- */

APTR AllocPoolVec(ULONG size)
{
   ULONG newsize = size + 4;
   APTR mem;

   if(size == NULL) return(NULL);

   if (mem = LibAllocPooled(MainPool, newsize))
   {
      *(ULONG *)mem = newsize;
      return((UBYTE *)mem+4);
   }
   return(NULL);
}

/* ----------------------------------------------------------------------- */

APTR ReallocPoolVec(APTR original, ULONG size)
{
   ULONG *mem;
   ULONG oldsize;

   mem = (ULONG *)AllocPoolVec(size);
   if(original == NULL) return(mem);
   if(mem != NULL)
   {
      oldsize = *((ULONG *)original - 1);
      oldsize = oldsize - 4;
      if(oldsize > size) oldsize = size;
      memcpy(mem, original, oldsize);
      FreePoolVec(original);

      return((APTR)mem);
   }
   return(NULL);
}

/* ----------------------------------------------------------------------- */

STRPTR strdupPoolVec(STRPTR original)
{
   STRPTR Output;
   ULONG Length;

   Length = strlen(original);
   Output = (STRPTR)AllocPoolVec(Length + 1);
   if(Output == NULL) return(NULL);
   strcpy(Output, original);

   return(Output);
}

/* ----------------------------------------------------------------------- */

VOID FreePoolVec(APTR mem)
{
   ULONG *temp = mem;

   temp--;
   LibFreePooled(MainPool, temp, *temp);
}
