aboutsummaryrefslogtreecommitdiff
path: root/src/io.c
blob: 8469a6b527e4c1751e01048a6cd354022fe892f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
#include <f65.h>
#include "unalf.h"
#include "addrs.h"

static int headers_read = 0;

static void die_arc(void) {
	fprintf(stderr, "%s: this is an ARC file, not ALF\n", self);
	exit(1);
}

static void die_not_alf(void) {
	fprintf(stderr, "%s: not an ALF file\n", self);
	exit(1);
}

static void eof_junk(void) {
	fprintf(stderr, "%s: junk at EOF (ignoring)\n", self);
}

/* return 1 if a header is read, 0 if not */
int read_alf_header(void) {
	u8 h1, h2;
	int bytes;

	bytes = fread(mem + alf_header, 1, 29, in_file);

	if(!bytes) {
		if(headers_read)
			return 0;
		else
			die_not_alf();
	} else if(bytes < 29) {
		if(headers_read) {
			eof_junk();
			return 0;
		} else {
			die_not_alf();
		}
	}

	h1 = mem[alf_header];
	h2 = mem[alf_hdr_sig];

	if(h1 == 0x1a) {
		if(h2 < 0x0f) die_arc();
		if(h2 == 0x0f) {
			headers_read++;
			return 1; /* signature matches */
		}
	}

	if(headers_read)
		eof_junk();
	else
		die_not_alf();

	return 0;
}

/* read buf_len_l/h bytes into buf_adr_l/h, then store the number
   of bytes actually read in buf_len_l/h. TODO: what about EOF? */
void readblock(void) {
	int bytes, len, bufadr;
	u8 *buf;

	bufadr = dpeek(buf_adr_l);
	buf = mem + bufadr;
	len = dpeek(buf_len_l);

	// fprintf(stderr, "readblock, bufadr = $%04x, len = $%04x\n", bufadr, len);

	bytes = fread(buf, 1, len, in_file);
	dpoke(buf_len_l, bytes);
}

int is_text_file(char *fn) {
	if(globmatch("*.txt", fn)) return 1;
	if(globmatch("*.doc", fn)) return 1;
	if(globmatch("*.lst", fn)) return 1;
	return 0;
}

/* mirror of readblock() */
void writeblock(void) {
	int i, bytes, len, bufadr;
	u8 *buf;
	extern char *out_filename;

	bufadr = dpeek(buf_adr_l);
	buf = mem + bufadr;
	len = dpeek(buf_len_l);

	if(opts.txtconv) {
		if(opts.txtconv > 1 || is_text_file(out_filename))
		for(i = 0; i < len; i++)
			if(buf[i] == 0x9b) buf[i] = '\n';
	}

	// fprintf(stderr, "writeblock, bufadr = $%04x, len = $%04x\n", bufadr, len);

	bytes = fwrite(buf, 1, len, out_file);
	dpoke(buf_len_l, bytes);
}