Tried to fix Magic by adding some locks and cleaned up code