stack based version as per jeffreykegler