code refactored by @delfrrr's advice