/* Copyright (C) 1995 Aladdin Enterprises.  All rights reserved.
  
  This file is part of Aladdin Ghostscript.
  
  Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author
  or distributor accepts any responsibility for the consequences of using it,
  or for whether it serves any particular purpose or works at all, unless he
  or she says so in writing.  Refer to the Aladdin Ghostscript Free Public
  License (the "License") for full details.
  
  Every copy of Aladdin Ghostscript must include a copy of the License,
  normally in a plain ASCII text file named PUBLIC.  The License grants you
  the right to copy, modify and redistribute Aladdin Ghostscript, but only
  under certain conditions described in the License.  Among other things, the
  License requires that the copyright notice and this notice be preserved on
  all copies.
*/

/* srle.c */
/* RunLengthEncode filter */
#include "stdio_.h"		/* includes std.h */
#include "memory_.h"
#include "strimpl.h"
#include "srlx.h"

/* ------ RunLengthEncode ------ */

private_st_RLE_state();

#define ss ((stream_RLE_state *)st)

/* Initialize */
private int
s_RLE_init(stream_state *st)
{	return s_RLE_init_inline(ss);
}

/* Process a buffer */
private int
s_RLE_process(stream_state *st, stream_cursor_read *pr,
  stream_cursor_write *pw, bool last)
{	register const byte *p = pr->ptr;
	register byte *q = pw->ptr;
	const byte *rlimit = pr->limit;
	byte *wlimit = pw->limit;
	int status = 0;
	ulong rleft = ss->record_left;
	while ( p < rlimit )
	{	const byte *beg = p;
		const byte *p1;
		uint count = rlimit - p;
		byte next;
		if ( count > rleft )
			count = rleft;
		if ( count > 127 )
			count = 127;
		p1 = p + count;
		if ( count > 2 && (next = p[1]) == p[2] && next == p[3] )
		{	if ( wlimit - q < 2 )
			{	status = 1;
				break;
			}
			/* Recognize leading repeated byte */
			p1--;
			do { p++; }
			while ( p < p1 && p[2] == next );
			p++;
			*++q = (byte)(257 - (p - beg));
			*++q = next;
		}
		else
		{	p1 -= 2;
			while ( p < p1 && (p[2] != p[1] || p[3] != p[1]) )
				p++;
			if ( p >= p1 )
				p = p1 + 2;
			count = p - beg;
			if ( wlimit - q < count + 1 )
			{	p = beg;
				status = 1;
				break;
			}
			*++q = count - 1;
			memcpy(q + 1, beg + 1, count);
			q += count;
		}
		rleft -= p - beg;
		if ( rleft == 0 )
			rleft = ss->record_size;
	}
	if ( last && status == 0 && ss->EndOfData )
	  {	if ( q < wlimit )
		  *++q = 128;
		else
		  status = 1;
	  }
	pr->ptr = p;
	pw->ptr = q;
	ss->record_left = rleft;
	return status;
}

#undef ss

/* Stream template */
const stream_template s_RLE_template =
{	&st_RLE_state, s_RLE_init, s_RLE_process, 128, 129
};
