Tested and working version. Not optimal, refreshing only when required would help, but this is close to the original solution