Updated with local vars and better debugging