First working version; needs more testing