not my original code, just a few modifications, credits to martin ruks @ MWR