removed duplicate branches (if/else), pass by reference, math mode with \( \), changed scope of some vars, reduced assignments, fixed memory leaks