Code has been cleaned up and reduced significantly. It also now works.