#include <climits>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <stdlib.h>

#include <basic_impl.hpp>
#include <io.hpp>
#include <mrozek.hpp>

#include <invariants.hpp>

using namespace ba_graph;

std::map<std::string, std::ostream *> files;
std::map<std::string, int> counts;

int count = 0;
void sigintHandler(int sig_num) { std::cout << count << std::endl; }

void callback1(Graph &g, Factory &f, int *k) {
  if (count % 1000 == 0) {
    std::cout << count << std::endl;
  }
  count++;

  auto terminals = g.list(RP::degree(1), RT::n());

  if (terminals.size() == 0)
    return;

  auto order = g.order() - terminals.size();
  int gir = girth(g);
  std::string outputFileName = "sorted2/" + std::to_string(terminals.size()) +
                               "pole/" + std::to_string(terminals.size()) +
                               "pole__g" + std::to_string(gir) + "__v" +
                               std::to_string(order);

  if (!files[outputFileName]) {
    files[outputFileName] =
        new std::ofstream(outputFileName, std::ofstream::out);
    if (!files[outputFileName]) {
      throw std::runtime_error("could not open output file");
    }
    counts[outputFileName] = 0;
  }

  write_graph6_stream(g, *files[outputFileName]);
  counts[outputFileName]++;
}

int main(int argc, char **argv) {
  signal(SIGINT, sigintHandler);
  for (int i = 1; i <= 15; i++) {
    count = 0;
    std::cout << "Now doing multipoles with: " << i << " vertices."
              << std::endl;
    std::string inputFileName =
        "pregraphs/multipoles/v" + std::to_string(i) + ".code";
    std::cout << inputFileName << std::endl;
    int k;
    read_pregraph_file<int>(inputFileName, callback1, &k);
  }

  for (auto &pair : counts) {
    std::cout << pair.first << ": " << pair.second << std::endl;
  }
  return 0;
}
