Fixed some bugs, added some cleanup/locking code