rearranged and simplified scaling code