code needs cleaning up, but it works