/* @(#)scsi_cmds.c	1.16 02/01/13 Copyright 1998-2000 Heiko Eissfeldt */
#ifndef lint
static char     sccsid[] =
"@(#)scsi_cmds.c	1.16 02/01/13 Copyright 1998-2000 Heiko Eissfeldt";

#endif
/* file for all SCSI commands
 * FUA (Force Unit Access) bit handling copied from Monty's cdparanoia.
 */
#define TESTSUBQFALLBACK	0

#include "config.h"
#include <stdio.h>
#include <standard.h>
#include <stdxlib.h>
#include <strdefs.h>
#include <schily.h>

#include <btorder.h>

#define        g5x_cdblen(cdb, len)    ((cdb)->count[0] = ((len) >> 16L)& 0xFF,\
                                (cdb)->count[1] = ((len) >> 8L) & 0xFF,\
                                (cdb)->count[2] = (len) & 0xFF)


#include <scg/scgcmd.h>
#include <scg/scsidefs.h>
#include <scg/scsireg.h>

#include <scg/scsitransp.h>

#include "mytype.h"
#include "cdda2wav.h"
#include "interface.h"
#include "byteorder.h"
#include "global.h"
#include "cdrecord.h"
#include "toc.h"
#include "scsi_cmds.h"

unsigned char *bufferTOC;
subq_chnl *SubQbuffer;
unsigned char *cmd;

static unsigned ReadFullTOCSony __PR(( SCSI *scgp ));
static unsigned ReadFullTOCMMC __PR(( SCSI *scgp ));


int SCSI_emulated_ATAPI_on(SCSI *scgp)
{
/*	return is_atapi;*/
	if (scg_isatapi(scgp) > 0)
		return (TRUE);

	(void) allow_atapi(scgp, TRUE);
	return (allow_atapi(scgp, TRUE));
}

int heiko_mmc(SCSI *scgp)
{
        unsigned char	mode[0x100];
	int		was_atapi;
        struct  cd_mode_page_2A *mp;
	int retval;

        memset((caddr_t)mode, 0, sizeof(mode));

        was_atapi = allow_atapi(scgp, 1);
        scgp->silent++;
        mp = mmc_cap(scgp, mode);
        scgp->silent--;
        allow_atapi(scgp, was_atapi);
        if (mp == NULL)
                return (0);

        /* have a look at the capabilities */
	if (mp->cd_da_supported == 0) {
	  retval = -1;
	} else {
	  retval = 1 + mp->cd_da_accurate;
        }
	return retval;
}


int accepts_fua_bit;
unsigned char density = 0;
unsigned char orgmode4 = 0;
unsigned char orgmode10, orgmode11;

/* get current sector size from SCSI cdrom drive */
unsigned int 
get_orig_sectorsize(SCSI *scgp, unsigned char *m4, unsigned char *m10, unsigned char *m11)
{
      /* first get current values for density, etc. */

      static unsigned char *modesense = NULL;
   
      if (modesense == NULL) {
        modesense = (unsigned char *) malloc(12);
        if (modesense == NULL) {
          fprintf(stderr, "Cannot allocate memory for mode sense command in line %d\n", __LINE__);
          return 0;
        }
      }

      /* do the scsi cmd */
      if (scgp->verbose) fprintf(stderr, "\nget density and sector size...");
      if (mode_sense(scgp, modesense, 12, 0x01, 0) < 0)
	  fprintf(stderr, "get_orig_sectorsize mode sense failed\n");

      /* FIXME: some drives dont deliver block descriptors !!! */
      if (modesense[3] == 0)
        return 0;

      if (m4 != NULL)                       /* density */
        *m4 = modesense[4];
      if (m10 != NULL)                      /* MSB sector size */
        *m10 = modesense[10];
      if (m11 != NULL)                      /* LSB sector size */
        *m11 = modesense[11];

      return (modesense[10] << 8) + modesense[11];
}



/* switch CDROM scsi drives to given sector size  */
int set_sectorsize (SCSI *scgp, unsigned int secsize)
{
  static unsigned char mode [4 + 8];
  int retval;

  if (orgmode4 == 0xff) {
    get_orig_sectorsize(scgp, &orgmode4, &orgmode10, &orgmode11);
  }
  if (orgmode4 == 0x82 && secsize == 2048)
    orgmode4 = 0x81;

  /* prepare to read cds in the previous mode */

  memset((caddr_t)mode, 0, sizeof(mode));
  mode[ 3] = 8; 	       /* Block Descriptor Length */
  mode[ 4] = orgmode4; 	       /* normal density */
  mode[10] =  secsize >> 8;   /* block length "msb" */
  mode[11] =  secsize & 0xFF; /* block length lsb */

  if (scgp->verbose) fprintf(stderr, "\nset density and sector size...");
  /* do the scsi cmd */
  if ((retval = mode_select(scgp, mode, 12, 0, scgp->inq->data_format >= 2)) < 0)
        fprintf (stderr, "setting sector size failed\n");

  return retval;
}


/* switch Toshiba/DEC and HP drives from/to cdda density */
void EnableCddaModeSelect (SCSI *scgp, int fAudioMode)
{
  /* reserved, Medium type=0, Dev spec Parm = 0, block descriptor len 0 oder 8,
     Density (cd format) 
     (0=YellowBook, XA Mode 2=81h, XA Mode1=83h and raw audio via SCSI=82h),
     # blks msb, #blks, #blks lsb, reserved,
     blocksize, blocklen msb, blocklen lsb,
   */

  /* MODE_SELECT, page = SCSI-2  save page disabled, reserved, reserved, 
     parm list len, flags */
  static unsigned char mode [4 + 8] = { 
       /* mode section */
			    0, 
                            0, 0, 
                            8,       /* Block Descriptor Length */
       /* block descriptor */
                            0,       /* Density Code */
                            0, 0, 0, /* # of Blocks */
                            0,       /* reserved */
                            0, 0, 0};/* Blocklen */

  if (orgmode4 == 0 && fAudioMode) {
    if (0 == get_orig_sectorsize(scgp, &orgmode4, &orgmode10, &orgmode11)) {
        /* cannot retrieve density, sectorsize */
	orgmode10 = (CD_FRAMESIZE >> 8L);
	orgmode11 = (CD_FRAMESIZE & 0xFF);
    }
  }

  if (fAudioMode) {
    /* prepare to read audio cdda */
    mode [4] = density;  			/* cdda density */
    mode [10] = (CD_FRAMESIZE_RAW >> 8L);   /* block length "msb" */
    mode [11] = (CD_FRAMESIZE_RAW & 0xFF);  /* block length "lsb" */
  } else {
    /* prepare to read cds in the previous mode */
    mode [4] = orgmode4; /* 0x00; 			\* normal density */
    mode [10] = orgmode10; /* (CD_FRAMESIZE >> 8L);  \* block length "msb" */
    mode [11] = orgmode11; /* (CD_FRAMESIZE & 0xFF); \* block length lsb */
  }

  if (scgp->verbose) fprintf(stderr, "\nset density/sector size (EnableCddaModeSelect)...\n");
  /* do the scsi cmd */
  if (mode_select(scgp, mode, 12, 0, scgp->inq->data_format >= 2) < 0)
        fprintf (stderr, "Audio mode switch failed\n");
}


