move duplicate code into separate function
move some code inside _X11 ifdef