// himdformat command using libsgutils2 (included in sg3_utils package)
//
// linux: device is /dev/sgN or /dev/sdX, use sg_scan -i
// windows: use sg_scan utility to find device, usually PDx

#include <stdio.h>
#include <string.h>
#include <scsi/sg_lib.h>
#include <scsi/sg_pt.h>

#define TIMEOUT 20

int main(int argc, char ** argv)
{
	int ret;
	int slen = 0;
	int result;
	int sg_open = -1;
	struct sg_pt_base *ptvp = NULL;
	unsigned char command[12];
	unsigned char sense_buffer[32];

	if(argc < 2)
	{
	    fputs("Please specify the path to the scsi device\n",stderr);
	    return 1;
    }

// open scsi device
	sg_open = scsi_pt_open_device(argv[1], 0 ,0);
	if (sg_open < 0)
	{
	    fprintf(stderr,"%s: %s\n", argv[1], safe_strerror(-sg_open));
	    ret = SG_LIB_FILE_ERROR;
	    goto done;
    }

// prepare operation
	ptvp = construct_scsi_pt_obj();
    if (ptvp == NULL)
    {
        fputs("out of memory\n",stderr);
        goto done;
    }

// set format command
	memset(command,0,12);
	command[0] = 0xC2;	/* sony special commands */
   	command[4] = 3;     /* subcommand: format */

// setup cdb
	set_scsi_pt_cdb(ptvp, command, sizeof(command));

// setup sense buffer
	set_scsi_pt_sense(ptvp, sense_buffer, sizeof(sense_buffer));

// send command
	ret = do_scsi_pt(ptvp, sg_open, TIMEOUT, 0);
	if(ret != 0)
	{
		fprintf(stderr, "Error sending scsi command");
		goto done;
	}

// get sense data
	result = get_scsi_pt_result_category(ptvp);
	if (SCSI_PT_RESULT_GOOD == result)
	    ret = 0;
	else if (SCSI_PT_RESULT_SENSE == result)
	{
	    slen = get_scsi_pt_sense_len(ptvp);
	    ret = sg_err_category_sense(sense_buffer, slen);
	}
	else
        ret = SG_LIB_CAT_OTHER;

	fprintf(stderr, "SCSI Status: ");
	sg_print_scsi_status(get_scsi_pt_status_response(ptvp));
	fprintf(stderr, "\nSense Information: ");
	sg_print_sense(NULL, sense_buffer, slen, 0);

done:
    if (ptvp)
        destruct_scsi_pt_obj(ptvp);
    if (sg_open >= 0)
        scsi_pt_close_device(sg_open);
    return ret;
}



