First working version. Still needs some tweaking.