import ugfx

def draw_graph(x, y, width, height, samples, scale=1.0, colour=ugfx.BLACK):
    """Draws a graph at the specified coordinates.

    Draws a graph across the full length of the specified area, capping values
    at (height / scale)
    """

    # How many samples can we fit?
    sample_width = width / (len(samples) - 1)
    sample_width_round = int(sample_width + .5)
    
    prev_val = 0
    for i, item in enumerate(samples):
        val = max(0, height - 1 - int(item * scale + .5))
        if i > 0:
            left_edge = int(x + (i - 1) * sample_width + .5)
            if left_edge + sample_width_round >= width:
                sample_width_round = width - left_edge - 1

            # The right edge won't be drawn.
            ugfx.fill_polygon(int(x + (i - 1) * sample_width + .5), y, [
                                  (0, height - 1), (0, prev_val),
                                  (sample_width_round, val), (sample_width_round, height - 1)
                              ], colour)

        prev_val = val