Somehow messy code yet, but working.