Umm - idk, i think it works

Added some conditionals to avoid off by one errors or segmentation faults. This code appears to work for synchronous threads.