Added some robustness to pwait.