/* read CD Text information from the table of contents */
void ReadTocTextSCSIMMC ( SCSI *scgp )
{
    short datalength;
    unsigned char *p = bufferTOC;

#if 1
  /* READTOC, MSF, format, res, res, res, Start track/session, len msb,
     len lsb, control */
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)bufferTOC;
        scmd->size = 4;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x43;		/* Read TOC command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.addr[0] = 5;		/* format field */
        scmd->cdb.g1_cdb.res6 = 0;	/* track/session is reserved */
        g1_cdblen(&scmd->cdb.g1_cdb, 4);

        scgp->silent++;
        if (scgp->verbose) fprintf(stderr, "\nRead TOC CD Text size ...");

	scgp->cmdname = "read toc size (text)";

        if (scg_cmd(scgp) < 0) {
          scgp->silent--;
	  if (global.quiet != 1)
            fprintf (stderr, "Read TOC CD Text failed (probably not supported).\n");
	  p[0] = p[1] = '\0';
          return ;
        }
        scgp->silent--;

    datalength  = (p[0] << 8) | (p[1]);
    if (datalength <= 2) return;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)bufferTOC;
        scmd->size = 2+datalength;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x43;		/* Read TOC command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.addr[0] = 5;		/* format field */
        scmd->cdb.g1_cdb.res6 = 0;	/* track/session is reserved */
        g1_cdblen(&scmd->cdb.g1_cdb, 2+datalength);

        scgp->silent++;
        if (scgp->verbose) fprintf(stderr, "\nRead TOC CD Text data (length %hd)...", 2+datalength);

	scgp->cmdname = "read toc data (text)";

        if (scg_cmd(scgp) < 0) {
          scgp->silent--;
	  if (global.quiet != 1)
            fprintf (stderr,  "Read TOC CD Text data failed (probably not supported).\n");
	  p[0] = p[1] = '\0';
          return ;
        }
        scgp->silent--;
#else
	{ FILE *fp;
	int read_;
	fp = fopen("PearlJam.cdtext", "rb");
	/*fp = fopen("celine.cdtext", "rb");*/
	if (fp == NULL) { perror(""); return; }
	memset(bufferTOC, 0, CD_FRAMESIZE);
	read_ = fread(bufferTOC, 1, CD_FRAMESIZE, fp );
fprintf(stderr, "read %d bytes. sizeof(bufferTOC)=%u\n", read_, CD_FRAMESIZE);
        datalength  = (bufferTOC[0] << 8) | (bufferTOC[1]);
	fclose(fp);
	}
#endif
}

/* read the full TOC */
static unsigned ReadFullTOCSony ( SCSI *scgp )
{
  /* READTOC, MSF, format, res, res, res, Start track/session, len msb,
     len lsb, control */
	register struct	scg_cmd	*scmd = scgp->scmd;
	unsigned tracks = 99;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)bufferTOC;
        scmd->size = 4 + (3 + tracks + 6) * 11;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x43;		/* Read TOC command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.res6 = 1;    		/* session */
        g1_cdblen(&scmd->cdb.g1_cdb, 4 + (3 + tracks + 6) * 11);
        scmd->cdb.g1_cdb.vu_97 = 1;   		/* format */

        scgp->silent++;
        if (scgp->verbose) fprintf(stderr, "\nRead Full TOC Sony ...");

	scgp->cmdname = "read full toc sony";

        if (scg_cmd(scgp) < 0) {
          scgp->silent--;
	  if (global.quiet != 1)
            fprintf (stderr, "Read Full TOC Sony failed (probably not supported).\n");
          return 0;
        }
        scgp->silent--;

	return (unsigned)((bufferTOC[0] << 8) | bufferTOC[1]);
}

