One thing I can say is that this function is waaay too big. You should factor parts out to smaller functions so it's easier to see one level of abstraction at a time. Hide implementation details behind intention-revealing function names. That's one way to get a handle on the complexity of the code.
Practice only makes habit, only perfect practice makes perfect.
So, practice mindfully. Practice doing the right things and doing things right. — Junilu