Refactored Nistan's code