Functional version of the code

It works! I'm going to bed now, so not integrating your previous merges
right now, I'll probably have time to look at it tomorrow. Let me know
if you see any bugs!
Merge squashing