#include "bmp_image.h"
#include <sys/stat.h>
#include <stdio.h>
#include <memory.h>

void usage(const char *prog)
{
	fprintf(stderr, "Usage: %s out_image [ bmp_files ]\n", prog);
}

/*
 * Neutralize little endians.
 */
uint32_t le_uint32(uint32_t x)
{
    uint32_t val;
    uint8_t *p = (uint8_t *)(&x);

    val =  (*p++ & 0xff) << 0;
    val |= (*p++ & 0xff) << 8;
    val |= (*p++ & 0xff) << 16;
    val |= (*p   & 0xff) << 24;

    return val;
}

#define EXIT_FAILURE -1

int main (int argc, char *argv[])
{
    FILE *out, *fp;
    int offset = 0;
    int size = 0;
    int level = 0;
#define LEVEL_OPT "-level="

    char buf[RK_BLK_SIZE];
    int i = 0, j = 0;
    bmp_image_header_t header;
    header.tag = le_uint32(BMP_IMAGE_TAG);

    if (argc < 2) {
		usage(argv[0]);
        return -1;
	}

	out = fopen(argv[1], "wb+");
	if (!out) {
		perror(argv[1]);
        return -1;
	}

    printf("/*\n"
    " * Automatically generated by \"tools/bmp_image\"\n"
    " *\n"
    " * DO NOT EDIT\n"
    " *\n"
    " */\n\n\n"
    "#ifndef __BMP_IMAGE_DATA_H__\n"
    "#define __BMP_IMAGE_DATA_H__\n\n"
    "#include <bmp_image.h>\n\n"
    "bmp_image_t bmp_images[] = \n{\n");


    argc -= 2;
    argv += 2;
    for (i = 0;i < argc;i++) {
        if (!memcmp(LEVEL_OPT, argv[i], strlen(LEVEL_OPT))) {
            level = atoi(argv[i] + strlen(LEVEL_OPT));
            continue;
        }
        fp = fopen(argv[i], "rb+");
        struct stat sb;
        int ret = stat(argv[i], &sb);
        if (!fp || ret) {
            perror(argv[i]);
            return -1;
        }
        //fseek(out, offset * RK_BLK_SIZE, SEEK_SET);

        size = sb.st_size / RK_BLK_SIZE + 2;

        memset(buf, 0, sizeof(buf));                                                                                               

        memcpy(buf, &header, sizeof(header));
        fwrite(buf, sizeof(buf), 1, out);

        for (j = 0;j < size - 1;j++) {
            memset(buf, 0, sizeof(buf));
            fread(buf, 1, sizeof(buf), fp);
            fwrite(buf, sizeof(buf), 1, out);
        }
        fclose(fp);

        //output index map:   index  offset size
        printf("    {\n"
        "        .offset = %d, //%s\n"
        "        .size   = %d,\n"
        "        .level  = %d,\n"
        "        .loaded = 0,\n"
        "    },\n", offset, argv[i], size, level);

        offset += size;
        fflush(out);
    }
    printf("};\n\n\n#endif //BMP_IMAGE_DATA_H__\n");

    fclose (out);
    return 0;
}
