fixed up code a bit. At the moment our current algorithm causes seg faults with certain inputs