added changes made by Stephen. Edited them to work with current code