apply improvements suggested in SO question