First working version. Not fully tested.