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

#include "jmgraph.h"
#include "formulas.h"


#define MAX_N 102
#define EXTENSION_FILE "extensions.txt"

jmgraph *iextension(jmgraph *g, edgePair* p) {
    int v = p->v, vv = g->e[p->v][p->i];
    int u = p->u, uu = g->e[p->u][p->j];
    printf("iextension for %d %d, %d %d at distance %d\n", v, vv, u, uu, edgePairDistance(g, p));
    FILE *f = fopen(EXTENSION_FILE, "a");
    fprintf(f, "iextension for %d %d, %d %d at distance %d\n", v, vv, u, uu, edgePairDistance(g, p));
    fclose(f);

    jmgraph *h = newCubicGraph(g->n + 2);
    for (int x = 0; x < g->n; x++) {
        for (int k = 0; k < g->maxDegree; k++) {
            h->e[x][k] = g->e[x][k];
        }
    }
    removeEdge(h, v, p->i);
    removeEdge(h, u, p->j);
    int x = g->n, y = g->n + 1;
    addEdge(h, x, y);
    addEdge(h, x, v);
    addEdge(h, x, vv);
    addEdge(h, y, u);
    addEdge(h, y, uu);
    return h;
}


int main() {
    //srand(time(NULL));
    int count;
    jmgraph **graphs = readGraphsFromFileBA("/home/janko/praca/vyskum/data/snarks/martin/SKLAD/XMA1.52", &count);
    jmgraph *g = graphs[0]; free(graphs);
    while (g->n < MAX_N) {
        FILE *output = fopen("generatedByExtension.g6", "a");
        char *s = writeGraph6(g);
        fprintf(output, "%s\n", s);
        free(s); fclose(output);
        
        edgePair *bestPair = NULL;
        int bestDistance = -1;
        for (int v = 0; v < g->n; v++) {
            printf("%d ", v); fflush(stdout);
            for (int i = 0; i < g->maxDegree; i++) {
                for (int u = v+1; u < g->n; u++) {
                    for (int j = 0; j < g->maxDegree; j++) {
                        if ((g->e[v][i] == u) || (g->e[u][j] == v) || (g->e[u][j] == g->e[v][i]))
                            continue;
                        edgePair *pair = (edgePair *) malloc(sizeof(edgePair));
                        pair->v = v; pair->i = i;
                        pair->u = u; pair->j = j;
                        int distance = edgePairDistance(g, pair);
                        if ((distance > bestDistance) && isRemovableEdgePair(g, pair)) {
                            bestDistance = distance;
                            bestPair = pair;
                        } else {
                            free(pair);
                        }
                    }
                }                
            }
        }
        printf("\n");

        if (bestPair != NULL) {
            jmgraph *h = iextension(g, bestPair);
            free(bestPair);
            free(g);
            g = h;
        } else {
            printf("no removable pairs of edges\n");
            break;
        }
    }
    
    return 0;
}
