/*
 *         bpack - A Burrows-Wheeler Transform and Huffman Encoding
 *                            Implementation
 *
 *  Copyright (C) 2006      Angelo Arrifano <miknix@gmail.com>
 *  Copyright (C) 2006      Vasco Costa <the_papon@hotmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "rle.h"

int rle_encode(unsigned char *ibuffer, unsigned char *obuffer, int size){
	int i=0, j, k, o=0;
	
	if(size<3) return(size);
	do{
		if(ibuffer[i] == ibuffer[i+1]){
			obuffer[o++]=ibuffer[i++];
			obuffer[o++]=ibuffer[i];
			k=0;
			j=i++;
			while(k<256 && i<size && ibuffer[i]==ibuffer[j]){
				k++; i++;
			}
			obuffer[o++]=k;
		}else{
			obuffer[o++]=ibuffer[i++];
		}
	}while((i+1) < size);
	if(i < size) obuffer[o++]=ibuffer[i];
	return(o);
}
