better and cleaner code (thanks to markhunte)