fixed awful spaghetti code