Got this working, but maybe not for large values of T.