
def readDuplexes(filename):
    """Return list of tuples containing pairs of resids of paired bases.
    """
    lines=open(filename).readlines()
    inHelicalSegment=False
    import string
    pairs=[]
    for line in lines:
        if (line.startswith('$ bplist')):
            inHelicalSegment=True
            pass

        if inHelicalSegment and line[0] in string.digits:
            pairs.append( [int(s) for s in line.split()] )
            #print(pairs)
            pass


        pass
    #ret.append(pairs)
    return pairs

def genRestraints(pairs,
                  dist=3.,
                  deltaLess=1.5,
                  deltaPlus=0.,
                  selTemplate=r"resid %d and not name H* and not name *'"
                  ):
    """
    From a list of pairs of residue numbers, generate a restraint table using
    the given selTemplate for each residue, and an allowed distance range of
    dist-deltaLess ... dist+deltaPlus.

    """
    ret =""
    for a,b in pairs:
        asel = selTemplate % a
        bsel = selTemplate % b
        ret += "assign (%s) (%s) %f %f %f\n" % (asel,bsel,
                                                dist,deltaLess,deltaPlus)
        pass
    return ret

if __name__=="__main__":
    pairs = readDuplexes('input_YU1A.bpl')
    #print(genRestraints(pairs))
    # print(pairs)
    # print(sum(pairs,[]))
    open('pair.tbl','w').write(genRestraints(pairs))
