I've reworked this whole function. Please re-read and let me know if any of the issues identified here still apply :)