Pretty much copied and pasted code from BBFS