extracted and refactored from personal project;