First working version. Needs clean-up and commenting