import json


def reset_notebook(fname, dryrun=False):
    """
    Empties the output fields and resets execution_count in all code cells in the given notebook.

    Also removes any empty code cells. The specified notebook is overwritten.

    Parameters
    ----------
    fname : str
        Name of the notebook file.
    dryrun : bool
        If True, don't actually update the file.

    Returns
    -------
    bool
        True if the file was updated or would have been updated if not a dry run.
    """
    changed = False

    with open(fname) as f:
        dct = json.load(f)

    newcells = []
    for cell in dct['cells']:
        if cell['cell_type'] == 'code':
            if cell['source']:  # cell is not empty
                if cell['execution_count'] is not None or len(cell['outputs']) > 0:
                    cell['execution_count'] = None
                    cell['outputs'] = []
                    changed = True
                newcells.append(cell)
        else:
            newcells.append(cell)

    changed |= len(dct['cells']) != len(newcells)

    dct['cells'] = newcells

    if changed and not dryrun:
        with open(fname, 'w') as f:
            json.dump(dct, f, indent=1, ensure_ascii=False)
            print(file=f)  # avoid 'no newline at end of file' message

    return changed