/* read the table of contents from the cd and fill the TOC array */
unsigned ReadTocSony ( SCSI *scgp )
{
	unsigned tracks;
	unsigned return_length;
	unsigned entries;
	int datatrack = 0;
	int i;
	return_length = ReadFullTOCSony(scgp);

	/* Check if the format was understood */
	if ((return_length & 7) == 2 && (bufferTOC[3] - bufferTOC[2]) == (return_length >> 3)) {
		/* The extended format seems not be understood, fallback to
		 * the classical format. */
		return ReadTocSCSI( scgp );
	}

	entries = ((return_length - 2) / 11);
#if	0
	for (i = 0; i < entries; i++) {
fprintf(stderr, "%d %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n" 
	,bufferTOC[4+0 + (i * 11)]
	,bufferTOC[4+1 + (i * 11)]
	,bufferTOC[4+2 + (i * 11)]
	,bufferTOC[4+3 + (i * 11)]
	,bufferTOC[4+4 + (i * 11)]
	,bufferTOC[4+5 + (i * 11)]
	,bufferTOC[4+6 + (i * 11)]
	,bufferTOC[4+7 + (i * 11)]
	,bufferTOC[4+8 + (i * 11)]
	,bufferTOC[4+9 + (i * 11)]
	,bufferTOC[4+10 + (i * 11)]
	);
	}
#endif
	/* reformat to standard toc format */

	/* first track number */
	bufferTOC[2] = from_bcd(bufferTOC[4 + (0*11) + 8]);
	/* last track number */
	bufferTOC[3] = from_bcd(bufferTOC[4 + (1*11) + 8]);
	/* patch leadout track number over POINT a2 */
	bufferTOC[4 + (2*11) + 3] = 0xAA;
	tracks = bufferTOC[3] - bufferTOC[2] + 2; 

	if (tracks + 2 + 6 <= entries) {
		/* if we have multisession, add at most
			 one data track for cd extra */
		unsigned long start_of_first_leadout;
		unsigned long second_leadout = 0;

		start_of_first_leadout =
			from_bcd(bufferTOC[4 + (2*11) + 8])*60*75
			+ from_bcd(bufferTOC[4 + (2*11) + 9])*75
			+ from_bcd(bufferTOC[4 + (2*11) + 10]);

		/* search an additional data track in the second session. */
		datatrack = tracks + 2;
		while (datatrack < entries) {
			if (/* session == 2 */
			    bufferTOC[4 + (datatrack*11)] == 2) {
				if (bufferTOC[4 + (datatrack*11) + 3]== 0xa2) {
					second_leadout = datatrack;
				}
				/* consecutive track number for data track */
				if (/* track type == data track */
				    (bufferTOC[4 + (datatrack*11) + 1] & 0x04)
				 && (from_bcd(bufferTOC[4 + (datatrack*11) + 3])
				    == tracks)) {
					break;
				}
			}
			datatrack++;
		}
		if (datatrack < entries) {
			unsigned long start_of_first_secondsession_track;
			start_of_first_secondsession_track =
				 from_bcd(bufferTOC[4 + (datatrack*11)+8])*60*75
				+ from_bcd(bufferTOC[4 + (datatrack*11)+9])*75
				+ from_bcd(bufferTOC[4 + (datatrack*11)+10]);
			if (start_of_first_secondsession_track >
				start_of_first_leadout 
			    && second_leadout != 0) {
				tracks++;
				bufferTOC[3]++;
				/* patch second leadout over first leadout */
				bufferTOC[4 + (2*11) + 8] = 
				bufferTOC[4 + (second_leadout*11) + 8];
				bufferTOC[4 + (2*11) + 9] =
				bufferTOC[4 + (second_leadout*11) + 9];
				bufferTOC[4 + (2*11) + 10] =
				bufferTOC[4 + (second_leadout*11) + 10];
			} else {
				/* do not believe data track info. */
				datatrack = 0;
			}
		} else {
			/* no real data track found. */
			datatrack = 0;
		}
	}
	/* length */
	bufferTOC[0] = ((tracks * 8) + 2) >> 8; /* the new struct has size 8 */
	bufferTOC[1] = ((tracks * 8) + 2) & 0xff;

	if (datatrack != 0) {
		/* move data track entry at the end before leadout */
		memcpy(bufferTOC+4 + (tracks+1)*11, bufferTOC+4+(datatrack*11), 11);
	}
	/* move lead out entry at the end */
	memcpy(bufferTOC+4 + (tracks+2)*11, bufferTOC+4+(2*11), 11);
	/* move tracks and lead out block to front */
	memmove(bufferTOC+4, bufferTOC+4+(3*11), tracks*11);

	/* reformat 11 byte blocks to 8 byte entries */
	/* 1: Session		->	reserved
	   2: adr ctrl		->	adr ctrl
	   3: TNO		->	track number
	   4: Point		->	reserved
	   5: Min		->	0
	   6: Sec		->	Min
	   7: Frame		->	Sec
	   8: Zero		->	Frame
	   9: PMin
	   10: PSec
	   11: PFrame
	*/
	for (i = 0; i < tracks; i++) {
		bufferTOC[4+0 + (i << 3)] = 0;
		bufferTOC[4+1 + (i << 3)] = bufferTOC[4+1 + (i*11)];
		if (i == tracks -1) {
			bufferTOC[4+2 + (i << 3)] = bufferTOC[4+3 + (i*11)];
		} else {
			bufferTOC[4+2 + (i << 3)] = from_bcd(bufferTOC[4+3 + (i*11)]);
		}
		bufferTOC[4+3 + (i << 3)] = 0;
		bufferTOC[4+4 + (i << 3)] = 0;
		bufferTOC[4+5 + (i << 3)] = from_bcd(bufferTOC[4+8 + (i*11)]);
		bufferTOC[4+6 + (i << 3)] = from_bcd(bufferTOC[4+9 + (i*11)]);
		bufferTOC[4+7 + (i << 3)] = from_bcd(bufferTOC[4+10 + (i*11)]);
#if	0
fprintf(stderr, "%02x %02x %02x %02x %02x\n"
	,bufferTOC[4+ 1 + i*8]
	,bufferTOC[4+ 2 + i*8]
	,bufferTOC[4+ 5 + i*8]
	,bufferTOC[4+ 6 + i*8]
	,bufferTOC[4+ 7 + i*8]
);
#endif
	}

	TOC_entries(tracks, NULL, bufferTOC+4, 0);
	return --tracks;           /* without lead-out */
}

/* read the start of the lead-out from the first session TOC */
unsigned ReadFirstSessionTOCSony ( SCSI *scgp )
{
	unsigned return_length;
	return_length = ReadFullTOCSony(scgp);
        if (return_length >= 4 + (3 * 11) -2) {
          unsigned off;

          /* We want the entry with POINT = 0xA2, which has the start position
             of the first session lead out */
          off = 4 + 2 * 11 + 3;
          if (bufferTOC[off-3] == 1 && bufferTOC[off] == 0xA2) {
            unsigned retval;

            off = 4 + 2 * 11 + 8;
            retval = bufferTOC[off] >> 4;
	    retval *= 10; retval += bufferTOC[off] & 0xf;
	    retval *= 60;
	    off++;
            retval += 10 * (bufferTOC[off] >> 4) + (bufferTOC[off] & 0xf);
	    retval *= 75;
	    off++;
            retval += 10 * (bufferTOC[off] >> 4) + (bufferTOC[off] & 0xf);
	    retval -= 150;

            return retval;
          }
        }
        return 0;
}

/* read the full TOC */
static unsigned ReadFullTOCMMC ( SCSI *scgp )
{

  /* READTOC, MSF, format, res, res, res, Start track/session, len msb,
     len lsb, control */
	register struct	scg_cmd	*scmd = scgp->scmd;
	unsigned tracks = 99;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)bufferTOC;
        scmd->size = 4 + (tracks + 8) * 11;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x43;		/* Read TOC command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.addr[0] = 2;		/* format */
        scmd->cdb.g1_cdb.res6 = 1;		/* session */
        g1_cdblen(&scmd->cdb.g1_cdb, 4 + (tracks + 8) * 11);

        scgp->silent++;
        if (scgp->verbose) fprintf(stderr, "\nRead Full TOC MMC...");

	scgp->cmdname = "read full toc mmc";

        if (scg_cmd(scgp) < 0) {
	  if (global.quiet != 1)
            fprintf (stderr, "Read Full TOC MMC failed (probably not supported).\n");
#ifdef	B_BEOS_VERSION
#else
          scgp->silent--;
          return 0;
#endif
        }
        scgp->silent--;

	return (unsigned)((bufferTOC[0] << 8) | bufferTOC[1]);
}

