Seems to work now, cleaned up, but probably needs a code review