# Buggy code
def save_fields(fields, target, append=False):
    """
    Save an iterable of PP fields to a PP file.

    Args:

    * fields:
        An iterable of PP fields.
    * target:
        A filename or open file handle.

    Kwargs:

    * append:
        Whether to start a new file afresh or add the cube(s) to the end
        of the file.
        Only applicable when target is a filename, not a file handle.
        Default is False.
    * callback:
        A modifier/filter function.

    See also :func:`iris.io.save`.

    """
    # Open issues

    # Deal with:
    #   LBLREC - Length of data record in words (incl. extra data)
    #       Done on save(*)
    #   LBUSER[0] - Data type
    #       Done on save(*)
    #   LBUSER[1] - Start address in DATA (?! or just set to "null"?)
    #   BLEV - Level - the value of the coordinate for LBVC

    # *) With the current on-save way of handling LBLREC and LBUSER[0] we can't
    # check if they've been set correctly without *actually* saving as a binary
    # PP file. That also means you can't use the same reference.txt file for
    # loaded vs saved fields (unless you re-load the saved field!).

    # Set to (or leave as) "null":
    #   LBEGIN - Address of start of field in direct access dataset
    #   LBEXP - Experiment identification
    #   LBPROJ - Fields file projection number
    #   LBTYP - Fields file field type code
    #   LBLEV - Fields file level code / hybrid height model level

    if isinstance(target, six.string_types):
        pp_file = open(target, "ab" if append else "wb")
        filename = target
    elif hasattr(target, "write"):
        if hasattr(target, "mode") and "b" not in target.mode:
            raise ValueError("Target not binary")
        filename = target.name if hasattr(target, "name") else None
        pp_file = target
    else:
        raise ValueError("Can only save pp to filename or writable")

    try:
        # Save each field
        for pp_field in fields:
            # Write to file
            pp_field.save(pp_file)
    finally:
        if isinstance(target, six.string_types):
            pp_file.close()


# Traceback (thread.error)
Traceback (most recent call last):
File "/.../create_jules_ic_v2.py", line 279, in <module>
main()
File "/.../create_jules_ic_v2.py", line 274, in main
nameoffile=create_jules_ic(Ddate,INDIR,UM_FILE_IN,OUTDIR)
File "/.../create_jules_ic_v2.py", line 152, in create_jules_ic
print(type(cube_vegfrac.data <=0.0001))
File "/.../python2.7/site-packages/iris/cube.py", line 1644, in data
return self._data_manager.data
File "/.../python2.7/site-packages/iris/_data_manager.py", line 216, in data
result = as_concrete_data(self._lazy_array)
File "/.../python2.7/site-packages/iris/_lazy_data.py", line 128, in as_concrete_data
data = np.asanyarray(data.compute())
File "/.../python2.7/site-packages/dask/base.py", line 143, in compute
(result,) = compute(self, traverse=False, **kwargs)
File "/.../python2.7/site-packages/dask/base.py", line 392, in compute
results = get(dsk, keys, **kwargs)
File "/.../python2.7/site-packages/dask/threaded.py", line 75, in get
pack_exception=pack_exception, **kwargs)
File "/.../python2.7/site-packages/dask/local.py", line 521, in get_async
raise_exception(exc, tb)
File "/.../python2.7/site-packages/dask/local.py", line 290, in execute_task
result = _execute_task(task, data)
File "/.../python2.7/site-packages/dask/local.py", line 270, in _execute_task
args2 = [_execute_task(a, cache) for a in args]
File "/.../python2.7/site-packages/dask/local.py", line 271, in _execute_task
return func(*args2)
File "/.../python2.7/site-packages/dask/array/core.py", line 74, in getter
c = a[b]
File "/.../python2.7/site-packages/iris/fileformats/pp.py", line 647, in __getitem__
self.mdi, self.mask)
File "/.../python2.7/site-packages/iris/fileformats/pp.py", line 770, in _data_bytes_to_shaped_array
land_mask = mask.data.astype(np.bool)
File "/.../python2.7/site-packages/iris/fileformats/pp.py", line 1033, in data
self._data = as_concrete_data(self._data)
File "/.../python2.7/site-packages/iris/_lazy_data.py", line 128, in as_concrete_data
data = np.asanyarray(data.compute())
File "/.../python2.7/site-packages/dask/base.py", line 143, in compute
(result,) = compute(self, traverse=False, **kwargs)
File "/.../python2.7/site-packages/dask/base.py", line 392, in compute
results = get(dsk, keys, **kwargs)
File "/.../python2.7/site-packages/dask/threaded.py", line 70, in get
pool = ThreadPool(num_workers)
File "/.../python2.7/multiprocessing/pool.py", line 727, in __init__
Pool.__init__(self, processes, initializer, initargs)
File "/.../python2.7/multiprocessing/pool.py", line 159, in __init__
self._repopulate_pool()
File "/.../python2.7/multiprocessing/pool.py", line 223, in _repopulate_pool
w.start()
File "/.../python2.7/multiprocessing/dummy/__init__.py", line 75, in start
threading.Thread.start(self)
File "/.../python2.7/threading.py", line 736, in start
_start_new_thread(self.__bootstrap, ())
thread.error: can't start new thread

# Fixed code
def save_fields(fields, target, append=False):
    """
    Save an iterable of PP fields to a PP file.

    Args:

    * fields:
        An iterable of PP fields.
    * target:
        A filename or open file handle.

    Kwargs:

    * append:
        Whether to start a new file afresh or add the cube(s) to the end
        of the file.
        Only applicable when target is a filename, not a file handle.
        Default is False.

    See also :func:`iris.io.save`.

    """
    # Open issues

    # Deal with:
    #   LBLREC - Length of data record in words (incl. extra data)
    #       Done on save(*)
    #   LBUSER[0] - Data type
    #       Done on save(*)
    #   LBUSER[1] - Start address in DATA (?! or just set to "null"?)
    #   BLEV - Level - the value of the coordinate for LBVC

    # *) With the current on-save way of handling LBLREC and LBUSER[0] we can't
    # check if they've been set correctly without *actually* saving as a binary
    # PP file. That also means you can't use the same reference.txt file for
    # loaded vs saved fields (unless you re-load the saved field!).

    # Set to (or leave as) "null":
    #   LBEGIN - Address of start of field in direct access dataset
    #   LBEXP - Experiment identification
    #   LBPROJ - Fields file projection number
    #   LBTYP - Fields file field type code
    #   LBLEV - Fields file level code / hybrid height model level

    if isinstance(target, six.string_types):
        pp_file = open(target, "ab" if append else "wb")
    elif hasattr(target, "write"):
        if hasattr(target, "mode") and "b" not in target.mode:
            raise ValueError("Target not binary")
        pp_file = target
    else:
        raise ValueError("Can only save pp to filename or writable")

    try:
        # Save each field
        for pp_field in fields:
            # Write to file
            pp_field.save(pp_file)
    finally:
        if isinstance(target, six.string_types):
            pp_file.close()