/* read the start of the lead-out from the first session TOC */
unsigned ReadFirstSessionTOCMMC ( SCSI *scgp )
{
        unsigned off;
	unsigned return_length;
	return_length = ReadFullTOCMMC(scgp);

        /* We want the entry with POINT = 0xA2, which has the start position
             of the first session lead out */
        off = 4 + 3;
        while (off < return_length && bufferTOC[off] != 0xA2) {
          off += 11;
        }
        if (off < return_length) {
          off += 5;
          return (bufferTOC[off]*60 + bufferTOC[off+1])*75 + bufferTOC[off+2] - 150;
        }
        return 0;
}

/* read the table of contents from the cd and fill the TOC array */
unsigned ReadTocMMC ( SCSI *scgp )
{
	unsigned tracks;
	unsigned return_length;
	unsigned entries;
	int datatrack = 0;
	int i;
	return_length = ReadFullTOCMMC(scgp);
	if (return_length == 0) return ReadTocSCSI(scgp);

	entries = ((return_length - 2) / 11);
#if	0
	for (i = 0; i < entries; i++) {
fprintf(stderr, "%d %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n" 
	,bufferTOC[4+0 + (i * 11)]
	,bufferTOC[4+1 + (i * 11)]
	,bufferTOC[4+2 + (i * 11)]
	,bufferTOC[4+3 + (i * 11)]
	,bufferTOC[4+4 + (i * 11)]
	,bufferTOC[4+5 + (i * 11)]
	,bufferTOC[4+6 + (i * 11)]
	,bufferTOC[4+7 + (i * 11)]
	,bufferTOC[4+8 + (i * 11)]
	,bufferTOC[4+9 + (i * 11)]
	,bufferTOC[4+10 + (i * 11)]
	);
	}
#endif
	/* reformat to standard toc format */

	/* first track number */
	bufferTOC[2] = bufferTOC[4 + (0*11) + 8];
	/* last track number */
	bufferTOC[3] = bufferTOC[4 + (1*11) + 8];
	/* patch leadout track number */
	bufferTOC[4 + (2*11) + 3] = 0xAA;
	tracks = bufferTOC[3] - bufferTOC[2] + 2; 

	if (tracks + 2 + 6 <= entries) {
		/* if we have multisession, add at most
			 one data track for cd extra */
		unsigned long start_of_first_leadout;
		unsigned long second_leadout = 0;

		start_of_first_leadout =
			(bufferTOC[4 + (2*11) + 8])*60*75
			+ (bufferTOC[4 + (2*11) + 9])*75
			+ (bufferTOC[4 + (2*11) + 10]);

		/* search an additional data track in the second session. */
		datatrack = tracks + 2;
		while (datatrack < entries) {
			if (/* session == 2 */
			    bufferTOC[4 + (datatrack*11)] == 2) {
				if (bufferTOC[4 + (datatrack*11) + 3]== 0xa2) {
					second_leadout = datatrack;
				}
				/* consecutive track number for data track */
				if (/* track type == data track */
				    (bufferTOC[4 + (datatrack*11) + 1] & 0x04)
				 && ((bufferTOC[4 + (datatrack*11) + 3])
				    == tracks)) {
					break;
				}
			}
			datatrack++;
		}
		if (datatrack < entries) {
			unsigned long start_of_first_secondsession_track;
			start_of_first_secondsession_track =
				 (bufferTOC[4 + (datatrack*11)+8])*60*75
				+ (bufferTOC[4 + (datatrack*11)+9])*75
				+ (bufferTOC[4 + (datatrack*11)+10]);
			if (start_of_first_secondsession_track >
				start_of_first_leadout 
			    && second_leadout != 0) {
				tracks++;
				bufferTOC[3]++;
				/* patch second leadout over first leadout */
				bufferTOC[4 + (2*11) + 8] = 
				bufferTOC[4 + (second_leadout*11) + 8];
				bufferTOC[4 + (2*11) + 9] =
				bufferTOC[4 + (second_leadout*11) + 9];
				bufferTOC[4 + (2*11) + 10] =
				bufferTOC[4 + (second_leadout*11) + 10];
			} else {
				/* do not believe data track info. */
				datatrack = 0;
			}
		} else {
			/* no real data track found. */
			datatrack = 0;
		}
	}
	/* length */
	bufferTOC[0] = ((tracks * 8) + 2) >> 8;
	bufferTOC[1] = ((tracks * 8) + 2) & 0xff;

	if (datatrack != 0) {
		/* move data track entry at the end before leadout */
		memcpy(bufferTOC+4 + (tracks+1)*11, bufferTOC+4+(datatrack*11), 11);
	}
	/* move lead out entry at the end */
	memcpy(bufferTOC+4 + (tracks+2)*11, bufferTOC+4+(2*11), 11);
	/* move tracks and lead out block to front */
	memmove(bufferTOC+4, bufferTOC+4+(3*11), tracks*11);

	/* reformat 11 byte blocks to 8 byte entries */
	for (i = 0; i < tracks; i++) {
		bufferTOC[4+0 + (i << 3)] = 0;
		bufferTOC[4+1 + (i << 3)] = bufferTOC[4+1 + (i*11)];
		bufferTOC[4+2 + (i << 3)] = bufferTOC[4+3 + (i*11)];
		bufferTOC[4+3 + (i << 3)] = 0;
		bufferTOC[4+4 + (i << 3)] = 0;
		bufferTOC[4+5 + (i << 3)] = bufferTOC[4+8 + (i*11)];
		bufferTOC[4+6 + (i << 3)] = bufferTOC[4+9 + (i*11)];
		bufferTOC[4+7 + (i << 3)] = bufferTOC[4+10 + (i*11)];
#if	0
fprintf(stderr, "%02x %02x %02x %02x %02x\n"
	,bufferTOC[4+ 1 + i*8]
	,bufferTOC[4+ 2 + i*8]
	,bufferTOC[4+ 5 + i*8]
	,bufferTOC[4+ 6 + i*8]
	,bufferTOC[4+ 7 + i*8]
);
#endif
	}

	TOC_entries(tracks, NULL, bufferTOC+4, 0);
	return --tracks;           /* without lead-out */
}

