used code fragment from @ueshin to fix the problem in a better way