Replace sleep() with select()
Some debug code