Reference and modified code from @arnastia