Added several debug statements, added perror(), enhanced wait algorithm