refactored a bit after consulting Duda