'Fix the grade assigned to a StudentModule'

def fix_studentmodule_grade(self, module, save_changes):

    module_state = module.state
    if (module_state is None):
        LOG.info(u'No    state    found    for    %s    module    %s    for    student    %s    in    course    %s', module.module_type, module.module_state_key, module.student.username, module.course_id)
        return
    state_dict = json.loads(module_state)
    self.num_visited += 1
    student_answers = state_dict['student_answers']
    if ((not student_answers) or (len(student_answers) == 0)):
        if (module.grade != 0):
            log_msg = (u'No    answer    found    but    grade    %(grade)s    exists    for    %(type)s    module    %(id)s    for    student    %(student)s    ' + u'in    course    %(course_id)s')
            LOG.error(log_msg, {'grade': module.grade, 'type': module.module_type, 'id': module.module_state_key, 'student': module.student.username, 'course_id': module.course_id})
        else:
            log_msg = (u'No    answer    and    no    grade    found    for    %(type)s    module    %(id)s    for    student    %(student)s    ' + u'in    course    %(course_id)s')
            LOG.debug(log_msg, {'grade': module.grade, 'type': module.module_type, 'id': module.module_state_key, 'student': module.student.username, 'course_id': module.course_id})
        return
    correct_map = CorrectMap()
    if ('correct_map' in state_dict):
        correct_map.set_dict(state_dict['correct_map'])
    correct = 0
    for key in correct_map:
        correct += correct_map.get_npoints(key)
    if (module.grade == correct):
        log_msg = u'Grade    matches    for    %(type)s    module    %(id)s    for    student    %(student)s    in    course    %(course_id)s'
        LOG.debug(log_msg, {'type': module.module_type, 'id': module.module_state_key, 'student': module.student.username, 'course_id': module.course_id})
    elif save_changes:
        log_msg = (u'Grade    changing    from    %(grade)s    to    %(correct)s    for    %(type)s    module    ' + u'%(id)s    for    student    %(student)s    in    course    %(course_id)s')
        LOG.debug(log_msg, {'grade': module.grade, 'correct': correct, 'type': module.module_type, 'id': module.module_state_key, 'student': module.student.username, 'course_id': module.course_id})
        module.grade = correct
        module.save()
        self.num_changed += 1
    else:
        log_msg = (u'Grade    would    change    from    %(grade)s    to    %(correct)s    for    %(type)s    module    %(id)s    for    student    ' + u'%(student)s    in    course    %(course_id)s')
        LOG.debug(log_msg, {'grade': module.grade, 'correct': correct, 'type': module.module_type, 'id': module.module_state_key, 'student': module.student.username, 'course_id': module.course_id})
        self.num_changed += 1
