#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) {
  if(argc != 2) { printf("error: no dimension\n"); exit(1); }
  int dim = argv[1][0] - '0';
  if(dim != 2 && dim != 3) { printf("error: wrong dimension\n"); exit(1); }

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

  printf("pkg load symbolic\n");
  printf("pkg load statistics\n");
  printf("0;\n");
  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);

  if(dim == 2)
    printf("coords_emb = coalescent_embedding(x, 'RA1', 'LE', 'EA', 2);\n");
  else
    printf("coords_emb = coalescent_embedding(x, 'RA1', 'ISO', 'original', 3);\n");

  if(dim == 3) {
    FILE *f = fopen("coalescent_embedding/usage_example/graphallshortestpaths.m", "w");
    fprintf(f, "function kernel = graphallshortestpaths(a,b,c)\n");
    fprintf(f, "kernel = [\n");
    edges_of.resize(N);
    for(auto e: edges) edges_of[e.first-1].push_back(e.second-1), edges_of[e.second-1].push_back(e.first-1);
    for(int i=0; i<N; i++) {
      vector<int> dists(N, 999999999);
      vector<int> q;
      auto visit = [&] (int pos, int d) {
        if(dists[pos] > d) dists[pos] = d, q.push_back(pos);
        };
      visit(i, 0);
      for(int x=0; x<int(q.size()); x++) {
        int j1 = q[x], d = dists[j1] + 1;
        for(auto j2: edges_of[j1]) visit(j2, d);
        }
      for(int x=0; x<N; x++) fprintf(f, "%d%c", dists[x], ",;" [x == N-1]);
      fprintf(f, "\n");
      }
    fprintf(f, "];\nend\n");
    fclose(f);
    }
  
  if(dim == 2) printf("printf(\"n R alpha T\\n%%d 0 0 0\\n\", %d);\n", N);
  for(int i=1; i<=N; i++) {
    if(dim == 2)
      printf("printf(\"%s %%.20f %%.20f\\n\", coords_emb(%d,2), coords_emb(%d,1) * 360 / 2 / pi);\n", ids[i].c_str(), i, i);
    else {
      printf("[cx,cy,cz] = sph2cart(coords_emb(%d,1), coords_emb(%d,2), sinh(coords_emb(%d,3)));\n", i, i, i);
      printf("printf(\"%s\\n%%.20f\\n%%.20f\\n%%.20f\\n%%.20f\\n\", cosh(coords_emb(%d,3)), cx, cy, cz);\n", ids[i].c_str(), i);
      }
    }

  return 0;
  }
