#!/usr/bin/python
# makes a .star parfil for bfil usinf a boxfile generated by e2boxer.py

# mark the fibrils with e2boxer.py click off the micrograph to designate the next fibril
# vers 0.3 had to add the _micrograph.field_id and micrograph.id to make it work... WTF don't know what changed in bfil

vers = "0.3"

import sys
import datetime

if '-f' in sys.argv:
    yflip = True
    imgsize = float(raw_input("image size (px): "))
else:
    yflip = False
    
#-------- FUNCT: read boxfile ------#
def readboxfile(file):
    if '-r' in sys.argv[1:]:
        roundmode = True
        print "** Rounding to nearest whole number **"

    else:
        roundmode = False
        
    
    rawdata = open(file,'r').readlines()
    newcoords = []
    for i in rawdata:
        line = i.strip('\n').split('\t')
        print "DEBUG: {0}".format(line) 
        assert line[2] == line[3], 'ERROR: non-square box'
        if float(line[0]) < 0:
            x='skip'
        else:
            x = float(line[0]) + 0.5*float(line[2])
        if yflip == True:
            y = imgsize-float(line[1]) + 0.5*float(line[2])
        else:
            y = float(line[1]) + 0.5*float(line[2])
        if roundmode == True:
            newcoords.append((int(round(x)),int(round(y))))
        else:
            newcoords.append((x,y))
    return newcoords    
#-----------------------------------#

# get files to operate on
if '--help' in sys.argv:
    sys.exit('\nUSAGE: make-bfil-parfile.py <input box file> <image file> <options>\nadditional options:\n -f\tto flip over y-axis\n -r\tto round to nearest whole number')
if len(sys.argv) < 3:
    sys.exit('\nUSAGE: make-bfil-parfile.py <input box file> <image file> <options>\nadditional options:\n -f\tto flip over y-axis\n -r\tto round to nearest whole number')
inputfile = sys.argv[1]
output = open (inputfile.split('/')[-1].split('.')[0]+".star",'w')


# write file header
output.write("""# bfil par file file written {0} by make-bfil-parfile.py v{1}

data_filament

_micrograph.field_id\t{3}
_micrograph.id\t{3}
_micrograph.select\t1
_micrograph.file_name\t{2}

loop_
_filament.id
_filament.node_id
_filament.x
_filament.y
_filament.z""".format(datetime.datetime.now(),vers,sys.argv[2],sys.argv[2].split('.')[0]))

# get the boxfile data and write the data loop in the outout starfile

alldata = readboxfile(inputfile)
nodecount = 1
fibno = 1
for i in alldata:
    if i[0] == 'skip':
        nodecount = 1
        fibno += 1
    else:
        output.write("\n{3}\t{0}\t{1}\t{2}\t0".format(nodecount,i[0],i[1],fibno))
        nodecount +=1
