This code needs serious cleanup