/*
 * tools/lib/debug.c
 *
 * Copyright (C) 1997 - 2001  Heinz Mauelshagen, Sistina Software
 *
 * June 1997
 * January 2000
 * January,April 2001
 *
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

/*
 * Changelog
 *
 *    30/01/2000 - extended va buffer
 * 		- implemented debug_enter()/debug_leave()
 *    23/01/2001 - changed to use lvm_log [JT]
 *    19/02/2001 - changed names to have lvm_ prefix [JT]
 *    09/04/2001 - moved var definition into if ( opt_d > 0)
 *
 */

#ifdef DEBUG
#include "liblvm.h"
#define	BUFLEN	512
static int call_depth = 0;

static void _debug_out(char *message) {
   char buffer[64], *ptr, c;
   int i, n;

   n = sizeof(buffer) - 4;
   n = (call_depth < n) ? call_depth : n;
   ptr = buffer;
   c = call_depth > 9 ? 'A' - 10 + call_depth : '0' + call_depth;
   *ptr++ = '<';

   for(i = 0; i < n; i++)
     *ptr++ = c;
   *ptr++ = '>';
   *ptr = '\0';

   /* just using fatal here to ensure it's displayed */
   print_log(LOG_FATAL, "%s %s", buffer, message);
}


void lvm_debug(const char *fmt, ...) {

   if ( opt_d > 0) {
      va_list val;
      char buf[BUFLEN];

      if ( call_depth < 0) call_depth = 0;
      va_start ( val, fmt);
      vsprintf ( buf, fmt, val);
      va_end ( val);
      _debug_out(buf);
   }
}


void lvm_debug_enter(const char *fmt, ...) {
   if ( opt_d > 0) {
      va_list val;
      char buf[BUFLEN];

      call_depth++;
      va_start ( val, fmt);
      vsprintf ( buf, fmt, val);
      va_end ( val);
      _debug_out(buf);
   }
}


void lvm_debug_leave(const char *fmt, ...) {
   if ( opt_d > 0) {
      va_list val;
      char buf[BUFLEN];

      va_start ( val, fmt);
      vsprintf ( buf, fmt, val);
      va_end ( val);
      _debug_out(buf);
      call_depth--;
   }
}
#endif
