Condensed and checked code. Integrated with visualization.