This function is hard to follow, I suggest cutting it into smaller pieces. Especially parts where checks are done vs parts where sig is changed.