Final working version; tested