#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <farstr.h>
#include <dos.h>
#include "sfx.h"
#include "lh.h"
#include "intrface.h"
#include "errmes.h"
#include "disp.h"

struct exe_header {
	ushort	id;
	ushort	last;
	ushort	size;
	ushort	relsize;
	ushort	hdrsize;
	ushort	minalloc;
	ushort	maxalloc;
	ushort	initss;
	ushort	initsp;
	ushort	sum;
	ushort	initip;
	ushort	initcs;
	ushort	reloffset;
	ushort	overlay;
	ushort	dummy0;
	ushort	dummy1;
} exehdr = 
{0x5a4d, (A_endofcode + sizeof(exehdr)) & 0x01ff, 
                 (A_endofcode + sizeof(exehdr) + 0x01ff) / 0x0200, 
                         0x0000, 0x0002, 0x1000, 0xffff, 0xfff0,
 0x0100, 0x0000, 0x0100, 0xfff0, 0x001c, 0x0000, 0x0000, 0x0000};

char nojump[] = "\xeb\x01";

void initsfx(void)
{
	char *p, *q;

	p = getfilename(filename1);
	q = strchr(p, '.');
	if (q) *q = '\0';
	strcpy(filename1, p);
	strcat(filename1, ".EXE");

	extract_internal(NULL, sfx);
	if (flg_x == 0) {
		exehdr.last = (A_endofshort + sizeof(exehdr)) & 0x01ff;
		exehdr.size = (A_endofshort + sizeof(exehdr) + 0x01ff) / 0x0200;
		text[A_subver] = 'S';
		strcpy(&text[A_getopt - 3], nojump);
		*(ushort *)&text[A_seeksize - 2] = A_endofshort + sizeof(exehdr);
		strcpy(&text[A_extended - 3], nojump);	/* memcpy(,,3) */
		strcpy(&text[A_setattr - 3], nojump);
		strcpy(&text[A_autoexec - 3], nojump);
	}
	strcpy(&text[A_myself], filename1);
	fwrite(&exehdr, sizeof(exehdr), 1, file2);
	fwrite(text, flg_x ? A_endofcode : A_endofshort, 1, file2);
}

int copysfx(void)
{
	char *p;
	char c;

	p = &hpb.method[3];
	if (flg_x == 0) hpb.pathname = hpb.filename;
	dispalone("Extract");
	c = *p; *p = ' ';
	if (memcmp(hpb.method, "-lh -", 5) || strchr("045", c) == NULL) {
		eprintf(" : %s\n", METHODERR);
		return 0;
	}
	*p = c;
	hpb.level = 0;
	update_arcstamp();
	makehdr();
	writehdr();
	copyfile(file1, file2, hpb.packed, 0);
	eprintf("\n");
	return 1;
}

void makesfx(char far *bdir)
{
	uint attr;
	int yn;

	fclose(file1);
	far_strcpy(arcname, bdir);
	strcat(arcname, getfilename(filename1));
	strcpy(filename1, arcname);
	if (_dos_getfileattr(arcname, &attr) == 0) {
		yn = 'Y';
		if (flg_m == 0) {
			eprintf("\n%s : %s\n%s", arcname, SAMEFILE, OVERWT);
			yn = getyn();
		}
		if (yn == 'N') {
			fclose(file2);
			remove(filename2);
			file2 = NULL;
		} else {
			if (remove(arcname)) error(RDONLY, arcname);
		}
	}
}
