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

set<pair<string, string> > es;

set<string> labels;

map<string, vector<string>> edges_of;

#include "txtcsv.h"

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

  int selfloops = 0;
  
  FILE *f = fopen(argv[1], "r");
  if(!f) { printf("file missing: %s\n", argv[1]); exit(1); }
  while(!feof(f)) {
    char a[100], b[100];
    a[0] = 0;
    fscanf(f, "%s%s", a, b);
    if(a[0] == 0) break;
    string sa = a, sb = b;
    for(char& ch: sa) if(ch == '/') ch = '_';
    for(char& ch: sb) if(ch == '/') ch = '_';
    es.emplace(sa, sb);
    labels.insert(sa);
    labels.insert(sb);
    }
  int dir = 0;

  printf("a\n");

  printf("b\n");
  for(auto k: labels) {
    for(auto i: labels) if(es.count({i, k})) for(auto j: labels) if(es.count({k, j}) && !es.count({i, j})) es.insert({i, j});
    }

  printf("c\n");
  for(auto e: es) { if(e.first == e.second) selfloops++; else  if(es.count({e.second, e.first})) dir++; }
  printf("directed: %d/%d, selfloops = %d\n", dir, int(es.size()), selfloops);

  for(auto e: es) {
    edges_of[e.first].push_back(e.second);
    }

  string root = *labels.begin();
  int N = edges_of.size();
  for(auto i: labels) if(edges_of[i].size() > edges_of[root].size()) root = i;

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

  txt = fopen(argv[2], "w");
  csv = fopen(argv[3], "w");
  fprintf(csv, "id1,id2,weight\n");

  int qty = 0;
  int nodes = 0;

  for(auto at: labels) {
    for(string& v: edges_of[at]) edge(at, v);
    }

  clos();
  return 0;
  }
