/*******************************************************/
/*                                                     */
/* File        : spy_ybos.c                            */
/* Description : Spy simulation from YBOS file library */
/*                                                     */
/* Author: Sfiligoi Igor                               */
/*                                                     */
/* Created      : 10.09.1998                           */
/* Last modified: 14.12.1998                           */
/*                                                     */
/*******************************************************/

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

#include <Error.h>
#include <cybos.h>

#include "spy_ybos.h"

#define SPY_YBOS_SLOTS   16

static pcybos spy_cybos_ids[SPY_YBOS_SLOTS] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
					       NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};

int spy_open_ybos(char *filename,      /* IN : filename of the YBOS file */
		  SPY_ext_id *sid)     /* OUT: SPY_id */
{
  int cybos_id_idx;;

  for (cybos_id_idx=0; (cybos_id_idx<SPY_YBOS_SLOTS) && (spy_cybos_ids[cybos_id_idx]!=NULL); cybos_id_idx++);

  if (cybos_id_idx>=SPY_YBOS_SLOTS) 
    {
      ErrorSetF(SPY_ERROR_UNKNOWN,"spy_open_ybos","No more free cybos_ids");
      return SPY_ERROR_UNKNOWN;
    }

  spy_cybos_ids[cybos_id_idx] = cybos_open(filename);
  
  if (spy_cybos_ids[cybos_id_idx]==NULL)
    {
      ErrorSetF(SPY_ERROR_UNKNOWN,"spy_open_ybos","cybos_open error: %s",ErrorGetMessage());
      return SPY_ERROR_UNKNOWN;
    }

  *sid = (SPY_ext_id) malloc(sizeof(SPY_ext_id_base));

  (*sid)->spy_type = SPY_TYPE_YBOS;
  (*sid)->last_event_nr = 0;
  (*sid)->cid = cybos_id_idx;
  
  return SPY_ERROR_OK;
}


int spy_close_ybos(SPY_ext_id sid)
{
  cybos_close(spy_cybos_ids[sid->cid]);
  spy_cybos_ids[sid->cid] = NULL;

  free(sid);
  return SPY_ERROR_OK;
}

int spy_get_ybos(SPY_ext_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 */
{
  int size;
  int lrec_size;

  lrec_size = cybos_read(spy_cybos_ids[sid->cid],NULL,0);
  if (lrec_size==0)
    return SPY_ERROR_EMPTY;

  if (lrec_size<=0)
    {
      ErrorSetF(SPY_ERROR_UNKNOWN,"spy_get_ybos","cybos_read error: %s",ErrorGetMessage());
      return SPY_ERROR_UNKNOWN;
    }

  *bufsize = (lrec_size+2)*sizeof(int);
  *buf = malloc(*bufsize);
  ((int *) (*buf))[0] = 1;                     /* Only one logical record*/
  ((int *) (*buf))[1] = lrec_size*sizeof(int); /* size (in bytes) of the logical record */
  size = cybos_read(spy_cybos_ids[sid->cid],
		    &(((int *) *buf)[2]),
		    lrec_size);

  if ((lrec_size)!=size)
    {
      free(*buf);
      ErrorSetF(SPY_ERROR_UNKNOWN,"spy_get_ybos","cybos_read error: %s",ErrorGetMessage());
      return SPY_ERROR_UNKNOWN;
    }

  return SPY_ERROR_OK;
}