I would have to look more at the code, but does this do?