Dirty working version. Full comments. Needs better exception handling