It shouldn't be necessary to call all of these functions twice -- the first time you're just throwing away the return value. For instance, lines 28 and 26 could be removed here.