Query optimization + code cleanup