Almost finished. TODO: lock