This code is a mess but it seems to work correctly with the screen scaling.