#include<stdio.h>
#include"xjump.h"

#define LOG_MAX	65536

static unsigned char Log_data[LOG_MAX];

static unsigned char *Wrptr;
static unsigned char *Rdptr;

static log_t *Last_log;

static int Prev;
static int Count;
static int Size;

void LOG_init( void )
{
  Wrptr = Log_data;
}

void LOG_start_write( log_t *p )
{
  Prev = 0;
  Count = 1;
  Size = 0;
  p->data = Wrptr;
  Last_log = p;
}

void LOG_start_read( log_t *p )
{
  Rdptr = p->data;
  Prev = 0;
  Count = 0;
  Size = 0;
  (void)LOG_read();
}


int LOG_write( int key )
{
  if( Size == LOG_MAX )
    return Size;

  if( key != Prev || Count == 32 ){
    *Wrptr++ = Prev << 5 | (Count-1);
    Size++;
    if( Wrptr >= Log_data + LOG_MAX )
      Wrptr = Log_data;
    Prev = key;
    Count = 1;
  }else{
    Count++;
  }
  return Size;
}

int LOG_read( void )
{
  if( Size == LOG_MAX )
    return 0;

  if( Count-- == 0 ){
    Prev = *Rdptr >> 5;
    Count = *Rdptr & 31;
    Rdptr++;
    Size++;
    if( Rdptr >= Log_data + LOG_MAX )
      Rdptr = Log_data;
  }
  return Prev;
}


void LOG_check_broken( log_t *p )
{
  unsigned char *sa;

  if( p == Last_log )
    return;

  if( !p->floor )
    return;

  sa = p->data > Last_log->data ? p->data : p->data + LOG_MAX;
  if( sa < Last_log->data + Size )
    p->floor = 0;
}
