#include "graph_char_array.h"

graph_t graph_new(node_t nnodes) {
  return calloc(nnodes*(nnodes+1)/2,sizeof(char));
}

void graph_free(graph_t g) {
  free(g);
}

int graph_get_edge(graph_t g, node_t i, node_t j) {
  return (int)g[graph_idx(i,j)];
}

void graph_set_edge(graph_t g, node_t i, node_t j) {
  g[graph_idx(i,j)]=1;
}

void graph_del_edge(graph_t g, node_t i, node_t j) {
  g[graph_idx(i,j)]=0;
}

int graph_flip_edge(graph_t g, node_t i, node_t j) {
  return (int)(g[graph_idx(i,j)]^=1);
}

void graph_show(graph_t g, node_t n) {
  node_t i,j;
  for (i=0; i<n; i++) {
    for (j=0; j<n; j++) {
      if (i<j) {
        if (graph_get_edge(g,i,j)) printf("1"); else printf("0");
      } else {
        printf(" ");
      }
    }
    printf("\n");
  }
}

node_t graph_count_edges(graph_t g, node_t n) {
  node_t i,j,c=0;
  for (i=0; i<n; i++)
    for (j=i+1; j<n; j++) if (graph_get_edge(g,i,j)) c++;
  return c;
}

/*
void graph_show_edge_list(graph_t b, node_t n) { // TODO
}
*/

void graph_write_dotfile(char* fn, graph_t g, node_t n) {
  int i,j;
  FILE *f=fopen(fn,"w");
  fprintf(f,"graph_t foo {\n");
  fprintf(f,"  /* automatically generated by graph_write_dotfile */\n");
  fprintf(f,"  graph_t [fontcolor=green,fontsize=10,center=true,ratio=1,size=8,8];\n  node  [shape=\"circle\",fixedsize=\"true\"] \n  node  [color=green,fontcolor=red,fontsize=8,height=0.2] \n  edge  [color=blue];\n");
  for (i=0; i<n; i++) for (j=i+1; j<n; j++)
    if (graph_get_edge(g,i,j)) fprintf(f,"  %d--%d;\n",i,j);
  fprintf(f,"} /* end graph_t */\n");
  fclose(f);
  fprintf(stderr,"Now do: cat %s | neato -Tps | gv -\n",fn);
}
