#include <cstdio>
#include <set>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

set<pair<int, int> > es;

vector<vector<int>> edges_of;

int main(int argc, char ** argv) {
  if(argc != 4) exit(1);
  string dirname = argv[1];

  int selfloops = 0;
  
  FILE *f = fopen(argv[1], "r");
  if(!f) { printf("file missing: %s\n", argv[1]); exit(1); }
  while(!feof(f)) {
    int a = -1, b = -1;
    fscanf(f, "%d%d", &a, &b);
    if(a == -1) break;
    if(a == b) { selfloops++; continue; }
    es.emplace(a, b);
    }
  int dir = 0;
  for(auto e: es) if(es.count({e.second, e.first})) dir++;
  printf("directed: %d/%d, selfloops = %d\n", dir, int(es.size()), selfloops);
  for(auto e: es) es.emplace(e.second, e.first);

  for(auto e: es) {
    while(edges_of.size() <= e.first) edges_of.emplace_back();
    edges_of[e.first].push_back(e.second);
    }

  int root = 0;
  int N = edges_of.size();
  for(int i=0; i<N; i++) if(edges_of[i].size() > edges_of[root].size()) root = i;

  printf("root: %d of degree %d\n", root, int(edges_of[root].size()));

  FILE *gtxt = fopen(argv[2], "w");
  FILE *gcsv = fopen(argv[3], "w");
  fprintf(gcsv, "id1,id2,weight\n");

  int qty = 0;
  int nodes = 0;

  vector<int> visited = {root};
  for(int i=0; i<int(visited.size()); i++) {
    int at = visited[i];
    for(int v: edges_of[at]) {
       fprintf(gcsv, "%d,%d,1\n", at, v);  
       fprintf(gtxt, "%d\t%d\n", at, v);  
       visited.push_back(v);
       }
    if(edges_of[at].size()) {
      nodes++;
      qty += edges_of[at].size();
      edges_of[at].clear();
      }
    }

  printf("giant: %d/%d with %d nodes\n", qty, int(es.size()), nodes);
  return 0;
  }
