Added changes from korshun's version