#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <Errors.h>
#include <Devices.h>
#include <Serial.h>

#define BSIZE	102400

main(int argc, char **argv)
{
	short	ref;
	short	config;
	int	count;
	int	fd;
	OSErr	err;
	char	*buf, *buf2, *malloc();
	
	if ((buf = malloc(BSIZE)) == NULL) {
		fprintf(stderr, "malloc failed\n");
		exit(1);
	}
	
	if ((buf2 = malloc(BSIZE)) == NULL) {
		fprintf(stderr, "malloc (2) failed\n");
		goto free1;
	}
	
	if ((err = RamSDOpen(sPortA)) != noErr) {
		fprintf(stderr, "RAMSDOpen = %d\n", err);
		goto free2;
	}
	
	if ((err = OpenDriver("\P.AIn", &ref)) != noErr) {
		fprintf(stderr, "OpenDriver = %d\n", err);
		goto free2;
	}
	
	config = baud9600 | stop10 | noParity | data8;
	if ((err = SerReset(ref, config)) != noErr) {
		fprintf(stderr, "SerReset = %d\n", err);
		goto done;
	}
	
	if ((err = SerSetBuf(ref, (Ptr) buf, BSIZE)) != noErr) {
		fprintf(stderr, "SerSetBuf = %d\n", err);
		goto done;
	}
	
	fprintf(stderr, "Ready\n");
	count = BSIZE;
	if ((err = FSRead(ref, &count, (Ptr) buf2)) != noErr)
		fprintf(stderr, "FSRead = %d\n", err);
	
	fprintf(stderr, "Read %d bytes\n", count);
	if ((err = SerSetBuf(ref, (Ptr) nil, 0)) != noErr)
		fprintf(stderr, "SerSetBuf (2) = %d\n", err);
		
done:
	if ((err = CloseDriver(ref)) != noErr)
		fprintf(stderr, "CloseDriver = %d\n", err);

	RamSDClose(sPortA);
	if ((fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC)) < 0) {
		fprintf(stderr, "open = %d\n", errno);
		goto free2;
	}
	
	if (write(fd, buf2, count) != count)
		fprintf(stderr, "write = %d\n", errno);
		
	(void) close(fd);
free2:	
	free(buf2);
free1:
	free(buf);
	exit(0);
}
