Need to look into ways to speed up this function. Code was taken from another source but I have not analyzed the algorithm for potential speed ups.