/* lkgb.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "aslink.h"

#define CARTSIZE (32L*1024L)
#define NBSEG 8L
#define SEGSIZE (CARTSIZE/NBSEG)

unsigned char *cart[NBSEG];

VOID gb(int in)
{
	static int first = 1;
	unsigned int pos, chk;
	int i;

	if(first) {
		for(i = 0; i < NBSEG; i++) {
			if((cart[i] = malloc(SEGSIZE)) == NULL) {
				printf("Can't allocate %dth segment of memory (%d bytes)\n", i, (int)SEGSIZE);
				exit(1);
			}
			memset(cart[i], 0, SEGSIZE);
		}
		first = 0;
	}
	if (in) {
		if (hilo == 0)
			pos = rtval[0] | (rtval[1]<<8);
		else
			pos = rtval[1] | (rtval[0]<<8);

		for (i = 2; i < rtcnt ; i++) {
			if(pos < CARTSIZE)
				cart[pos/SEGSIZE][pos%SEGSIZE] = rtval[i];
			pos++;
		}
	} else {
		/* EOF */
		if(ofname != NULL) {
			for(i = strlen(ofname); i > 0 && (isalnum(ofname[i-1]) || ofname[i-1] == '.'); i--)
				;
			for(pos = 0x0134; pos < 0x0144 && ofname[i] && ofname[i] != '.'; pos++, i++)
				cart[pos/SEGSIZE][pos%SEGSIZE] = ofname[i];
			for(; pos < 0x0144; pos++)
				cart[pos/SEGSIZE][pos%SEGSIZE] = 0;
		}
		/* update checksum */
		chk = 0;
		cart[0x014E/SEGSIZE][0x014E%SEGSIZE] = 0;
		cart[0x014F/SEGSIZE][0x014F%SEGSIZE] = 0;
		for(i = 0; i < NBSEG; i++) {
			for(pos = 0; pos < SEGSIZE; pos++) {
				chk += cart[i][pos];
			}
		}
		cart[0x014E/SEGSIZE][0x014E%SEGSIZE] = (chk>>8)&0xFF;
		cart[0x014F/SEGSIZE][0x014F%SEGSIZE] = chk&0xFF;

		for(i = 0; i < NBSEG; i++)
			fwrite(cart[i], 1, SEGSIZE, ofp);
	}
}