/* read the table of contents from the cd and fill the TOC array */
unsigned ReadTocSCSI ( SCSI *scgp )
{
    unsigned tracks;
    int	result;
    unsigned char bufferTOCMSF[CD_FRAMESIZE];

    /* first read the first and last track number */
    /* READTOC, MSF format flag, res, res, res, res, Start track, len msb,
       len lsb, flags */
    register struct	scg_cmd	*scmd = scgp->scmd;

    memset((caddr_t)scmd, 0, sizeof(*scmd));
    scmd->addr = (caddr_t)bufferTOC;
    scmd->size = 4;
    scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
    scmd->cdb_len = SC_G1_CDBLEN;
    scmd->sense_len = CCS_SENSE_LEN;
    scmd->cdb.g1_cdb.cmd = 0x43;		/* read TOC command */
    scmd->cdb.g1_cdb.lun = scg_lun(scgp);
    scmd->cdb.g1_cdb.res6 = 1;		/* start track */
    g1_cdblen(&scmd->cdb.g1_cdb, 4);

    if (scgp->verbose) fprintf(stderr, "\nRead TOC size (standard)...");
    /* do the scsi cmd (read table of contents) */

    scgp->cmdname = "read toc size";
    if (scg_cmd(scgp) < 0)
	FatalError ("Read TOC size failed.\n");
    

    tracks = ((bufferTOC [3] ) - bufferTOC [2] + 2) ;
    if (tracks > MAXTRK) return 0;
    if (tracks == 0) return 0;
    
    
    memset(bufferTOCMSF, 0, sizeof(bufferTOCMSF));
    memset((caddr_t)scmd, 0, sizeof(*scmd));
    scmd->addr = (caddr_t)bufferTOCMSF;
    scmd->size = 4 + tracks * 8;
    scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
    scmd->cdb_len = SC_G1_CDBLEN;
    scmd->sense_len = CCS_SENSE_LEN;
    scmd->cdb.g1_cdb.cmd = 0x43;		/* read TOC command */
    scmd->cdb.g1_cdb.lun = scg_lun(scgp);
    scmd->cdb.g1_cdb.res = 1;		/* MSF format */
    scmd->cdb.g1_cdb.res6 = 1;		/* start track */
    g1_cdblen(&scmd->cdb.g1_cdb, 4 + tracks * 8);

    if (scgp->verbose) fprintf(stderr, "\nRead TOC tracks (standard MSF)...");
    /* do the scsi cmd (read table of contents) */

    scgp->cmdname = "read toc tracks ";
    result = scg_cmd(scgp);

    if (result < 0) {
	/* MSF format did not succeeded */
	memset(bufferTOCMSF, 0, sizeof(bufferTOCMSF));
    }

    /* LBA format for cd burners like Philips CD-522 */
    memset((caddr_t)scmd, 0, sizeof(*scmd));
    scmd->addr = (caddr_t)bufferTOC;
    scmd->size = 4 + tracks * 8;
    scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
    scmd->cdb_len = SC_G1_CDBLEN;
    scmd->sense_len = CCS_SENSE_LEN;
    scmd->cdb.g1_cdb.cmd = 0x43;		/* read TOC command */
    scmd->cdb.g1_cdb.lun = scg_lun(scgp);
    scmd->cdb.g1_cdb.res = 0;		/* LBA format */
    scmd->cdb.g1_cdb.res6 = 1;		/* start track */
    g1_cdblen(&scmd->cdb.g1_cdb, 4 + tracks * 8);

    if (scgp->verbose) fprintf(stderr, "\nRead TOC tracks (standard LBA)...");
    /* do the scsi cmd (read table of contents) */

    scgp->cmdname = "read toc tracks ";
    if (scg_cmd(scgp) < 0) {
	FatalError ("Read TOC tracks (lba) failed.\n");
    }
    TOC_entries(tracks, bufferTOC+4, bufferTOCMSF+4, result);
    return --tracks;           /* without lead-out */
}

/* ---------------- Read methods ------------------------------ */

/* Read max. SectorBurst of cdda sectors to buffer
   via standard SCSI-2 Read(10) command */
int ReadStandard (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal )
{
  /* READ10, flags, block1 msb, block2, block3, block4 lsb, reserved, 
     transfer len msb, transfer len lsb, block addressing mode */
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)p;
        scmd->size = SectorBurstVal*CD_FRAMESIZE_RAW;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x28;		/* read 10 command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
	scmd->cdb.g1_cdb.res |= (accepts_fua_bit == 1 ? 1 << 2 : 0);
        g1_cdbaddr(&scmd->cdb.g1_cdb, lSector);
        g1_cdblen(&scmd->cdb.g1_cdb, SectorBurstVal);
        if (scgp->verbose) fprintf(stderr, "\nReadStandard10 CDDA...");

	scgp->cmdname = "ReadStandard10";

	if (scg_cmd(scgp)) return 0;

	/* has all or something been read? */
	return SectorBurstVal - scg_getresid(scgp)/CD_FRAMESIZE_RAW;
}

/* Read max. SectorBurst of cdda sectors to buffer
   via vendor-specific ReadCdda(10) command */
int ReadCdda10 (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal)
{
  /* READ10, flags, block1 msb, block2, block3, block4 lsb, reserved, 
     transfer len msb, transfer len lsb, block addressing mode */
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)p;
        scmd->size = SectorBurstVal*CD_FRAMESIZE_RAW;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0xd4;		/* Read audio command */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
	scmd->cdb.g1_cdb.res |= (accepts_fua_bit == 1 ? 1 << 2 : 0);
        g1_cdbaddr(&scmd->cdb.g1_cdb, lSector);
        g1_cdblen(&scmd->cdb.g1_cdb, SectorBurstVal);
        if (scgp->verbose) fprintf(stderr, "\nReadNEC10 CDDA...");

	scgp->cmdname = "Read10 NEC";

	if (scg_cmd(scgp)) return 0;

	/* has all or something been read? */
	return SectorBurstVal - scg_getresid(scgp)/CD_FRAMESIZE_RAW;
}


