Ported the code over from the last attempt and restructured.