aboutsummaryrefslogtreecommitdiff
path: root/unprotbas.c
blob: 3486ac4a0669a0f9e06df6de919be2b1448bcb3e (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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

/* attempt to fix a "list-protected" Atari 8-bit BASIC program.
	we don't fully detokenize, so this won't fix truly corrupted
	files.

	the "fix" is in 2 parts:
	1. fix any invalid (0-byte) offsets after a line number. this is
	   what causes BASIC to lock up.
	2. if the variable names were overwritten (e.g. with EOL characters,
	   or whatever), we "fix" that by making up new variable names.
*/

/* maximum size of the program in memory. 64KB is actually way overkill. */
#define BUFSIZE 65536

/* the difference between the VVTP and VNTP values in the file, and the
	actual file positions of the variable names and values. */
#define TBL_OFFSET 0xf2

/* minimum program size, for a program that has no variables and
	only one line of code (the immediate line 32768, consisting only of
	one token, which would be CSAVE). anything smaller than this, we
	can't process. */
#define MIN_PROG_SIZE 21

/* maximum practical size for a BASIC program. if a file exceeds this
	size, we warn about it, but otherwise process it normally.
	this value is derived by subtracting the default LOMEM without DOS
	($0700) from the start of the display list in GR.0 ($9c20, on a 48K Atari).
 */
#define MAX_PROG_SIZE 38176

/* maximum number of variables in the variable name and value tables. this
	could be 128, but "ERROR- 4" still expands the tables. Entries >128
	don't have tokens, can't be referred to in code, but we'll preserve
	them anyway. */
#define MAXVARS 256

/* tokenized colon (statement separator) */
#define TOK_COLON 0x14

/* variable types, bits 6-7 of byte 0 of each vvtable entry. */
#define TYPE_SCALAR 0
#define TYPE_ARRAY  1
#define TYPE_STRING 2

/* entire file gets read into memory (for now) */
unsigned char data[BUFSIZE];

/* for the -p/-pc options: 32767 END */
unsigned char badcode[] = {
	0xff, 0x7f,   /* line number 32767      */
	0x00,         /* *bad* next-line offset */
	0x06,         /* next-statement offset  */
	0x15,         /* END token              */
	0x16,         /* end-of-line token      */
};

/* for -p/-pv */
int varname_char = 0x9b;

/* for -s */
int shrinktable = 0;

/* for the -r option */
#define MAP_FILE "varnames.txt"
unsigned char varnames[BUFSIZE];
unsigned char *varmap[MAXVARS];
int varmap_count;

/* BASIC 14-byte header values */
unsigned short lomem;
unsigned short vntp;
unsigned short vntd;
unsigned short vvtp;
unsigned short stmtab;
unsigned short stmcur;
unsigned short starp;

/* positions where various parts of the file start,
	derived from the header vars above. */
unsigned short codestart;
unsigned short code_end;
unsigned short vnstart;
unsigned short vvstart;
int filelen;

/* name of executable, taken from argv[0] */
char *self;

/* these are set by the various command-line switches */
int keepvars = 0;
int forcevars = 0;
int keepgarbage = 1;
int checkonly = 0;
int was_protected = 0;
int verbose = 0;
int readmap = 0;
int writemap = 0;
int protect_vars = 0;
int protect_code = 0;

/* file handles */
FILE *input_file = NULL;
FILE *output_file = NULL;
char *output_filename = NULL;

void die(const char *msg) {
	fprintf(stderr, "%s: %s\n", self, msg);
	exit(1);
}

/* read entire file into memory */
int readfile(void) {
	int got = fread(data, 1, BUFSIZE - 1, input_file);
	if(verbose) fprintf(stderr, "Read %d bytes.\n", got);
	if(!feof(input_file))
		fprintf(stderr, "Warning: file is >64KB, way too big for a BASIC program.\n");
	else if(got > MAX_PROG_SIZE)
		fprintf(stderr, "Warning: file is %d bytes, suspiciously large for a BASIC program.\n", got);
	fclose(input_file);
	if(got < MIN_PROG_SIZE)
		die("File too short to be a BASIC program (truncated?)\n");
	return got;
}

/* get a 16-bit value from the file, in 6502 LSB/MSB order. */
unsigned short getword(int addr) {
	return data[addr] | (data[addr + 1] << 8);
}

void setword(int addr, int value) {
	data[addr] = value & 0xff;
	data[addr + 1] = value >> 8;
}

void dump_header_vars(void) {
	fprintf(stderr, "LOMEM  $%04x    VNTP $%04x   VNTD $%04x  VVTP $%04x\n", lomem, vntp, vntd, vvtp);
	fprintf(stderr, "STMTAB $%04x  STMCUR $%04x  STARP $%04x\n", stmtab, stmcur, starp);
	fprintf(stderr, "vnstart $%04x, vvstart $%04x, codestart $%04x, code_end $%04x\n", vnstart, vvstart, codestart, code_end);
}

void parse_header(void) {
	lomem = getword(0);
	vntp = getword(2);
	vntd = getword(4);
	vvtp = getword(6);
	stmtab = getword(8);
	stmcur = getword(10);
	starp = getword(12);
	codestart = stmtab - TBL_OFFSET - (vntp - 256);
	vnstart = vntp - TBL_OFFSET;
	vvstart = vvtp - TBL_OFFSET;
	code_end = starp - TBL_OFFSET;

	if(filelen < code_end) {
		fprintf(stderr, "Warning: file is truncated: %d bytes, should be %d.\n", filelen, code_end);
	}

	if(verbose) dump_header_vars();
}

void update_header(void) {
	setword(0, lomem);
	setword(2, vntp);
	setword(4, vntd);
	setword(6, vvtp);
	setword(8, stmtab);
	setword(10, stmcur);
	setword(12, starp);
}

/* fixline() calculates & sets correct line length, by iterating
	over the statement(s) within the line. the last statement's
	offset will be the same as the line offset should have been,
	if it weren't zeroed.  when reading this code, it's helpful to
	know that the lengths (line and statement) are counted from the
	start of the line in memory.

	A line with only a line number and one token (such as END) would have a
	line length of 6: 2 for the 16-bit line number, 1 for the length byte
	itself, 1 for the statement length byte (also 6), 1 for the END token, and one
	for the end-of-line token.

	A line with two statements: 10 ?:END
	offset   value   meaning
	0        0A      line number (low byte)
	1        00      line number (high byte)
	2        09      line length (or, offset to next line) [!]
	3        06      offset to next statement *from the start of the line*
	4        28      token for "?"
	5        14      token for : (end of statement), we call it TOK_COLON
	6        09      offset to next statement [!]
	7        15      token for END
	8        16      token for end-of-line [*]
	9        ??      (line number of next statement)

	Note the values marked with [!] are equal.
	The line length at offset 2 is what gets zeroed out by the
	protection. To fix it, we follow the next-statement offsets. If
	there's not a colon before the offset, replace the byte at
	offset 2 with that statement's offset.

	[*] end-of-line is $16 *except* for REM and DATA, which are
	    terminated with $9B instead.
*/
int fixline(int linepos) {
	/* +3 here to skip the line number + line length */
	int offset = data[linepos + 3];

	while(data[linepos + offset - 1] == TOK_COLON)
		offset = data[linepos + offset];

	data[linepos + 2] = offset;
	return offset;
}

/* Iterate over all the tokenized lines. If any of them have invalid
	line lengths (<=5), call fixline() on them. */
int fixcode(void) {
	int result = 0;
	int pos = codestart;
	int offset, lineno = -1, tmpno;

	while(pos < filelen) {
		tmpno = getword(pos);
		if(tmpno <= lineno) {
			fprintf(stderr, "Warning: line number %d at offset $%04x is <= previous line number %d.\n",
					tmpno, pos, lineno);
		}
		lineno = tmpno;

		offset = data[pos + 2];
		/* fprintf(stderr, "pos %d, line #%d, offset %d\n", pos, lineno, offset); */
		if(offset < 6) {
			if(verbose) fprintf(stderr, "Found invalid offset %d (<6) at line %d, file offset $%04x.\n", offset, lineno, pos);
			offset += fixline(pos);
			result++;
		}
		pos += offset;

		/* Atari BASIC tolerates garbage after the last tokenized line,
			so we must do likewise. */
		if(lineno == 32768) break;
	}

	if(verbose) fprintf(stderr, "End program file offset: $%04x/%d\n", pos, pos);

	if(filelen > pos) {
		int i, same = 1;
		for(i = pos; i < filelen; i++) {
			if(data[i] != data[pos]) same = 0;
		}
		if(verbose) {
			fprintf(stderr, "Trailing garbage at EOF, %d bytes, ", filelen - pos);
			if(same)
				fprintf(stderr, "all $%02x", data[pos]);
			else
				fprintf(stderr, "maybe valid data");
			fprintf(stderr, ", %s.\n", (keepgarbage ? "keeping" : "removing"));
		}
		if(!keepgarbage) filelen = pos;
	} else {
		if(verbose)
			fprintf(stderr, "No trailing garbage at EOF.\n");
	}
	return result;
}

/* iterate over all the lines, insert a poisoned line 32767 just
	before line 32768 */
void breakcode(void) {
	int pos = codestart, oldpos = 0;
	int offset, lineno = -1, tmpno = -1;

	while(pos < filelen) {
		lineno = tmpno;
		tmpno = getword(pos);
		if(tmpno == 32768) {
			break;
		} else {
			offset = data[pos + 2];
			if(!offset) {
				fprintf(stderr, "%s: program already was code-protected.\n", self);
				exit(2);
			}
			oldpos = pos;
			pos += offset;
		}
	}

	if(!oldpos) die("Can't protect code because there are no lines of code.");
	if(lineno == 32767) die("Can't protect code because there is already a line 32767.");

	/* pos is now the start of line 32768, move it up to make room for
		the new line */
	offset = sizeof(badcode);
	memmove(data + pos + offset, data + pos, filelen);

	/* insert new line */
	memmove(data + pos, badcode, offset);

	if(verbose)
		fprintf(stderr, "Inserted line 32767 with invalid offset at file offset $%04x.\n", pos);

	/* update pointers that would be affected by the code move */
	stmcur += offset;
	starp += offset;
	update_header();
	parse_header();
	filelen += offset;
}

/* sometimes the variable name table isn't large enough to hold
	the generated variable names. move_code() makes more space,
	by moving the rest of the program (including the variable value
	table) up in memory. */
void move_code(int offset) {
	unsigned char *dest = data + vvstart + offset;

	if(dest < data || ((filelen + offset) > (BUFSIZE - 1))) {
		die("Attempt to move memory out of range; corrupt header bytes?\n");
	}

	memmove(dest, data + vvstart, filelen);

	vntd += offset;
	vvtp += offset;
	stmtab += offset;
	stmcur += offset;
	starp += offset;
	update_header();
	parse_header();
	filelen += offset;
}

/* Fixing the variables is a bit more work than it seems like
	it might be, because the last byte of the name has to match
	the type (inverse video "(" for numeric array, inverse "$" for
	string, inverse last character of name for scalars). To do
	this right, we have to examine the variable value table to
	find out the type of each variable.

	Each variable type get assigned A to Z, then A1 to A9, B1 to B9,
	etc. This means there will be A, A$, and A( variables, which might
	be a bit confusing, but we have to keep the generated name table as
	short as possible, because we can't extend the size of the table in
	the file.

	We can find the actual table size in the file by subtracting VNTP
	(start of variable name table) from VNTD (end of variable name table).
	It's possible that the table size is too small for the generated
	variable names, in which case we have to call move_code() to
	make more room.

	The maximum number of variable names is 128. If all 128 vars are in
	use, the minimum table size is 230 (26 one-letter names, 102 2-letter
	or letter+number or one-letter string/array names).
*/

/* return true if the variable name table is OK */
int vntable_ok(void) {
	int vp, bad;

	if(vntp == vntd) {
		if(verbose) fprintf(stderr, "No variables.\n");
		return 1;
	}

	/* first pass: bad = 1 if all the bytes in the table have the same
		value, no matter what it is. */
	vp = vnstart + 1;
	bad = 1;
	while(vp < vvstart - 1) {
		if(data[vp] != data[vnstart]) {
			bad = 0;
			break;
		}
		vp++;
	}
	if(bad) return 0;

	/* 2nd pass: bad = 1 if there's any invalid character in the table. */
	vp = vnstart;
	while(vp < vvstart) {
		unsigned char c = data[vp];

		/* treat a null byte as end-of-table, ignore any junk between it and VNTP. */
		if(c == 0) break;

		vp++;

		/* inverse $ or ( is OK */
		if(c == 0xa4 || c == 0xa8) continue;

		/* numbers and letters are allowed, inverse or normal. */
		c &= 0x7f;
		if(c >= 0x30 && c <= 0x39) continue;
		if(c >= 0x41 && c <= 0x5a) continue;

		bad++;
		break;
	}

	return !bad;
}

/* walk the variable value table, generating variable names.
	if write is 0, just return the size the table will be.
	if write is 1, actually write the names to memory. */
int rebuild_vntable(int write) {
	int vp = vnstart;
	int vv = vvstart;
	int size = 0;
	int strings = 0, arrays = 0, scalars = 0, varname = 0, varnum = 0;

	while(vv < codestart) {
		unsigned char sigil = 0;
		/* type: scalar = 0, array = 1, string = 2 */
		unsigned char type = data[vv] >> 6;
		/* fprintf(stderr, "%04x: %04x, %d\n", vv, data[vv], type); */

		if(varnum == MAXVARS) {
			fprintf(stderr, "Warning: skipping variable numbers >=%d in value table.\n", MAXVARS);
			break;
		}

		if(varnum != data[vv+1]) {
			fprintf(stderr, "Warning: variable #%d value is corrupt!\n", varnum);
		}

		switch(type) {
			case TYPE_SCALAR: varname = scalars++;               break;
			case TYPE_ARRAY:  varname = arrays++;  sigil = 0xa8; break;
			case TYPE_STRING: varname = strings++; sigil = 0xa4; break;
			default:
					  fprintf(stderr, "Warning: variable value #%d has unknown type.\n", varnum);
					  break;
		}

		if(varname < 26) {
			if(write) data[vp] = ('A' + varname);
			size++;
		} else {
			varname -= 26;
			if(write) {
				data[vp++] = 'A' + varname / 9;
				data[vp] = '1' + varname % 9;
			}
			size += 2;
		}

		if(sigil) {
			size++;
			vp++;
			if(write) data[vp++] = sigil;
		} else {
			if(write) data[vp] |= 0x80;
			vp++;
		}

		vv += 8;
		varnum++;
	}

	/* there's supposed to be a null byte at the end of the table, unless
		all 128 table slots are used... except really, there can be >=129
		entries, and there's always a null byte. */
	if(write) data[vp] = 0;
	size++;

	return size;
}

void adjust_vntable_size(int oldsize, int newsize) {
	int move_by;
	if(oldsize != newsize) {
		move_by = newsize - oldsize;
		if(verbose) fprintf(stderr,
				"Need %d bytes for vntable, have %d, moving VVTP by %d to $%04x.\n",
				newsize, oldsize, move_by, vvtp + move_by);
		move_code(move_by);
	}
}

int fixvars(void) {
	int old_vntable_size, new_vntable_size;

	if(vntable_ok() && !forcevars)
		return 0;

	old_vntable_size = vvstart - vnstart;
	new_vntable_size = rebuild_vntable(0);

	adjust_vntable_size(old_vntable_size, new_vntable_size);

	rebuild_vntable(1);
	return 1;
}

void write_var_map(void) {
	FILE *f;
	int vp, count = 0;

	if(verbose) fprintf(stderr, "Writing variable names to '" MAP_FILE "'.\n");
	f = fopen(MAP_FILE, "w");
	if(!f) {
		perror(MAP_FILE);
		die("Can't create map file for -w option.");
	}

	for(vp = vnstart; (vp < vntd) && (data[vp] != 0); vp++) {
		unsigned char c = data[vp];
		if(c < 0x80) {
			fputc(c, f);
		} else {
			fputc(c & 0x7f, f);
			fputc('\n', f);
			count++;
		}
	}

	fclose(f);

	if(verbose) fprintf(stderr, "Wrote %d variable names to '" MAP_FILE "'.\n", count);
}

void die_mapfile(char *msg, int num) {
	fprintf(stderr, MAP_FILE ": line %d: %s.\n", num, msg);
	exit(1);
}

void check_varname(const unsigned char *name, int line) {
	int len = strlen((char *)name);
	int i;
	unsigned char c = 0, type;

	/* fprintf(stderr, "check_varname(\"%s\", %d)\n", name, line); */

	if(len < 1) die_mapfile("Blank variable name", line);
	if(len > 128) die_mapfile("Variable name >128 characters", line);
	if(name[0] < 'A' || name[0] > 'Z')
		die_mapfile("Invalid variable name: First character must be a letter", line);

	for(i = 1; i < len; i++) {
		c = name[i];
		if(c >= 'A' && c <= 'Z') continue;
		if(c >= '0' && c <= '9') continue;
		if(c == '$' || c == '(') {
			if(i == (len - 1))
				continue;
			else
				die_mapfile("Invalid variable name: $ and ( only allowed at end", line);
		}
		die_mapfile("Invalid character in variable name", line);
	}

	if(c == 0) c = name[0];

	/* c now has the last char of the name, make sure it matches the variable type */
	type = data[vvstart + 8 * (line - 1)] >> 6;
	/* type: scalar = 0, array = 1, string = 2 */
	if(type == TYPE_SCALAR) {
		if(c == '$')
			die_mapfile("Type mismatch: numeric variable may not end with $", line);
		else if(c == '(')
			die_mapfile("Type mismatch: numeric variable may not end with (", line);
	} else if(type == TYPE_ARRAY) {
		if(c != '(')
			die_mapfile("Type mismatch: array variable must end with (", line);
	} else if(type == TYPE_STRING) {
		if(c != '$')
			die_mapfile("Type mismatch: string variable must end with $", line);
	} else {
		fprintf(stderr, "Warning: variable value table is corrupt (invalid type).\n");
	}

	/* check for dups */
	for(i = 0; i < line - 1; i++) {
		if(strcmp((char *)name, (char *)varmap[i]) == 0)
			die_mapfile("duplicate variable name", line);
	}
}

void read_var_map(void) {
	FILE *f;
	unsigned char *p = varnames, *curname = varnames;
	int count = 0, vvcount = (codestart - vvstart) / 8;

	if(verbose) fprintf(stderr, "Reading variable names from " MAP_FILE ".\n");
	f = fopen(MAP_FILE, "r");
	if(!f) {
		perror(MAP_FILE);
		die("Can't read map file for -r option.");
	}

	while(!feof(f)) {
		*p = toupper(fgetc(f)); /* allow lowercase */

		if(*p == ' ' || *p == '\t' || *p == '\r')
			continue; /* ignore whitespace */

		if(*p == '\n') {
			*p = '\0';
			varmap[count++] = curname;
			check_varname(curname, count);
			curname = p + 1;
		}
		p++;
	}
	fclose(f);

	if(verbose) fprintf(stderr, "Read %d variable names from " MAP_FILE ".\n", count);

	if(vvcount > count) {
		fprintf(stderr, MAP_FILE ": not enough variables (have %d, need %d).\n", count, vvcount);
		exit(1);
	} else if(count > vvcount) {
		fprintf(stderr, MAP_FILE ": too many variables (have %d, need %d).\n", count, vvcount);
		exit(1);
	}

	varmap_count = count;
}

void apply_var_map(void) {
	unsigned char new_vntable[BUFSIZE];
	int i, newp = 0;
	unsigned char *v;

	if(verbose)
		fprintf(stderr, "Using variable names from " MAP_FILE ".\n");

	for(i = 0; i < varmap_count; i++) {
		v = varmap[i];
		while(*v) {
			new_vntable[newp++] = *v;
			v++;
		}
		new_vntable[newp - 1] |= 0x80;
	}

	new_vntable[newp++] = '\0';

	i = vvstart - vnstart;
	adjust_vntable_size(i, newp);
	memmove(data + vnstart, new_vntable, newp);
}

void scramble_vars(void) {
	int i;

	if(!vntable_ok()) {
		fprintf(stderr, "%s: Program already was variable-protected.\n", self);
		exit(2);
	}

	if(shrinktable) {
		if(verbose) fprintf(stderr, "Shrinking variable name table.\n");
		adjust_vntable_size((vvstart - 1) - vnstart, (codestart - vvstart) / 8);
	}

	if(varname_char == -1) srand(time(NULL));

	for(i = vnstart; i < vvstart - 1; i++)
		if(varname_char == -1)
			data[i] = (rand() >> 8) & 0xff;
		else
			data[i] = varname_char & 0xff;

	if(verbose) {
		i -= vnstart;
		if(i) {
			fprintf(stderr, "Replaced %d byte variable name table with ", i);
			if(varname_char == -1)
				fprintf(stderr, "random characters.\n");
			else
				fprintf(stderr, "character $%02x.\n", varname_char);
		} else {
			die("Can't protect variables because there are no variables.");
		}
	}
}

void print_help(void) {
	fprintf(stderr, "Usage: %s [-v] [-f] [-n] [-g] [-c] [-r|-w]  <inputfile> <outputfile>\n", self);
	fprintf(stderr, "       %s [-v] [-p|-pc|-pv] [-xr|-xNN] [-s] <inputfile> <outputfile>\n", self);
	fprintf(stderr, "  -v: Verbose.\n");
	fprintf(stderr, "  -f: Force variable name table rebuild.\n");
	fprintf(stderr, "  -n: Do not rebuild variable name table, even if it's invalid.\n");
	fprintf(stderr, "  -g: Remove trailing garbage, if present.\n");
	fprintf(stderr, "  -c: Check only; no output file.\n");
	fprintf(stderr, "  -w: Write variable names to 'varnames.txt'.\n");
	fprintf(stderr, "  -r: Read variable names from 'varnames.txt'.\n");
	fprintf(stderr, "  -pc/-pv/-p: Protect code/variables/both.\n");
	fprintf(stderr, "  -s: Shrink variable name table to min size, with -p/-pv.\n");
	fprintf(stderr, "  -xNN: Hex code NN for variable names, with -p/-pv.\n");
	fprintf(stderr, "  -xr: Random variable names, with -p/-pv.\n");
	fprintf(stderr, "Use - as a filename to read from stdin and/or write to stdout.\n");
}

void invalid_args(const char *arg) {
	fprintf(stderr, "%s: Invalid argument '%s'.\n\n", self, arg);
	print_help();
	exit(1);
}

FILE *open_file(const char *name, const char *mode) {
	FILE *fp;
	if(!(fp = fopen(name, mode))) {
		perror(name);
		exit(1);
	}
	return fp;
}

void open_input(const char *name) {
	if(!name) {
		if(isatty(fileno(stdin))) {
			die("Can't read binary data from the terminal.");
		}
		if(freopen(NULL, "rb", stdin)) {
			input_file = stdin;
			return;
		} else {
			perror("stdin");
			exit(1);
		}
	}

	input_file = open_file(name, "rb");
}

void open_output(const char *name) {
	if(!name || (strcmp(name, "-") == 0)) {
		if(isatty(fileno(stdout))) {
			die("Refusing to write binary data to the terminal.");
		}
		if(freopen(NULL, "wb", stdout)) {
			output_file = stdout;
			return;
		} else {
			perror("stdout");
			exit(1);
		}
	}

	output_file = open_file(name, "wb");
}

void parse_args(int argc, char **argv) {
	char *p;
	int xopt_used = 0;

	self = *argv;
	p = strrchr(self, '/');
	if(p) self = p + 1;

	if(argc < 2) {
		print_help();
		exit(1);
	}

	if(strcmp(argv[1], "--help") == 0) {
		print_help();
		exit(0);
	}

	if(strcmp(argv[1], "--version") == 0) {
		printf("%s %s\n", self, VERSION);
		exit(0);
	}

	while(++argv, --argc) {
		if((*argv)[0] == '-') {
			switch((*argv)[1]) {
				case 'v': verbose++; break;
				case 'f': forcevars++; break;
				case 'n': keepvars++; break;
				case 'g': keepgarbage = 0; break;
				case 'c': checkonly = 1; break;
				case 'r': readmap = 1; break;
				case 'w': writemap = 1; break;
				case 'p': {
								 switch((*argv)[2]) {
									 case 'c':
										 protect_code = 1; break;
									 case 'v':
										 protect_vars = 1; break;
									 case 0:
										 protect_code = protect_vars = 1; break;
									 default:
										 die("Invalid -p suboption (only -p, -pc, -pv are valid).");
								 }
							 }
							 break;
				case 'x': {
								 xopt_used++;
								 switch((*argv)[2]) {
									case 'r':
										varname_char = -1; break;
									case 0:
										die("-x option requires a hex number or 'r' (e.g. -x20, not -x 20)."); break;
									default:
										{
											char *e;
											varname_char = (int)strtol(&(*argv)[2], &e, 16);
											if(*e != 0 || varname_char > 0xff)
												die("invalid hex value for -x option (range is 0 to ff).");
										}
								 }
							 }
							 break;
				case 's': shrinktable = 1; break;
				case 0:
							 if(!input_file)
								 open_input(NULL);
							 else if(!output_filename)
								 output_filename = *argv;
							 else
								 invalid_args(*argv);
							 break;
				default:  invalid_args(*argv); break;
			}
		} else {
			/* arg doesn't start with a -, must be a filename */
			if(!input_file)
				open_input(*argv);
			else if(!checkonly && !output_filename)
				output_filename = *argv;
			else
				invalid_args(*argv);
		}
	}

	if(!input_file) die("No input file given (use - for stdin).");
	if(!checkonly && !output_filename) die("No output file given (use - for stdout).");
	if(keepvars && forcevars) die("-f and -n are mutually exclusive.");
	if(readmap && writemap) die("-r and -w are mutually exclusive.");
	if(readmap && keepvars) die("-r and -n are mutually exclusive, maybe you want -w?");
	if(checkonly && (readmap || writemap)) die("-c and -r/-w are mutually exclusive.");
	if(protect_code || protect_vars) {
		if(checkonly || keepvars || forcevars || readmap || writemap || !keepgarbage)
			die("-p, -pc, -pv options can only be combined with -v, -x, -s.");
	}
	if(xopt_used && !protect_vars)
		die("-x option requires -p or -pv.");
	if(shrinktable && !protect_vars)
		die("-s option requires -p or -pv.");
}

int main(int argc, char **argv) {
	int outbytes, invoffs = 0;
	parse_args(argc, argv);

	filelen = readfile();
	parse_header();

	if(lomem) die("This doesn't look like an Atari BASIC program (no $0000 signature).");

	if(protect_code || protect_vars) {
		if(verbose) {
			fprintf(stderr, "Protecting program, ");
			if(protect_vars && !protect_code)
				fprintf(stderr, "variables only.\n");
			else if(protect_code && !protect_vars)
				fprintf(stderr, "code only.\n");
			else
				fprintf(stderr, "both code and variables.\n");
		}
		if(protect_vars) scramble_vars();
		if(protect_code) breakcode();
		was_protected = 1; /* opposite sense for this one */
	} else {
		if(readmap) {
			was_protected = !vntable_ok();
			read_var_map();
			apply_var_map();
		} else {
			if(!keepvars) {
				if(fixvars()) {
					was_protected = 1;
					if(verbose) fprintf(stderr, "Variable names replaced.\n");
				} else {
					if(verbose) fprintf(stderr, "Variable names were already OK.\n");
				}
			}
		}

		invoffs = fixcode();
		if(invoffs) {
			if(verbose)
				fprintf(stderr, "Fixed %d invalid offset%s in code.\n",
						invoffs, (invoffs == 1 ? "" : "s"));
			was_protected = 1;
		} else {
			if(verbose) fprintf(stderr, "No invalid offsets.\n");
		}

		if(verbose) {
			fprintf(stderr, "Program was %sprotected.\n", (was_protected ? "" : "NOT "));
		}

		if(checkonly) {
			if(verbose) fprintf(stderr, "Check-only mode; no output written.\n");
			return was_protected ? 0 : 2;
		}
	}

	/* we don't open the output file until all processing is done, to
		avoid leaving invalid output files if we exit on error. */
	open_output(output_filename);
	outbytes = fwrite(data, 1, filelen, output_file);
	fclose(output_file);
	if(verbose) fprintf(stderr, "Wrote %d bytes.\n", outbytes);

	if(writemap) write_var_map();

	return was_protected ? 0 : 2;
}