int main(int argc, char* argv[])
{
  TRY_ENTRY();

  epee::string_tools::set_module_name_and_folder(argv[0]);

  std::string default_db_type = "lmdb";

  std::string available_dbs = cryptonote::blockchain_db_types(", ");
  available_dbs = "available: " + available_dbs;

  uint32_t log_level = 0;
  uint64_t block_start = 0;
  uint64_t block_stop = 0;

  tools::on_startup();

  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_log_level  = {"log-level",  "0-4 or categories", ""};
  const command_line::arg_descriptor<std::string> arg_database = {
    "database", available_dbs.c_str(), default_db_type
  };
  const command_line::arg_descriptor<uint64_t> arg_block_start  = {"block-start", "start at block number", block_start};
  const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
  const command_line::arg_descriptor<bool> arg_inputs  = {"with-inputs", "with input stats", false};
  const command_line::arg_descriptor<bool> arg_outputs  = {"with-outputs", "with output stats", false};
  const command_line::arg_descriptor<bool> arg_ringsize  = {"with-ringsize", "with ringsize stats", false};
  const command_line::arg_descriptor<bool> arg_hours  = {"with-hours", "with txns per hour", false};

  command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_database);
  command_line::add_arg(desc_cmd_sett, arg_block_start);
  command_line::add_arg(desc_cmd_sett, arg_block_stop);
  command_line::add_arg(desc_cmd_sett, arg_inputs);
  command_line::add_arg(desc_cmd_sett, arg_outputs);
  command_line::add_arg(desc_cmd_sett, arg_ringsize);
  command_line::add_arg(desc_cmd_sett, arg_hours);
  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    auto parser = po::command_line_parser(argc, argv).options(desc_options);
    po::store(parser.run(), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  mlog_configure(mlog_get_default_log_path("monero-blockchain-stats.log"), true);
  if (!command_line::is_arg_defaulted(vm, arg_log_level))
    mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
  else
    mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());

  LOG_PRINT_L0("Starting...");

  std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
  bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
  bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
  network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
  block_start = command_line::get_arg(vm, arg_block_start);
  block_stop = command_line::get_arg(vm, arg_block_stop);
  bool do_inputs = command_line::get_arg(vm, arg_inputs);
  bool do_outputs = command_line::get_arg(vm, arg_outputs);
  bool do_ringsize = command_line::get_arg(vm, arg_ringsize);
  bool do_hours = command_line::get_arg(vm, arg_hours);

  std::string db_type = command_line::get_arg(vm, arg_database);
  if (!cryptonote::blockchain_valid_db_type(db_type))
  {
    std::cerr << "Invalid database type: " << db_type << std::endl;
    return 1;
  }

  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  std::unique_ptr<Blockchain> core_storage;
  tx_memory_pool m_mempool(*core_storage);
  core_storage.reset(new Blockchain(m_mempool));
  BlockchainDB *db = new_db(db_type);
  if (db == NULL)
  {
    LOG_ERROR("Attempted to use non-existent database type: " << db_type);
    throw std::runtime_error("Attempting to use non-existent database type");
  }
  LOG_PRINT_L0("database: " << db_type);

  const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");

  try
  {
    db->open(filename, DBF_RDONLY);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, net_type);

  CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");

  tools::signal_handler::install([](int type) {
    stop_requested = true;
  });

  const uint64_t db_height = db->height();
  if (!block_stop)
      block_stop = db_height;
  MINFO("Starting from height " << block_start << ", stopping at height " << block_stop);

