updated beej's example code