added object-oriented solution (slower); fixed output indentation