#include <stdint.h>
#include "monoimg.h"

#define max(a,b) ((a) >= (b) ? (a) : (b))
#define min(a,b) ((a) <= (b) ? (a) : (b))

uint8_t mimg_get_pixel_unsafe(const uint8_t *img, uint8_t x, uint8_t y) {
    // MVLSB format
    uint8_t width = img[0] + 1;
    uint16_t index = (y >> 3) * width + x + 2;
    uint8_t offset = y & 0x07;
    uint8_t value = (img[index] >> offset) & 0x01;
    return value; // return 1 or 0
}

uint8_t mimg_get_pixel(const uint8_t *img, uint16_t x, uint16_t y) {
    // MVLSB format
    uint8_t width = img[0] + 1;
    uint8_t height = img[1] + 1;
    if (x >= width || y >= height) {
        return 0;
    }
    return mimg_get_pixel_unsafe(img, (uint8_t)x, (uint8_t)y);
}

void mimg_draw(mimg_FunctionSetPixel set_pixel, uint16_t x, uint16_t y, uint16_t color, const uint8_t *img, mimg_Area area) {
    uint8_t width_s1 = img[0]; // width - 1
    uint8_t height_s1 = img[1]; // height - 1
    uint8_t ix = min(area.x, width_s1);
    uint8_t iy = min(area.y, height_s1);
    uint8_t iw = min(area.w, width_s1 - ix + 1);
    uint8_t ih = min(area.h, height_s1 - iy + 1);
    uint8_t off_x, off_y;
    for (off_y = 0; off_y < ih; off_y ++) {
        for (off_x = 0; off_x < iw; off_x ++) {
            if (mimg_get_pixel_unsafe(img, ix + off_x, iy + off_y)) {
                set_pixel(x + off_x, y + off_y, color);
            }
        }
    }
}

mimg_Area mimg_get_tile_area(const uint8_t *img, uint8_t cols, uint8_t rows, uint8_t index) {
    uint8_t width = img[0] + 1;
    uint8_t height = img[1] + 1;
    mimg_Area area;
    area.w = width / cols;
    area.h = height / rows;
    area.y = (index / cols) * area.h;
    area.x = (index % cols) * area.w;
    return area;
}
