#include <vector>
#include <map>
#include <string>

using namespace std;

vector<string> ids = {""};

map<string, int> its;

vector<pair<int, int>> edges;

vector<vector<int>> edges_of;

int N;

int id_of(string s) {
  if(its.count(s)) return its[s];
  ids.push_back(s);
  return its[s] = ++N;
  }

int main(int argc, char **argv) {

  int seed = 1;

  if(argc > 1) seed = atoi(argv[1]);

  char buf1[200], buf2[200];
  while(scanf("%s%s", buf1, buf2) == 2) {
    edges.emplace_back(id_of(buf1), id_of(buf2));
    }

  FILE *f = fopen("data-for-louvain.txt", "wt");
  for(auto [a, b]: edges) fprintf(f, "%d %d\n", a-1, b-1);
  fclose(f);

  f = fopen("louvain-seeded.R", "wt");
  fprintf(f, "set.seed(%d)\n", seed);
  fprintf(f, "source(\"louvain-community.R\")\n", seed);
  fclose(f);

  system("R --no-save < louvain-seeded.R > /dev/null");

  vector<vector<int>> data;

  f = fopen("communities.txt", "rt");
  while(!feof(f)) {
    data.emplace_back();
    data.back().resize(N);
    for(int i=0; i<N; i++) fscanf(f, "%d", &data.back()[i]);
    }
  data.pop_back();
  printf("%% number of levels = %d\n", int(data.size()));
  fflush(stdout);
  fclose(f);

  printf("pkg load symbolic\n");
  printf("pkg load statistics\n");
  printf("0;\n");
  printf("rand(\"state\", %d);\n", seed);
  printf("function ds(t)\n");
  printf("end;\n");
  printf("ds(N = %d)\n", N);
  printf("ds(x = sparse(N, N))\n");
  for(auto e: edges) printf("ds(x(%d,%d) = 1)\n", e.first, e.second);
  for(auto e: edges) printf("ds(x(%d,%d) = 1)\n", e.second, e.first);

  auto lastlev = data.back(); data.pop_back();
  
  printf("ds(label = [");
  for(int i: lastlev) printf("%d,", i);
  printf("])\n");
  

  printf("[ Q,w ] = CalQ(x, label );\n");
  printf("order=LocOrder2(w); \n");

  while(data.size()) {
    auto nextlev = data.back(); data.pop_back();

    printf("ds(label1 = [");
    for(int i: nextlev) printf("%d,", i);
    printf("])\n");

    printf("[ order1 ] = LocNextOrder( x, label, label1, order );\n");
    printf("ds(label = label1);\n");
    printf("ds(order = order1);\n");
    }

  printf("theta=InitCoord_1(x,label,order);\n");

  f = fopen("gamma.txt", "rt");
  double gamma;
  fscanf(f, "%lf", &gamma);
  fclose(f);

  printf("r=GetR( x, %.6f);\n", gamma);


  printf("printf(\"n R alpha T\\n%%d 0 0 0\\n\", %d);\n", N);
  for(int i=1; i<=N; i++) {
    printf("printf(\"%s %%.20f %%.20f\\n\", r(%d), theta(%d) * 180 / pi);\n", ids[i].c_str(), i, i);
    }

  return 0;
  }
