#include "stdio.h"
#include "stdlib.h"
#include "ctype.h"
#include "string.h"

void error(char *s) {
	while(*s) putchar(*s++);
	putchar('\n');
	exit(1);
}

FILE *fopene(char *s, char *mode) {
	FILE *a;
	if((a = fopen(s, mode)) == NULL) {
		printf("Nemohu otevrit %s", s);
		exit(1);
	}
	return(a);
}

FILE *in, *out;

char header[282] = { 0x5a, 0x1a };

void rlb(int o) {
	header[o] = getc(in);
}

void rlw(int o) {
	header[o++] = getc(in);
	header[o] = getc(in);
}

void passw(void) {
	getc(in);
	getc(in);
}

void passb(void) {
	getc(in);
}

long getl(void) {
	long l;
	l  = getc(in) << 24;
	l |= getc(in) << 16;
	l |= getc(in) << 8;
	l |= getc(in);
	return(l);
}

void main(int argc, char **argv) {
	int a, c, dbl, rdbl;
	long l;
	printf("Konverze textu MAT2.0 -> MAT1.2 (c) 1992 CYBEX spol. s. r.o.\n");
	if(argc != 3)
		error("Pouziti: K12 vstupni_soubor vystupni_soubor");
	in   = fopene(argv[1], "rb");
	out  = fopene(argv[2], "wb");
	passw();
	passw();
	passb();
	rlb(3);
	passb();
	rlb(5);
	passb();
	rlb(7);
	passb();
	header[8] = 60;
	rlb(9);
	rlw(10);
	for(a = 0; a < 256; a++) header[a + 12] = getc(in);
	rlb(268);
	rlb(269);
	rlb(270);
	rlb(271);
	rlb(272);
	rlb(273);
	l  = getl();
	l += getl();
	l += getl();
	l += getl();
	passw();
	passw();
	passw();
	rlw(280);
	a  = getc(in) << 8;
	a |= getc(in);
	while(a--) getc(in);
	for(a = 0; a < 282; a++) putc(header[a], out);
	while(l--) getc(in);
	dbl = rdbl = 0;
	while((c = getc(in)) != EOF) {
		if(c == 6) for(a = 95; a--;) getc(in);
		else
		if(c == 8) getc(in);
		else
		if(c == 23) rdbl = !rdbl;
		else
			if(!rdbl && c != 21) {
				putc(c, out);
				if(c >= 32 && dbl) {
					putc(22, out);
					putc(23, out);
					putc(c,  out);
					putc(22, out);
					putc(23, out);
				}
				if(c == 22) dbl = 1;
				if(c == 10) rdbl = dbl = 0;
			}
	}
}