#include "../fileio/fileglob.h"
#include "globals.h"
#include "cpt.h"
#include "crc.h"

#define NONESEEN	0
#define ESC1SEEN	1
#define ESC2SEEN	2

static int cpt_outstat;
static unsigned char cpt_savechar;

void cpt_rle();
void cpt_rle_lzh();
void outc();

void cpt_wrfile(ibytes, obytes, type)
unsigned long ibytes, obytes;
unsigned short type;
{
    if(ibytes == 0) {
	return;
    }
    cpt_outstat = NONESEEN;
    cpt_inlength = ibytes;
    cpt_outlength = obytes;
    cpt_LZptr = 0;
    if(type == 0) {
	cpt_rle();
    } else {
	cpt_rle_lzh();
    }
    cpt_crc = (*updcrc)(cpt_crc, out_buffer, obytes);
}

void cpt_outch(ch)
unsigned char ch;
{
    cpt_LZbuff[cpt_LZptr++ & (CIRCSIZE - 1)] = ch;
    switch(cpt_outstat) {
    case NONESEEN:
	if(ch == ESC1 && cpt_outlength != 1) {
	    cpt_outstat = ESC1SEEN;
	} else {
	    cpt_savechar = ch;
	    *out_ptr++ = ch;
	    cpt_outlength--;
	}
	break;
    case ESC1SEEN:
	if(ch == ESC2) {
	    cpt_outstat = ESC2SEEN;
	} else {
	    cpt_savechar = ESC1;
	    *out_ptr++ = ESC1;
	    cpt_outlength--;
	    if(cpt_outlength == 0) {
		return;
	    }
	    if(ch == ESC1 && cpt_outlength != 1) {
		return;
	    }
	    cpt_outstat = NONESEEN;
	    cpt_savechar = ch;
	    *out_ptr++ = ch;
	    cpt_outlength--;
	}
	break;
    case ESC2SEEN:
	cpt_outstat = NONESEEN;
	if(ch != 0) {
	    while(--ch != 0) {
		*out_ptr++ = cpt_savechar;
		cpt_outlength--;
		if(cpt_outlength == 0) {
		    return;
		}
	    }
	} else {
	    *out_ptr++ = ESC1;
	    cpt_outlength--;
	    if(cpt_outlength == 0) {
		return;
	    }
	    cpt_savechar = ESC2;
	    *out_ptr++ = ch;
	    cpt_outlength--;
	}
    }
}

