include("libpnamnaalign.jl")
using DataFrames

function main(setsfile, pairsfile)
    dfsets = readtable(setsfile,header=true)
    dfpairs = readtable(pairsfile,header=true)

    for i = 1:size(dfpairs,1)
        algo = dfpairs[i,:algorithm_name]
        if startswith(algo,"M2P_")
            algo = algo[5:end]
        else
            error("bad algo name?")
        end
        netset = split(dfpairs[i,:networks_group],'_')[1]
        alnfile = dfpairs[i,:aln_file]
        println("Writing algorithm_name = $algo, networks_group = $netset to alignment file $alnfile")

        # same algo and network set
        df = dfsets[(dfsets[:networks_group].==netset) .& (dfsets[:algorithm_name].==algo),:]
        if size(df,1) != 1 error("no df match") end

        nts = readgwlist(dfpairs[i,:networks_file])
        nodeset = Set{String}()
        for nt in nts
            union!(nodeset, nt.nodes)
        end

        fdin = open(df[1,:aln_file],"r")
        mkpath(dirname(dfpairs[i,:aln_file]))
        fdout = open(dfpairs[i,:aln_file],"w")
        for line in eachline(fdin)
            vals = split(strip(line))
            valsout = filter(x -> x in nodeset, vals)
            if length(valsout) > 1
                for x in valsout
                    print(fdout,x," ")
                end
                println(fdout)
            end
        end
        close(fdin)
        close(fdout)
    end
end
main(ARGS[1], ARGS[2])
