Refactored Nitsan's code