Implemented a fancier version of the wait function.