/* Read max. SectorBurst of cdda sectors to buffer
   via vendor-specific ReadCdda(12) command */
int ReadCdda12 (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal )
{
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)p;
        scmd->size = SectorBurstVal*CD_FRAMESIZE_RAW;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G5_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g5_cdb.cmd = 0xd8;		/* read audio command */
        scmd->cdb.g5_cdb.lun = scg_lun(scgp);
	scmd->cdb.g5_cdb.res |= (accepts_fua_bit == 1 ? 1 << 2 : 0);
        g5_cdbaddr(&scmd->cdb.g5_cdb, lSector);
        g5_cdblen(&scmd->cdb.g5_cdb, SectorBurstVal);

        if (scgp->verbose) fprintf(stderr, "\nReadSony12 CDDA...");

	scgp->cmdname = "Read12";

	if (scg_cmd(scgp)) return 0;

	/* has all or something been read? */
	return SectorBurstVal - scg_getresid(scgp)/CD_FRAMESIZE_RAW;
}

/* Read max. SectorBurst of cdda sectors to buffer
   via vendor-specific ReadCdda(12) command */
/*
> It uses a 12 Byte CDB with 0xd4 as opcode, the start sector is coded as
> normal and the number of sectors is coded in Byte 8 and 9 (begining with 0).
*/

int ReadCdda12Matsushita (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal )
{
	register struct	scg_cmd	*scmd = scgp->scmd;

        memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)p;
        scmd->size = SectorBurstVal*CD_FRAMESIZE_RAW;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G5_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g5_cdb.cmd = 0xd4;		/* read audio command */
        scmd->cdb.g5_cdb.lun = scg_lun(scgp);
	scmd->cdb.g5_cdb.res |= (accepts_fua_bit == 1 ? 1 << 2 : 0);
        g5_cdbaddr(&scmd->cdb.g5_cdb, lSector);
        g5_cdblen(&scmd->cdb.g5_cdb, SectorBurstVal);

        if (scgp->verbose) fprintf(stderr, "\nReadMatsushita12 CDDA...");

	scgp->cmdname = "Read12Matsushita";

	if (scg_cmd(scgp)) return 0;

	/* has all or something been read? */
	return SectorBurstVal - scg_getresid(scgp)/CD_FRAMESIZE_RAW;
}

/* Read max. SectorBurst of cdda sectors to buffer
   via MMC standard READ CD command */
int ReadCddaMMC12 (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal )
{
	register struct	scg_cmd	*scmd;
	scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)p;
        scmd->size = SectorBurstVal*CD_FRAMESIZE_RAW;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G5_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g5_cdb.cmd = 0xbe;		/* read cd command */
        scmd->cdb.g5_cdb.lun = scg_lun(scgp);
        scmd->cdb.g5_cdb.res = 1 << 1; /* expected sector type field CDDA */
        g5_cdbaddr(&scmd->cdb.g5_cdb, lSector);
        g5x_cdblen(&scmd->cdb.g5_cdb, SectorBurstVal);
	scmd->cdb.g5_cdb.count[3] = 1 << 4;	/* User data */

        if (scgp->verbose) fprintf(stderr, "\nReadMMC12 CDDA...");

	scgp->cmdname = "ReadCD MMC 12";

	if (scg_cmd(scgp)) return 0;

	/* has all or something been read? */
	return SectorBurstVal - scg_getresid(scgp)/CD_FRAMESIZE_RAW;
}

int ReadCddaFallbackMMC (SCSI *scgp, UINT4 *p, unsigned lSector, unsigned SectorBurstVal )
{
	static int ReadCdda12_unknown = 0;
	int retval = -999;

	scgp->silent++;
	if (ReadCdda12_unknown 
	    || ((retval = ReadCdda12(scgp, p, lSector, SectorBurstVal)) <= 0)) {
		/* if the command is not available, use the regular
		 * MMC ReadCd 
		 */
		if (retval <= 0 && scg_sense_key(scgp) == 0x05) {
			ReadCdda12_unknown = 1;
		}
		scgp->silent--;
		return ReadCddaMMC12(scgp, p, lSector, SectorBurstVal);
	}
	scgp->silent--;
	return retval;
}

/* Read the Sub-Q-Channel to SubQbuffer. This is the method for
 * drives that do not support subchannel parameters. */
static subq_chnl *ReadSubQFallback (SCSI *scgp, unsigned char sq_format, unsigned char track)
{
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)SubQbuffer;
        scmd->size = 24;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x42;		/* Read SubQChannel */
						/* use LBA */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.addr[0] = 0x40; 	/* SubQ info */
        scmd->cdb.g1_cdb.addr[1] = 0;	 	/* parameter list: all */
        scmd->cdb.g1_cdb.res6 = track;		/* track number */
        g1_cdblen(&scmd->cdb.g1_cdb, 24);

        if (scgp->verbose) fprintf(stderr, "\nRead Subchannel_dumb...");

	scgp->cmdname = "Read Subchannel_dumb";

	if (scg_cmd(scgp) < 0) {
	  fprintf( stderr, "Read SubQ failed\n");
	}

	/* check, if the requested format is delivered */
	{ unsigned char *p = (unsigned char *) SubQbuffer;
	  if ((((unsigned)p[2] << 8) | p[3]) /* LENGTH */ > ULONG_C(11) &&
	    (p[5] >> 4) /* ADR */ == sq_format) {
	    return SubQbuffer;
	  }
	}

	/* FIXME: we might actively search for the requested info ... */
	return NULL;
}

/* Read the Sub-Q-Channel to SubQbuffer */
subq_chnl *ReadSubQSCSI (SCSI *scgp, unsigned char sq_format, unsigned char track)
{
        int resp_size;
	register struct	scg_cmd	*scmd = scgp->scmd;

        switch (sq_format) {
          case GET_POSITIONDATA:
            resp_size = 16;
	    track = 0;
          break;
          case GET_CATALOGNUMBER:
            resp_size = 24;
	    track = 0;
          break;
          case GET_TRACK_ISRC:
            resp_size = 24;
          break;
          default:
                fprintf(stderr, "ReadSubQSCSI: unknown format %d\n", sq_format);
                return NULL;
        }

	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->addr = (caddr_t)SubQbuffer;
        scmd->size = resp_size;
        scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
        scmd->cdb_len = SC_G1_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g1_cdb.cmd = 0x42;
						/* use LBA */
        scmd->cdb.g1_cdb.lun = scg_lun(scgp);
        scmd->cdb.g1_cdb.addr[0] = 0x40; 	/* SubQ info */
        scmd->cdb.g1_cdb.addr[1] = sq_format;	/* parameter list: all */
        scmd->cdb.g1_cdb.res6 = track;		/* track number */
        g1_cdblen(&scmd->cdb.g1_cdb, resp_size);

        if (scgp->verbose) fprintf(stderr, "\nRead Subchannel...");

	scgp->cmdname = "Read Subchannel";

  if (scg_cmd(scgp) < 0) {
    /* in case of error do a fallback for dumb firmwares */
    return ReadSubQFallback(scgp, sq_format, track);
  }

  return SubQbuffer;
}

