applied Martin Hurton's scan() patch with slight modifications