def _regwrite(shapelist,outfile):
    """ Writes the current shape list out as a region file """
    # This function corrects bugs and provides improvements over the pyregion's
    # ShapeList.write method in the following:
    #
    # 1. ShapeList.write crashes if regions have no comments;
    # 2. ShapeList.write converts 'exclude' ("-") regions to normal regions ("+");
    # 3. ShapeList.write does not support mixed coordinate systems in a
    #    region list.
    #
    # NOTE: This function is provided as a temoprary workaround for the above
    #    listed problems of the ShapeList.write. We hope that a future version
    #    of pyregion will address all these issues.
    #
    #TODO: Push these changes to pyregion.

    if len(shapelist) < 1:
        _print_warning("The region list is empty. The region file \"%s\" "\
                       "will be empty." % outfile)
        try:
            outf = open(outfile,'w')
            outf.close()
            return
        except IOError as e:
            cmsg = "Unable to create region file \'%s\'." % outfile
            if e.args:
                e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:]
            else:
                e.args=(cmsg,)
            raise e
        except:
            raise

    prev_cs = shapelist[0].coord_format

    outf = None
    try:
        outf = open(outfile,'w')

        attr0 = shapelist[0].attr[1]
        defaultline = " ".join(["%s=%s" % (a,attr0[a]) for a in attr0 \
                                if a!='text'])

        # first line is globals
        print("global", defaultline, file=outf)
        # second line must be a coordinate format
        print(prev_cs, file=outf)

        for shape in shapelist:
            shape_attr = '' if prev_cs == shape.coord_format \
                            else shape.coord_format+"; "
            shape_excl = '-' if shape.exclude else ''
            text_coordlist = ["%f" % f for f in shape.coord_list]
            shape_coords = "(" + ",".join(text_coordlist) + ")"
            shape_comment = " # " + shape.comment if shape.comment else ''

            shape_str = shape_attr + shape_excl + shape.name + shape_coords + \
                        shape_comment

            print(shape_str, file=outf)

    except IOError as e:
        cmsg = "Unable to create region file \'%s\'." % outfile
        if e.args:
            e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:]
        else:
            e.args=(cmsg,)
        if outf: outf.close()
        raise e
    except:
        if outf: outf.close()
        raise

    outf.close()
Writes the current shape list out as a region file