/*
 * FreeAdhocUDF - copyright (c) 2004 adhoc dataservice GmbH Peter Mandrella
 * based on FreeUDFLibC - copyright (c) 1999 Gregory Deatz
 * altered 2001 by ADITO Software GmbH Robert Loipfinger
 *
 *   blob_functions.h
 *     Blob routines
 *
 *   for exported functions list see math_functions.h
 */

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

#include "global.h"
#include "blob_functions.h"


// pm 21.08.04
char * blobaspchar (struct blob *blob)
{
  char * result;
  long bytes_read, bytes_left, total_bytes_read;

  bytes_read = 0;
  total_bytes_read = 0;

  if (blob->blob_handle == NULL)
    result = (char*) MALLOC(1);
  else
  {
    result = (char*) MALLOC(blob->blob_total_length + 1);
    memset(result,0,blob->blob_total_length + 1);

    bytes_left = blob->blob_total_length;
    while (bytes_left > 0)
    {
      blob->get_segment(blob->blob_handle, result + total_bytes_read,
                        bytes_left, &bytes_read);
      total_bytes_read += bytes_read;
      bytes_left -= bytes_read;
    }
  }

  result[total_bytes_read] = '\0';
  return result;
}


// pm 21.08.04
char * blobleft (struct blob *blob, int *count)
{
  int from = 0;
  return blobmid(blob,&from,count);
}


// pm 21.08.04
char * blobmid (struct blob *blob, int *from, int *count)
{
  int len = blobsize(blob);
  char * result = blobaspchar(blob);
  int f = *from, c = *count;

  while (len>0 && result[len-1]==' ')
    len--;
  result[len] = '\0';


  if (c < 0) c = 0;
  if (f < 0) f = 0;
  else if (f > len) f = len;
  if (f + c > len) c = len - f;

  memmove(result, result + f, c);
  result[c] = '\0';

  return result;
}


// pm 21.08.04
char * blobright (struct blob *blob, int * count)
{
  int f = blobsize(blob) - *count;
  return blobmid(blob, &f, count);
}


// pm 21.08.04
int blobsize (struct blob *blob)
{
  if (blob->blob_handle == NULL)
    return 0;
  else
    return blob->blob_total_length;
}


// pm 21.08.04

// According to IB docs, this is how you do it for blobs.
// First pass the "first" argument
// Second, pass the "return" argument (A Blob) as the last argument.
// then you would just declare the external function in
// IB as shown below

struct blob * strblob (char *str, struct blob *result)
{
  result->put_segment(result->blob_handle, str, strlen(str));
  return result;
}