/********* non standardized speed selects ***********************/

void SpeedSelectSCSIToshiba (SCSI *scgp, unsigned speed)
{
  static unsigned char mode [4 + 3];
  unsigned char *page = mode + 4;
  int retval;

  memset((caddr_t)mode, 0, sizeof(mode));
  /* the first 4 mode bytes are zero. */
  page[0] = 0x20;
  page[1] = 1;
  page[2] = speed;   /* 0 for single speed, 1 for double speed (3401) */

  if (scgp->verbose) fprintf(stderr, "\nspeed select Toshiba...");

  scgp->silent++;
  /* do the scsi cmd */
  if ((retval = mode_select(scgp, mode, 7, 0, scgp->inq->data_format >= 2)) < 0)
        fprintf (stderr, "speed select Toshiba failed\n");
  scgp->silent--;
}

void SpeedSelectSCSINEC (SCSI *scgp, unsigned speed)
{
  static unsigned char mode [4 + 8];
  unsigned char *page = mode + 4;
  int retval;
	register struct	scg_cmd	*scmd = scgp->scmd;

  memset((caddr_t)mode, 0, sizeof(mode));
  /* the first 4 mode bytes are zero. */
  page [0] = 0x0f; /* page code */
  page [1] = 6;    /* parameter length */
  /* bit 5 == 1 for single speed, otherwise double speed */
  page [2] = speed == 1 ? 1 << 5 : 0;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
  scmd->addr = (caddr_t)mode;
  scmd->size = 12;
  scmd->flags = SCG_DISRE_ENA;
  scmd->cdb_len = SC_G1_CDBLEN;
  scmd->sense_len = CCS_SENSE_LEN;
  scmd->cdb.g1_cdb.cmd = 0xC5;
  scmd->cdb.g1_cdb.lun = scg_lun(scgp);
  scmd->cdb.g1_cdb.addr[0] = 0 ? 1 : 0 | 1 ? 0x10 : 0;
  g1_cdblen(&scmd->cdb.g1_cdb, 12);

  if (scgp->verbose) fprintf(stderr, "\nspeed select NEC...");
  /* do the scsi cmd */

	scgp->cmdname = "speed select NEC";

  if ((retval = scg_cmd(scgp)) < 0)
        fprintf(stderr ,"speed select NEC failed\n");
}

void SpeedSelectSCSIPhilipsCDD2600 (SCSI *scgp, unsigned speed)
{
  /* MODE_SELECT, page = SCSI-2  save page disabled, reserved, reserved,
     parm list len, flags */
  static unsigned char mode [4 + 8];
  unsigned char *page = mode + 4;
  int retval;

  memset((caddr_t)mode, 0, sizeof(mode));
  /* the first 4 mode bytes are zero. */
  page[0] = 0x23;
  page[1] = 6;
  page[2] = page [4] = speed;
  page[3] = 1;

  if (scgp->verbose) fprintf(stderr, "\nspeed select Philips...");
  /* do the scsi cmd */
  if ((retval = mode_select(scgp, mode, 12, 0, scgp->inq->data_format >= 2)) < 0)
        fprintf (stderr, "speed select PhilipsCDD2600 failed\n");
}

void SpeedSelectSCSISony (SCSI *scgp, unsigned speed)
{
  static unsigned char mode [4 + 4];
  unsigned char *page = mode + 4;
  int retval;

  memset((caddr_t)mode, 0, sizeof(mode));
  /* the first 4 mode bytes are zero. */
  page[0] = 0x31;
  page[1] = 2;
  page[2] = speed;

  if (scgp->verbose) fprintf(stderr, "\nspeed select Sony...");
  /* do the scsi cmd */
  scgp->silent++;
  if ((retval = mode_select(scgp, mode, 8, 0, scgp->inq->data_format >= 2)) < 0)
        fprintf (stderr, "speed select Sony failed\n");
  scgp->silent--;
}

void SpeedSelectSCSIYamaha (SCSI *scgp, unsigned speed)
{
  static unsigned char mode [4 + 4];
  unsigned char *page = mode + 4;
  int retval;

  memset((caddr_t)mode, 0, sizeof(mode));
  /* the first 4 mode bytes are zero. */
  page[0] = 0x31;
  page[1] = 2;
  page[2] = speed;

  if (scgp->verbose) fprintf(stderr, "\nspeed select Yamaha...");
  /* do the scsi cmd */
  if ((retval = mode_select(scgp, mode, 8, 0, scgp->inq->data_format >= 2)) < 0)
        fprintf (stderr, "speed select Yamaha failed\n");
}

void SpeedSelectSCSIMMC (SCSI *scgp, unsigned speed)
{
  int spd;
	register struct	scg_cmd	*scmd = scgp->scmd;

   if (speed == 0 || speed == 0xFFFF) {
      spd = 0xFFFF;
   } else {
      spd = (1764 * speed) / 10;
   }
	memset((caddr_t)scmd, 0, sizeof(*scmd));
        scmd->flags = SCG_DISRE_ENA;
        scmd->cdb_len = SC_G5_CDBLEN;
        scmd->sense_len = CCS_SENSE_LEN;
        scmd->cdb.g5_cdb.cmd = 0xBB;
        scmd->cdb.g5_cdb.lun = scg_lun(scgp);
        i_to_2_byte(&scmd->cdb.g5_cdb.addr[0], spd);
        i_to_2_byte(&scmd->cdb.g5_cdb.addr[2], 0xffff);

        if (scgp->verbose) fprintf(stderr, "\nspeed select MMC...");

	scgp->cmdname = "set cd speed";

	scgp->silent++;
        if (scg_cmd(scgp) < 0) {
		if (scg_sense_key(scgp) == 0x05 &&
		    scg_sense_code(scgp) == 0x20 &&
		    scg_sense_qual(scgp) == 0x00) {
			/* this optional command is not implemented */
		} else {
			scg_printerr(scgp);
                	fprintf (stderr, "speed select MMC failed\n");
		}
	}
	scgp->silent--;
}

