Fixed thread bugs and added comments