/***********************************************************************
***
***  CDTV Dump Sector 1.0 (26-SEP-90)
***
***	By CARL SASSENRATH, Ukiah, CA  (707)-462-4878
***
***	Free to Distribute amoung CDTV developers.
***
***	A simple CD-ROM reader that uses the device driver directly
***	to access data.
***
***********************************************************************/

#include <exec/types.h>
#include <exec/io.h>
#include "cd.h"

extern	struct	IOStdReq *CreateStdIO();
extern	struct	MsgPort  *CreatePort();
struct	IOStdReq *IORequest = NULL;
struct	MsgPort  *IOPort = NULL;
char	Buffer[2048];
int	QuitFlag = FALSE;

#define	MUST(expr)  if (!(expr)) Quit();

main(argc,argv)
	int argc;
	char *argv[];
{
	int sector;

	if (argc < 2) sector = 16;
	else
	{
		sector = atoi(argv[1]);
		if (!sector) sector = 16;
	}

	MUST(IOPort = CreatePort(0,0));
	MUST(IORequest = CreateStdIO(IOPort));

	if (OpenDevice("cdtv.device",0,IORequest,0))
		{printf("CDTV Device will not open\n");	Quit();}

	IORequest->io_Command = CD_READ;
	IORequest->io_Offset = sector * 2048;
	IORequest->io_Length = 2048;
	IORequest->io_Data   = (APTR)Buffer;
	if (DoIO(IORequest)) printf("READ command error\n");

	printf("CD-ROM SECTOR: %ld\n",sector);
	DumpBlock(sector,Buffer,2048);

	Quit();
}

Quit()
{
	if (IORequest->io_Device) CloseDevice(IORequest);
	if (IORequest)	DeleteStdIO(IORequest);
	if (IOPort)	DeletePort(IOPort);
}

/* abort -- Capture MANX ^C interrupt */
_abort()
{
	QuitFlag = TRUE;
}

/* PrtChar -- Utility function used with DumpBlock */
char PrtChar(c)
	register char c;
{
	if (c < ' ' || c > '~') return '.';
	return c;
}

/* Bytes Per Line: */
#define BPL 16

/* DumpBlock -- print a block of bytes */
DumpBlock(blk,buf,size)
	long blk;
	unsigned char *buf;
	long size;
{
	register int i,j;

	for (i = 0; i < size; i+=BPL )
	{
		if (QuitFlag) break;
		printf("%03x:",i);	
		for (j = 0; j < BPL; j++)
		{
			printf("%02x",buf[i+j]);
			if (((j+1)%2) == 0) printf(" ");
		}
		for (j = 0; j < BPL; j++) printf("%c",PrtChar(buf[i+j]));
		printf("\n");
	}
	printf("\n");
}
