Refactored thanks to @xuwei-k