/*************************************************
    FixLZH : Fix an LZH archive (run ScanLZH first!)
    
    Copyright © 1994 Manolis S Pappas.
    All rights reserved.
    
 *************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#define VERSION "1.1"
#define CLI_VERSION "$VER: FixLZH v1.1"

FILE *f1, *f2, *f3;
char name[256], buf[SHRT_MAX];

void main(int argc, char *argv[])
{
	unsigned long start;
	long size;
	char *p;

	if (argc != 4) {
		printf("FixLZH v%s\n",VERSION);
		printf("Copyright (©) 1994-95, The Xperts Group Inc.\n");
                printf("All Rights Reserved Worldwide.\n");
                printf("Author: Manolis S Pappas.\n\n");
		printf("Usage : %s info-file bad-lzh new-lzh\n",argv[0]);
		return;
	}
	strcpy(name, argv[1]);
	f1 = fopen(name, "rt");
	if (f1 == NULL) {
		printf("FixLZH. Copyright © 1994 The Xperts Group. Version %s\n",VERSION);
		printf("Written by Manolis S Pappas. All Rights Reserved.\n");
		printf("\a");
		printf("\nERROR: Info-file '%s' can't open.\n\a", argv[1]);
		return;
	}
	strcpy(name, argv[2]);
	f2 = fopen(name, "rb");
	if (f2 == NULL) {
		strcat(name, ".lzh");
		f2 = fopen(name, "rb");
		if (f2 == NULL) {
			printf("FixLZH. Copyright © 1994 The Xperts Group. Version %s\n",VERSION);
		        printf("Written by Manolis S Pappas. All Rights Reserved.\n");
  			printf("\nERROR: Org-lzh '%s' can't open.\n\a\a", argv[2]);
			return;
		}
	}
	strcpy(name, argv[3]);
	if (strchr(name, '.') == NULL) {
		strcat(name, ".lzh");
	}
	if (fopen(name, "rb")) {
		printf("FixLZH. Copyright © 1994 The Xperts Group. Version %s\n",VERSION);
		printf("Written by Manolis S Pappas. All Rights Reserved.\n");
		printf("\nERROR: New-lzh '%s' already exists.\n\a\a", name);
		return;
	}
	f3 = fopen(name, "wb");
	if (f3 == NULL) {
		printf("FixLZH. Copyright © 1994 The Xperts Group. Version %s\n",VERSION);
		printf("Written by Manolis S Pappas. All Rights Reserved.\n");
		printf("\nERROR: New-lzh '%s' can't open.\n\a\a", name);
		return;
	}
	while (fgets(buf, sizeof(buf), f1)) {
		if (*buf == '=') continue;
		start = strtoul(buf, &p, 16);
		size = strtoul(p, &p, 16) - start;
		if (size <= 0) {
			printf("ERROR: Illegal position : %s\n\a", buf);
			continue;
		}
		fseek(f2, start, SEEK_SET);
		while (size) {
			int l;

			l = (size > sizeof(buf)) ? sizeof(buf) : size;
			fread(buf, l, 1, f2);
			fwrite(buf, l, 1, f3);
			size -= l;
		}
	}
	putc('\0', f3);
	fclose(f3);
	fclose(f2);
	fclose(f1);
}

void do_nothing()
{
        printf("%s",CLI_VERSION);
}
