#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* INJECTA by Nathan Cross '08
** inject sound into bottom couple of character rows of a bmp2scr video,
** specifically Girls Aloud's 'Something Kinda Oooh'. Yes, really. */

int main(int argc, char *argv[])
{

	FILE *vid;
	FILE *snd;
	FILE *out;
	
	int fc			= 0;
	unsigned char checksum	= 0;
	unsigned char flags;
	unsigned char buffer;
	unsigned char bigbuf[32];
	char string[256];
	char number[256];
	int addr;
	int xctr,tctr;
	
	unsigned char databuffer[6144];
	int ctr;
	int total;

	printf("Started\n");
	
	vid = fopen("video\\zx_ga_sko.tap", "rb");
	out = fopen("video\\output.tap", "wb");

	if(vid==NULL) {
		printf("Couldn't open vid\n");
	}
	if(out==NULL) {
		printf("Couldn't open out\n");
	}
	while(fc < 4838) { // 4838
	
/*	# 6937 intervals
	#  6912 bytes of data
	#  4 bytes of checksum (6916, leaves 21 for header info)
	#  Our sound data goes in at 5632 from the data block, which is 5636 bytes from the start of the data
	# 6421 is 6937-4-512
	# Checksum needs to be from byte 18 in onward, all XORed...
	# 19+5632 = 5651
*/	
		total = 0;
		// Copy header
		fread(&bigbuf, 1, 23, vid);
		fwrite(&bigbuf, 1, 23, out);
		total+=23;
		
		// Copy flags
		fread(&flags, 1, 1, vid);
		fwrite(&flags, 1, 1, out);
		total++;

	// Set checksum	
		checksum	= flags;
	// Read pixel data
		for(ctr=0; ctr<6144; ctr++) {
			fread(&databuffer[ctr], 1, 1, vid);
		}

	// Read and add sound data to pixel data
		strcpy(string, "output\\raw_");
		itoa(fc, number, 10);
		strcat(string, number);
		strcat(string, ".ay");
		snd = fopen(string, "rb");
		addr = 4288;
		xctr = 0;
		for(tctr=0;tctr<221;tctr++) {
			fread(&buffer, 1, 1, snd);
			databuffer[addr] = buffer;
			addr++;
			xctr++;
			if(xctr==64) {
				xctr=0;
				addr+=192;
			}
		}
		fclose(snd);

	// Write updated screen pixel data
		for(ctr=0; ctr<6144; ctr++) {
			fwrite(&databuffer[ctr], 1, 1, out);
			total++;
			checksum ^= databuffer[ctr];
		}

	// Copy attribute data		
		for(ctr=0; ctr<6848-6144; ctr++) {
			fread(&buffer, 1, 1, vid);
			checksum ^= buffer;
			fwrite(&buffer, 1, 1, out);
			total++;
		}
	// Black out the bottom two lines of attribute data
		for(ctr=0; ctr<6912-6848; ctr++) {
			fread(&buffer, 1, 1, vid);
			buffer = 0;
			fwrite(&buffer, 1, 1, out);
			checksum ^= buffer;
			total++;
		}
		
		// Now to output the checksum and hope it's right.
		fread(&buffer, 1, 1, vid);
		fwrite(&checksum, 1, 1, out);
		total++;
//		if(checksum != buffer) {
//			printf("Loop %i: checksum is %i, buffer is %i\n", fc, checksum, buffer);
//		}
		if(total!=6937) {
			printf("Total is %i\n",total);
		}
		fc++;
	}

	fclose(out);
	fclose(vid);

// Temp: audio is at 22016, 221 bytes long
    return 0;
}
