Based on work of Github user leonsas.