/************************************************/
/*                                              */
/* File        : spy_local.c                    */
/* Description : Local spy library              */
/*                                              */
/* Author: Sfiligoi Igor                        */
/*                                              */
/* Created      : 21.07.1997                    */
/* Last modified: 17.09.1997                    */
/*                                              */
/************************************************/

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

#include <Error.h>
#include <Circ.h>

#include "spy.h"
#include "spy_local.h"

int spy_open_local(char *keyname,      /* IN : keyname of the Circular buffer */
		   SPY_id *sid)        /* OUT: SPY_id */
{
  *sid = (SPY_id) malloc(sizeof(SPY_id_base));

  (*sid)->spy_type = SPY_TYPE_LOCAL;
  (*sid)->last_event_nr = 0;
  (*sid)->cid = CircOpen(NULL,keyname,0);
  
  if ((*sid)->cid<0)
    {
      free(*sid);
      ErrorSetF(SPY_ERROR_UNKNOWN,"spy_open_local","CircOpen error: %",ErrorGetMessage());
      return SPY_ERROR_UNKNOWN; 
    }
  
  return SPY_ERROR_OK;
}


int spy_close_local(SPY_id sid)
{
  if (CircClose(sid->cid)!=0)
   {
     ErrorSetF(SPY_ERROR_UNKNOWN,"spy_close_local","CircClose error: %",ErrorGetMessage());
     return SPY_ERROR_UNKNOWN; 
   }

  free(sid);
  return SPY_ERROR_OK;
}

int spy_get_local(SPY_id sid,    /* IN : SPY_id returned by spy_open_local */
		  char **buf,    /* OUT: pointer to the data */
                                 /* Should be disposed by the caller */
		  int *bufsize)  /* OUT: buffer size */
{
  char *circ_buf;
  int number = sid->last_event_nr;
  int size;

  circ_buf = CircSearch(sid->cid,&number,&size);
  if (circ_buf==(char*)-1)
    {
      *buf = NULL;
      *bufsize = 0;
      return SPY_ERROR_EMPTY;
    }

  sid->last_event_nr = number;
  *buf = (char *) malloc(size);
  memcpy(*buf,circ_buf,size);
  *bufsize = size;
  
  if (CircCopied(sid->cid,circ_buf)!=0)
    {
     free(*buf);
     *buf = NULL;
     *bufsize = 0;
     ErrorSetF(SPY_ERROR_UNKNOWN,"spy_get_local","CircCopied error: %",ErrorGetMessage());
     return SPY_ERROR_UNKNOWN; 
    }

  return SPY_ERROR_OK;
}