working version merged with Alex's code