/* request vendor brand and model */
unsigned char *Inquiry ( SCSI *scgp )
{
  static unsigned char *Inqbuffer = NULL;
	register struct	scg_cmd	*scmd = scgp->scmd;

  if (Inqbuffer == NULL) {
    Inqbuffer = (unsigned char *) malloc(36);
    if (Inqbuffer == NULL) {
      fprintf(stderr, "Cannot allocate memory for inquiry command in line %d\n", __LINE__);
        return NULL;
    }
  }

  memset(Inqbuffer, 0, 36);
	memset((caddr_t)scmd, 0, sizeof(*scmd));
  scmd->addr = (caddr_t)Inqbuffer;
  scmd->size = 36;
  scmd->flags = SCG_RECV_DATA|SCG_DISRE_ENA;
  scmd->cdb_len = SC_G0_CDBLEN;
  scmd->sense_len = CCS_SENSE_LEN;
  scmd->cdb.g0_cdb.cmd = SC_INQUIRY;
  scmd->cdb.g0_cdb.lun = scg_lun(scgp);
  scmd->cdb.g0_cdb.count = 36;
        
	scgp->cmdname = "inquiry";

  if (scg_cmd(scgp) < 0)
     return (NULL);

  /* define structure with inquiry data */
  memcpy(scgp->inq, Inqbuffer, sizeof(*scgp->inq)); 

  if (scgp->verbose)
     scg_prbytes("Inquiry Data   :", (Uchar *)Inqbuffer, 22 - scmd->resid);

  return (Inqbuffer);
}

#define SC_CLASS_EXTENDED_SENSE 0x07
#define TESTUNITREADY_CMD 0
#define TESTUNITREADY_CMDLEN 6

#define ADD_SENSECODE 12
#define ADD_SC_QUALIFIER 13
#define NO_MEDIA_SC 0x3a
#define NO_MEDIA_SCQ 0x00

int TestForMedium ( SCSI *scgp )
{
	register struct	scg_cmd	*scmd = scgp->scmd;

  if (interface != GENERIC_SCSI) {
    return 1;
  }

  /* request READY status */
	memset((caddr_t)scmd, 0, sizeof(*scmd));
  scmd->addr = (caddr_t)0;
  scmd->size = 0;
  scmd->flags = SCG_DISRE_ENA | (1 ? SCG_SILENT:0);
  scmd->cdb_len = SC_G0_CDBLEN;
  scmd->sense_len = CCS_SENSE_LEN;
  scmd->cdb.g0_cdb.cmd = SC_TEST_UNIT_READY;
  scmd->cdb.g0_cdb.lun = scg_lun(scgp);
        
  if (scgp->verbose) fprintf(stderr, "\ntest unit ready...");
  scgp->silent++;

	scgp->cmdname = "test unit ready";

  if (scg_cmd(scgp) >= 0) {
    scgp->silent--;
    return 1;
  }
  scgp->silent--;

  if (scmd->sense.code >= SC_CLASS_EXTENDED_SENSE) {
    return 
      scmd->u_sense.cmd_sense[ADD_SENSECODE] != NO_MEDIA_SC ||
      scmd->u_sense.cmd_sense[ADD_SC_QUALIFIER] != NO_MEDIA_SCQ;
  } else {
    /* analyse status. */
    /* 'check condition' is interpreted as not ready. */
    return (scmd->u_scb.cmd_scb[0] & 0x1e) != 0x02;
  }
}

int StopPlaySCSI ( SCSI *scgp )
{
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
	scmd->addr = NULL;
	scmd->size = 0;
	scmd->flags = SCG_DISRE_ENA;
	scmd->cdb_len = SC_G0_CDBLEN;
	scmd->sense_len = CCS_SENSE_LEN;
	scmd->cdb.g0_cdb.cmd = 0x1b;
	scmd->cdb.g0_cdb.lun = scg_lun(scgp);

	if (scgp->verbose) fprintf(stderr, "\nstop audio play");
	/* do the scsi cmd */

	scgp->cmdname = "stop audio play";

	return scg_cmd(scgp) >= 0 ? 0 : -1;
}

int Play_atSCSI ( SCSI *scgp, unsigned int from_sector, unsigned int sectors)
{
	register struct	scg_cmd	*scmd = scgp->scmd;

	memset((caddr_t)scmd, 0, sizeof(*scmd));
  scmd->addr = NULL;
  scmd->size = 0;
  scmd->flags = SCG_DISRE_ENA;
  scmd->cdb_len = SC_G1_CDBLEN;
  scmd->sense_len = CCS_SENSE_LEN;
  scmd->cdb.g1_cdb.cmd = 0x47;
  scmd->cdb.g1_cdb.lun = scg_lun(scgp);
  scmd->cdb.g1_cdb.addr[1] = (from_sector + 150) / (60*75);
  scmd->cdb.g1_cdb.addr[2] = ((from_sector + 150) / 75) % 60;
  scmd->cdb.g1_cdb.addr[3] = (from_sector + 150) % 75;
  scmd->cdb.g1_cdb.res6 = (from_sector + 150 + sectors) / (60*75);
  scmd->cdb.g1_cdb.count[0] = ((from_sector + 150 + sectors) / 75) % 60;
  scmd->cdb.g1_cdb.count[1] = (from_sector + 150 + sectors) % 75;

  if (scgp->verbose) fprintf(stderr, "\nplay sectors...");
  /* do the scsi cmd */

	scgp->cmdname = "play sectors";

  return scg_cmd(scgp) >= 0 ? 0 : -1;
}

static caddr_t scsibuffer;	/* page aligned scsi transfer buffer */

void init_scsibuf(SCSI *scgp, unsigned amt)
{
	if (scsibuffer != NULL) {
		fprintf(stderr, "the SCSI transfer buffer has already been allocated!\n");
		exit(3);
	}
	scsibuffer = (char*)scg_getbuf(scgp, amt);
	if (scsibuffer == NULL) {
		fprintf(stderr, "could not get SCSI transfer buffer!\n");
		exit(3);
	}
}
