#include "mcdp.h"

/**
 * Copyright (C) 2001-2006 Tino Reichardt
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#if DEBUG_CDB
void cmd_debug(char *file, int what)
{
	stralloc sa;
	int fd;
	unsigned int i;

	fd=open_append(file);
	if (fd == -1) return;

	stralloc_init(&sa);

	if (what == CDB_BEFORE) {
		if (!stralloc_cats(&sa, "\n")) die_nomem();
		if (!stralloc_cat(&sa, &cdb.name)) die_nomem();
		if (!stralloc_cats(&sa, " (fd=")) die_nomem();
		if (!stralloc_cat_uint(&sa, cd->fd)) die_nomem();
		if (!stralloc_cats(&sa, " cmdlen=")) die_nomem();
		if (!stralloc_cat_uint(&sa, cdb.cmdlen)) die_nomem();
		if (!stralloc_cats(&sa, " buflen=")) die_nomem();
		if (!stralloc_cat_uint(&sa, cdb.buflen)) die_nomem();
		if (!stralloc_cats(&sa, ")\nCDB=   ")) die_nomem();
		for (i=0; i < cdb.cmdlen; i++) {
			if (!stralloc_cat_x32pw(&sa, (unsigned char)cdb.cmd.s[i], 2, '0')) die_nomem();
			if (!stralloc_cats(&sa, " ")) die_nomem();
		}
	}

	if (what == CDB_AFTER) {
		if (!stralloc_cats(&sa, "\nRET=   ")) die_nomem();
		for (i=0; i < cdb.buflen; i++) {
			if (!stralloc_cat_x32pw(&sa, (unsigned char)cdb.buf.s[i], 2, '0')) die_nomem();
			if (!stralloc_cats(&sa, " ")) die_nomem();
		}
		if (!stralloc_cats(&sa, "\nSENSE= ")) die_nomem();
		for (i=0; i < MCDP_MAX_SENSE; i++) {
			if (!stralloc_cat_x32pw(&sa, (unsigned char)cdb.sense.s[i], 2, '0')) die_nomem();
			if (!stralloc_cats(&sa, " ")) die_nomem();
		}
		if (!stralloc_cats(&sa, "\n")) die_nomem();
	}

	(void)write(fd, sa.s, sa.len);
	(void)close(fd);
	stralloc_free(&sa);

	return;
}
#endif

