Reworked for my own needs, needs tested and tweaked