/* debug.cc - debugging stuff
 * Copyright 2003-2006 Bas Wijnen <wijnen@debian.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "debug.hh"
#include <string>
#include <cstdlib>

namespace
{
  bool check (std::string const &name)
  {
    char *val = std::getenv ("SHEVEK_DEBUG");
    if (!val)
      return false;
    return (std::string (":") + val + ":")
	    .find (std::string (":") + name + ":") != std::string::npos;
  }
}

namespace shevek
{
  bool _debug_startfunc = check ("startfunc");
  bool _debug_dbg = check ("dbg");

  // hexdump
  void dump (std::string const &data, std::ostream &target, char def)
  {
    unsigned l = data.size ();
    for (unsigned y = 0; y < l; y += 16)
      {
	target << std::setfill (' ') << std::setw (3) << std::hex << y << ':'
	       << std::setfill ('0');
	for (unsigned x = 0; x < 16; ++x)
	  {
	    if (y + x >= l) target << "   ";
	    else target << " " << std::setw (2)	<< std::hex
			<< unsigned (data[y + x] & 0xff);
	  }
	target << '\t';
	for (unsigned x = 0; x < 16; ++x)
	  {
	    if (y + x >= l) break;
	    if (std::isprint (data[y + x]))
	      target << data[y + x];
	    else
	      target << def;
	  }
	target << std::setfill (' ') << '\n';
      }
  }
}
