# Standard interface for PNA and MNA algorithms
include("libpnamnaalign.jl")

using DataFrames
using CSV
#using JSON

function main()
    netmapsfile = ARGS[1]
    algo = ARGS[2]
    netsfile = ARGS[3]
    netsgroup = ARGS[4]
    alnfile = ARGS[5]
    nodenameskip = ARGS[6]
    statsfile = joinpath(dirname(alnfile),string("stats_",basename(alnfile),".json"))

    println("Running algo = $algo, networks_file = $netsfile, networks_group = $netsgroup, aln_file = $alnfile")

    if isfile(alnfile) && isfile(statsfile)
        println("File $alnfile already exists. Quitting.")
        exit()
    end

    netmapstable = CSV.read(netmapsfile,header=true)
    df = netmapstable[netmapstable[:networks_file].==netsfile,:]

    netlistfile = joinpath(curdirname(),"../data",netsfile)
    netfiles = vec(readdlm(netlistfile))

    gdvfilemap = getgdvfiles(netmapstable)
    gdvfiles = [gdvfilemap[x] for x in netfiles]
    evalfilemap = getevalfiles(netmapstable,netsgroup)
    evalfiles = [evalfilemap[(x,y)] for x in netfiles, y in netfiles]

    nts = readgwlist(netlistfile)
    for i = 1:length(nts)
        # randomize node order so algos don't take advantage of node order when aligning
        p = randperm(size(nts[i].G,1))
        nts[i] = Network(nts[i].G[p,p], nts[i].nodes[p])
    end

    aln,runtime = align(algo, nts, gdvfiles, evalfiles)

    mkpath(dirname(alnfile))
    println("Writing alignment to ", alnfile)
    writemaln(alnfile,aln)
    println("Writing stats file ", statsfile)
    # stats = Dict("runtime" => runtime)
    # open(statsfile,"w") do fd JSON.print(fd,stats) end
    open(statsfile,"w") do fd print(fd,"{\"runtime\":$runtime}") end
end

# julia pnamnaalign.jl ../data/netsetmaps.csv "WAVE_top" "NETWORKS/gedevo_Y2H2_yeast_human.txt" Y2H2 "ALIGNMENTS_P_P/WAVE_top/Y2H2_yeast_human.aln" 3
# julia pnamnaalign.jl ../data/netsetmaps.csv "WAVE_seq" "NETWORKS/gedevo_Y2H2_yeast_human.txt" Y2H2 "ALIGNMENTS_P_P/WAVE_seq/Y2H2_yeast_human.aln" 3
# julia pnamnaalign.jl ../data/netsetmaps.csv "GHOST_seq" "NETWORKS/gedevo_yeastlc_yeast0_yeast5.txt" "ALIGNMENTS_P_P/GHOST_seq/yeastlc_yeast0_yeast5.txt" 3
# 

#convert_raw_evals_to_each_group("../data/netmaps.csv")
main()

