#!/usr/bin/python
import sys
import os.path
import re

directory = sys.argv[1]

def readNetworks(directory):
    networks = []
    for name in os.listdir(directory):
        result = re.match('^\.',name)
        if(result):
            continue
        parts = re.split('_',name)
        go=False
        j=0
        i=0
        fitness=""
        concost=""
        mod=""
        for part in parts:
            if(go):
                if(j==0):
                    fitness = str(float(part))
                elif(j==1):
                    strippedPart = re.sub('-','',part)
                    strippedPart = re.sub('\..*','',strippedPart)
                    concost = strippedPart
                elif(j==2):
                    mod=str(float(part))
                j+=1
            if(i>=2):
                go=True
            i+=1
        
        networks.append([fitness, concost, mod, directory + "/" + name[:-4]])
    return networks

def sortNetworks(networks):
    networks = sorted(networks, key=lambda indiv: indiv[2], reverse=True)
    networks = sorted(networks, key=lambda indiv: indiv[0], reverse=True)
    return networks

def write(networks):
    i=1
    scriptFile  = open(directory + ".tex",'w',)
    for network in networks:
        scriptFile.write( "        \\begin{subfigure}[b]{0.3\\textwidth}\n")
        scriptFile.write( "            \\centering\n")
        scriptFile.write( "            \\includegraphics[width=\\textwidth]{{" + network[3] + "}.pdf}\n")
        scriptFile.write( "            \\caption{\\tiny F:" + network[0] + "\\\\ C:"+ network[1] + " M:" + network[2] + "}\n")
        scriptFile.write( "            \\label{fig:" + directory + str(i) + "}\n")
        scriptFile.write( "        \\end{subfigure}%\n")
        if(i%3==0):
            scriptFile.write( "\n")
        i+=1
     
networks = readNetworks(directory)
networks = sortNetworks(networks)
write(networks)
