#!/usr/bin/env python

import os
from Bio.PDB import PDBParser, PDBIO
import rotlib
from rotlib.sidechains import BackboneRotamerLibrary, BBRotSwap
from rotlib.ExtendBio import PEARSStructureBuilder

LIBRARY_LOC  = "/".join( os.path.split(os.path.dirname(rotlib.__file__))[:-1] )
LIBRARY_FILE = os.path.join(LIBRARY_LOC, "rotlib/dat/bbdep_library.gz")
SEED         = 217

def run_bears(input_structure_file, output_structure_file, library_file = LIBRARY_FILE):
    """
    Run BEARS on the input structure.
    @param input_structure_file:  Path to the input structure
    @param output_structure_file: Path to the output structure
    @param library_file: Path to the library file ("library.gz") for PEARS.
    """
    builder = PEARSStructureBuilder()
    p = PDBParser(QUIET=True, structure_builder=builder)
    s = p.get_structure('input_file', input_structure_file)
    rl = BackboneRotamerLibrary(library_file)

    rs = BBRotSwap(s, rl)
    rs.verbose = True
    chains = "".join([ c.id for c in s.get_chains() ])
    rs.swap(chains=chains)

    io = PDBIO()
    io.set_structure(rs.structure)
    io.save(output_structure_file)
