/*
 * utility to toggle clear TPA beyond BSS flag in .prg header for Tos 1.4
 *
 *	Usage: toglclr file file ....
 *
 *	++jrb
 */

#include <stdio.h>
#include <stdlib.h>
#include <unixlib.h>
#include <string.h>
#include <st-out.h>


int toggle (fd, fn)
int fd;
char *fn;
{
    struct aexec head;
    unsigned long t;
    
    if(read(fd, &head, sizeof(head)) != sizeof(head))
    {
	perror(fn);
	return 4;
    }
    if(head.a_magic != CMAGIC)
    {
	fprintf(stderr,"%s: Invalid magic number %x\n", fn, head.a_magic);
	return 8;
    }

    t = head.a_AZero2;
    head.a_AZero2 ^= 1;
    lseek(fd, 0L, SEEK_SET);
    if(write(fd, &head, sizeof(head)) != sizeof(head))
    {
	perror(fn);
	return 16;
    }

    printf("%s: was %d is %d\n", fn, (int)t, (int)head.a_AZero2);
    return 0;
}

int main(argc, argv)
int argc;
char **argv;
{
    int fd;
    int status = 0;
    char fn[FILENAME_MAX];
    
    if(argc < 2)
    {
	fprintf(stderr, "usage: toglclr file file .....\n");
	exit(1);
    }

    while(--argc > 0)
    {
	(void) strcpy(fn, *++argv);
        if((fd = open(fn, 2)) < 0)
        {
	    perror(fn);
	    continue;
        }
	status |= toggle(fd, fn);
	if(close(fd))
	{
	    perror(fn);
	    exit(2);
	}
    }
    
    return status;
}