/*
 * The default output can be plotted with GnuPlot using these commands:
set key autotitle columnhead
set title "Monero Blockchain Growth"
set timefmt "%Y-%m-%d"
set xdata time
set xrange ["2014-04-17":*]
set format x "%Y-%m-%d"
set yrange [0:*]
set y2range [0:*]
set ylabel "Txs/Day"
set y2label "Bytes"
set y2tics nomirror
plot 'stats.csv' index "DATA" using (timecolumn(1,"%Y-%m-%d")):4 with lines, '' using (timecolumn(1,"%Y-%m-%d")):7 axes x1y2 with lines
 */

  // spit out a comment that GnuPlot can use as an index
  std::cout << ENDL << "# DATA" << ENDL;
  std::cout << "Date\tBlocks/day\tBlocks\tTxs/Day\tTxs\tBytes/Day\tBytes";
  if (do_inputs)
    std::cout << "\tInMin\tInMax\tInAvg";
  if (do_outputs)
    std::cout << "\tOutMin\tOutMax\tOutAvg";
  if (do_ringsize)
    std::cout << "\tRingMin\tRingMax\tRingAvg";
  if (do_hours) {
    char buf[8];
    unsigned int i;
    for (i=0; i<24; i++) {
      sprintf(buf, "\t%02u:00", i);
      std::cout << buf;
    }
  }
  std::cout << ENDL;

  struct tm prevtm = {0}, currtm;
  uint64_t prevsz = 0, currsz = 0;
  uint64_t prevtxs = 0, currtxs = 0;
  uint64_t currblks = 0;
  uint64_t totins = 0, totouts = 0, totrings = 0;
  uint32_t minins = 10, maxins = 0;
  uint32_t minouts = 10, maxouts = 0;
  uint32_t minrings = 50, maxrings = 0;
  uint32_t io, tottxs = 0;
  uint32_t txhr[24] = {0};
  unsigned int i;

  for (uint64_t h = block_start; h < block_stop; ++h)
  {
    cryptonote::blobdata bd = db->get_block_blob_from_height(h);
    cryptonote::block blk;
    if (!cryptonote::parse_and_validate_block_from_blob(bd, blk))
    {
      LOG_PRINT_L0("Bad block from db");
      return 1;
    }
    time_t tt = blk.timestamp;
    char timebuf[64];
    epee::misc_utils::get_gmt_time(tt, currtm);
    if (!prevtm.tm_year)
      prevtm = currtm;
    // catch change of day
    if (currtm.tm_mday > prevtm.tm_mday || (currtm.tm_mday == 1 && prevtm.tm_mday > 27))
    {
      // check for timestamp fudging around month ends
      if (prevtm.tm_mday == 1 && currtm.tm_mday > 27)
        goto skip;
      strftime(timebuf, sizeof(timebuf), "%Y-%m-%d", &prevtm);
      prevtm = currtm;
      std::cout << timebuf << "\t" << currblks << "\t" << h << "\t" << currtxs << "\t" << prevtxs + currtxs << "\t" << currsz << "\t" << prevsz + currsz;
      prevsz += currsz;
      currsz = 0;
      currblks = 0;
      prevtxs += currtxs;
      currtxs = 0;
      if (!tottxs)
        tottxs = 1;
      if (do_inputs) {
        std::cout << "\t" << (maxins ? minins : 0) << "\t" << maxins << "\t" << totins / tottxs;
        minins = 10; maxins = 0; totins = 0;
      }
      if (do_outputs) {
        std::cout << "\t" << (maxouts ? minouts : 0) << "\t" << maxouts << "\t" << totouts / tottxs;
        minouts = 10; maxouts = 0; totouts = 0;
      }
      if (do_ringsize) {
        std::cout << "\t" << (maxrings ? minrings : 0) << "\t" << maxrings << "\t" << totrings / tottxs;
        minrings = 50; maxrings = 0; totrings = 0;
      }
      tottxs = 0;
      if (do_hours) {
        for (i=0; i<24; i++) {
          std::cout << "\t" << txhr[i];
          txhr[i] = 0;
        }
      }
      std::cout << ENDL;
    }
skip:
    currsz += bd.size();
    for (const auto& tx_id : blk.tx_hashes)
    {
      if (tx_id == crypto::null_hash)
      {
        throw std::runtime_error("Aborting: tx == null_hash");
      }
      if (!db->get_tx_blob(tx_id, bd))
      {
        throw std::runtime_error("Aborting: tx not found");
      }
      transaction tx;
      if (!parse_and_validate_tx_from_blob(bd, tx))
      {
        LOG_PRINT_L0("Bad txn from db");
        return 1;
      }
      currsz += bd.size();
      currtxs++;
      if (do_hours)
        txhr[currtm.tm_hour]++;
      if (do_inputs) {
        io = tx.vin.size();
        if (io < minins)
          minins = io;
        else if (io > maxins)
          maxins = io;
        totins += io;
      }
      if (do_ringsize) {
        const cryptonote::txin_to_key& tx_in_to_key
                       = boost::get<cryptonote::txin_to_key>(tx.vin[0]);
        io = tx_in_to_key.key_offsets.size();
        if (io < minrings)
          minrings = io;
        else if (io > maxrings)
          maxrings = io;
        totrings += io;
      }
      if (do_outputs) {
        io = tx.vout.size();
        if (io < minouts)
          minouts = io;
        else if (io > maxouts)
          maxouts = io;
        totouts += io;
      }
      tottxs++;
    }
    currblks++;

    if (stop_requested)
      break;
  }

  core_storage->deinit();
  return 0;

  CATCH_ENTRY("Stats reporting error", 1);
}
int main(int argc, char* argv[])
{
  uint64_t height = 0;
  uint64_t start_block = 0;
  uint64_t end_block = 0;
  uint64_t num_blocks = 0;

  boost::filesystem::path default_data_path {tools::get_default_data_dir()};
  boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};


  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<uint32_t> arg_log_level   =  {"log-level", "", LOG_LEVEL_0};
  const command_line::arg_descriptor<uint64_t> arg_batch_size  =  {"batch-size", "", db_batch_size};
  const command_line::arg_descriptor<bool>     arg_testnet_on  = {
    "testnet"
      , "Run on testnet."
      , opt_testnet
  };
  const command_line::arg_descriptor<uint64_t> arg_block_number =
  {"block-number", "Number of blocks (default: use entire source blockchain)",
    0};

  command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
  command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_batch_size);
  command_line::add_arg(desc_cmd_sett, arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, arg_block_number);

  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  const command_line::arg_descriptor<bool> arg_batch  =  {"batch",
    "Batch transactions for faster import", true};
  const command_line::arg_descriptor<bool> arg_resume =  {"resume",
        "Resume from current height if output database already exists", true};

  // call add_options() directly for these arguments since command_line helpers
  // support only boolean switch, not boolean argument
  desc_cmd_sett.add_options()
    (arg_batch.name,  make_semantic(arg_batch),  arg_batch.description)
    (arg_resume.name, make_semantic(arg_resume), arg_resume.description)
    ;

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);


  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    po::store(po::parse_command_line(argc, argv, desc_options), vm);
    po::notify(vm);

    return true;
  });
  if (!r)
    return 1;

  int log_level = command_line::get_arg(vm, arg_log_level);
  opt_batch     = command_line::get_arg(vm, arg_batch);
  opt_resume    = command_line::get_arg(vm, arg_resume);
  db_batch_size = command_line::get_arg(vm, arg_batch_size);

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  if (! opt_batch && ! vm["batch-size"].defaulted())
  {
    std::cerr << "Error: batch-size set, but batch option not enabled" << ENDL;
    return 1;
  }
  if (! db_batch_size)
  {
    std::cerr << "Error: batch-size must be > 0" << ENDL;
    return 1;
  }

  log_space::get_set_log_detalisation_level(true, log_level);
  log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
  LOG_PRINT_L0("Starting...");

  std::string src_folder;
  opt_testnet = command_line::get_arg(vm, arg_testnet_on);
  auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
  src_folder = command_line::get_arg(vm, data_dir_arg);
  boost::filesystem::path dest_folder(src_folder);

  num_blocks = command_line::get_arg(vm, arg_block_number);

  if (opt_batch)
  {
    LOG_PRINT_L0("batch:   " << std::boolalpha << opt_batch << std::noboolalpha
        << "  batch size: " << db_batch_size);
  }
  else
  {
    LOG_PRINT_L0("batch:   " << std::boolalpha << opt_batch << std::noboolalpha);
  }
  LOG_PRINT_L0("resume:  " << std::boolalpha << opt_resume  << std::noboolalpha);
  LOG_PRINT_L0("testnet: " << std::boolalpha << opt_testnet << std::noboolalpha);

  fake_core c(src_folder, opt_testnet);

  height = c.m_storage.get_current_blockchain_height();

  BlockchainDB *blockchain;
  blockchain = new BlockchainLMDB(opt_batch);
  dest_folder /= blockchain->get_db_name();
  LOG_PRINT_L0("Source blockchain: " << src_folder);
  LOG_PRINT_L0("Dest blockchain:   " << dest_folder.string());
  LOG_PRINT_L0("Opening dest blockchain (BlockchainDB " << blockchain->get_db_name() << ")");
  blockchain->open(dest_folder.string());
  LOG_PRINT_L0("Source blockchain height: " << height);
  LOG_PRINT_L0("Dest blockchain height:   " << blockchain->height());

  if (opt_resume)
    // next block number to add is same as current height
    start_block = blockchain->height();

  if (! num_blocks || (start_block + num_blocks > height))
    end_block = height - 1;
  else
    end_block = start_block + num_blocks - 1;

  LOG_PRINT_L0("start height: " << start_block+1 << "  stop height: " <<
            end_block+1);

  if (start_block > end_block)
  {
    LOG_PRINT_L0("Finished: no blocks to add");
    delete blockchain;
    return 0;
  }

  if (opt_batch)
    blockchain->batch_start(db_batch_size);
  uint64_t i = 0;
  for (i = start_block; i < end_block + 1; ++i)
  {
    // block: i  height: i+1  end height: end_block + 1
    if ((i+1) % 10 == 0)
    {
      std::cout << "\r                   \r" << "height " << i+1 << "/" <<
        end_block+1 << " (" << (i+1)*100/(end_block+1)<< "%)" << std::flush;
    }
    // for debugging:
    // std::cout << "height " << i+1 << "/" << end_block+1
    //   << " ((" << i+1 << ")*100/(end_block+1))" << "%)" << ENDL;

    block b = c.m_storage.get_block(i);
    size_t bsize = c.m_storage.get_block_size(i);
    difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
    uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
    std::vector<transaction> txs;
    std::vector<crypto::hash> missed;

    c.m_storage.get_transactions(b.tx_hashes, txs, missed);
    if (missed.size())
    {
      std::cout << ENDL;
      std::cerr << "Missed transaction(s) for block at height " << i + 1 << ", exiting" << ENDL;
      delete blockchain;
      return 1;
    }

    try
    {
      blockchain->add_block(b, bsize, bdiff, bcoins, txs);

      if (opt_batch)
      {
        if ((i < end_block) && ((i + 1) % db_batch_size == 0))
        {
          std::cout << "\r                   \r";
          std::cout << "[- batch commit at height " << i + 1 << " -]" << ENDL;
          blockchain->batch_stop();
          blockchain->batch_start(db_batch_size);
          std::cout << ENDL;
          blockchain->show_stats();
        }
      }
    }
    catch (const std::exception& e)
    {
      std::cout << ENDL;
      std::cerr << "Error adding block " << i << " to new blockchain: " << e.what() << ENDL;
      delete blockchain;
      return 2;
    }
  }
  if (opt_batch)
  {
    std::cout << "\r                   \r" << "height " << i << "/" <<
      end_block+1 << " (" << (i)*100/(end_block+1)<< "%)" << std::flush;
    std::cout << ENDL;
    std::cout << "[- batch commit at height " << i << " -]" << ENDL;
    blockchain->batch_stop();
  }
  std::cout << ENDL;
  blockchain->show_stats();
  std::cout << "Finished at height: " << i << "  block: " << i-1 << ENDL;

  delete blockchain;
  return 0;
}