Added threading and fixed minor bugs