#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "jmgraph.h"


void incorrectParameters() {
    fprintf(stderr, "Incorrect command line parameters, use 'showgraph <g6/ba> <filename> <graph index (starting from 1)> [first red vertex]'\n");
    exit(1);
}


char *neatoRepresentation(jmgraph *g, int firstRedVertex) {
    char s[1000000]; s[0] = '\0';
    strcpy(s, "graph {\noverlap = false;\nsplines = true;\nsep=.3;\nnode[margin=0, fontsize=12, shape=circle, height=.3, width=.3];\n");
    char *t = s + strlen(s);
    if (firstRedVertex < g->n) {
        char *a = "{node [color=red, style=filled]";
        strcpy(t, a); t += strlen(a);
        for (int v = firstRedVertex; v < g->n; v++) {
            char x[100];
            sprintf(x, "%d ", v);
            strcpy(t, x); t += strlen(x);
        }
        a = ";}\n";
        strcpy(t, a); t += strlen(a);
    }
    for (int v = 0; v < g->n; v++) {
        for (int i = 0; i < g->maxDegree && g->e[v][i] != -1; i++) {
            int u = g->e[v][i];
            if (u > v) {
                char a[1000]; a[0] = '\0';
                sprintf(a, "%d -- %d;\n", v, u);
                strcpy(t, a);
                t += strlen(a);
            }
        }
    }
    strcpy(t, "}\n");
    return strdup(s);
}


int main(int argc, char **argv) {
    if (argc < 4)
        incorrectParameters();

    char *filename = argv[2];
    int graphNumber = strtol(argv[3], NULL, 10) - 1;

    int nGraphs;
    jmgraph **graphs;
    if (!strcasecmp(argv[1], "g6"))
        graphs = readGraphsFromFileG6(filename, &nGraphs);
    else if (!strcasecmp(argv[1], "ba"))
        graphs = readGraphsFromFileG6(filename, &nGraphs);
    else
        incorrectParameters();

    if (graphNumber >= nGraphs) {
        fprintf(stderr, "There is no such graph in the input file\n");
        exit(1);
    }

    jmgraph *g = graphs[graphNumber];
//    printf("%d\n", g->n);
    int firstRedVertex = (argc >= 5) ? strtol(argv[4], NULL, 10) : g->n + 1;
    
    char *r = neatoRepresentation(g, firstRedVertex);
//    printf("%s", r);
    char command[1000000];
    sprintf(command, "echo \"%s\" | neato -Tpdf > myneato_%s_%d.pdf", r, filename, graphNumber);
    free(r);

    system(command);

    return 0;
}
