#!/usr/bin/env python3
import sys
import tempfile
from optparse import OptionParser


def log(message,*formatting):
    print(message.format(*formatting),file=sys.stderr)

def sortVCF(args):
    import sys,os
    vcf_file = args.vcf
    fasta_file = args.fasta
    out = args.out

    headers = list()
    variants = list()
    cur_byte = 0
    chroms = list() 
    temps  = dict()
    log("Sorting {}",vcf_file)
    # Get the chromosome order
    with open(fasta_file,'r') as FASTA:
        for line in FASTA:
            if line.startswith('>'):
                chrom,*info = line.strip().lstrip('>').split()
                log("Found chromosome {}",chrom)
                chroms.append(chrom)
                temps[chrom] = tempfile.NamedTemporaryFile('w') 
    # Get headers and extract positions with file byte offsets
    log("Reading in VCF: {}",vcf_file)
    with open(vcf_file,'r') as VCF:
        for i,line in enumerate(VCF):
            if line.startswith("#"):
                headers.append(line.strip())
            else:
                chrom,pos,*junk = line.split()
                temps[chrom].write(line)
    # close all temp files
    for key,val in temps.items():
        log("flushing tmp file: {}",key)
        val.flush()
    log("sorting chroms")
    with open(out,'w') as OUT:
        # print headers
        print("\n".join(headers),file=OUT)
        for chrom in chroms:
            # read in that chroms bullshit
            with open(temps[chrom].name,'r') as CHROM:
                variants =  CHROM.readlines()
                # sort by position
                variants.sort(key=lambda x: int(x.split()[1]))
                log("printing chrom {}",chrom)
                print("".join(variants),file=OUT,end="")
                temps[chrom].close()

@@ -43,16 +43,32 @@
 empfile%0A
+import resource%0A
 from opt
@@ -93,16 +93,50 @@
 nParser%0A
+from ponytools.Fasta import Fasta%0A
 %0A%0Adef lo
@@ -421,24 +421,25 @@
 s  = dict()%0A
+%0A
     log(%22Sor
@@ -496,170 +496,204 @@
     
-with open(fasta_file,'r') as FASTA:%0A        for line in FASTA:%0A            if line.startswith('%3E'):%0A                chrom,*info = line.strip().lstrip('%3E').split
+fasta = Fasta.from_file(fasta_file,nickname=(r'.*chromosome (%5B%5CdX%5D+).*',r'chr%5C1')) %0A    # Iterate through the chromosome keys and open temp files%0A    try:%0A        for chrom in fasta.chroms.keys
 ()
+:
 %0A   
@@ -705,146 +705,187 @@
     
-    log(%22Found chromosome %7B%7D%22,chrom)%0A                chroms.append(chrom)%0A                temps%5Bchrom%5D = tempfile.NamedTemporaryFile('w') 
+temps%5Bchrom%5D = tempfile.NamedTemporaryFile('w') %0A            chroms.append(chrom)%0A    except Exception as e:%0A        log('%7B%7D: try increasing the open file limit on your system',e)
 %0A   
@@ -1200,24 +1200,120 @@
 ine.split()%0A
+                if chrom in fasta.nicknames:%0A                    chrom = fasta.nicknames%5Bchrom%5D%0A
             
@@ -1476,23 +1476,219 @@
 og(%22
-sorting chroms%22
+Outputting sorted chroms%22)%0A    if out == None:%0A        out = vcf_file%0A        if out.endswith('.vcf'):%0A            out = out.replace('.vcf','.sorted.vcf')%0A        else:%0A            out = out.append('.sorted.vcf'
 )%0A  

upgrade how we sort and add a test for max files open