I'm sorry but this so look like spaghetti code, with lots of if/callbacks. Is it possible to separate this code in smaller functions ?