def rects_merge(rects):
    """ Merge a list of rectangle (xywh) tuples.
        Returns a list of rectangles that cover the same 
        surface. This is not necessarily optimal though.
        
        >>> rects_merge([(0,0,1,1),(1,0,1,1)])
        [(0, 0, 2, 1)]
    """
    def stack(rects, horizontal=False):
        """ Stacks rectangles that connect in either horizontal
            or vertical direction.
        """
        if horizontal:
            rects = [(y,x,h,w) for (x,y,w,h) in rects]
        rects.sort()
        newrects = []
        i = 0
        while i < len(rects):        
            (x1,y1,w1,h1) = rects[i]
            # Initialize new rect to this one
            nr = [x1,y1,w1,h1]
            # While the next rectangle connects to this one:
            while (i+1 < len(rects) and 
                    nr[0] == rects[i+1][0] and 
                    nr[2] == rects[i+1][2] and 
                    nr[1]+nr[3] == rects[i+1][1]):
                # Increase height of the current new rect
                nr[3] += rects[i+1][3]
                i += 1
            i += 1
            newrects.append(tuple(nr))
        # Flip rects back if we were stacking horizontally
        if horizontal:
            newrects = [(x,y,w,h) for (y,x,h,w) in newrects]
        return newrects
    # Stack twice, once in each direction
    return stack(stack(rects),horizontal=True)