script now working correctly. Could use some optimizations though.  But complete, and reasonably robust.