/*
 *  (C) 2005 Alan Donovan.
 *
 *  Author: Alan Donovan <adonovan@csail.mit.edu>
 *
 *  bmp2bit.c -- Convert 16-bit 5:6:5 True Color BMP files to
 *               LG-VX3200 cellphone wallpaper image format.
 *
 *  $Id$
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of version 2 of the GNU General Public
 *  License as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU General Public License for more details.
 *  <http://www.gnu.org/copyleft/gpl.html>.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define BMP_HEADER_SIZE 54

int main(int argc, char **argv)
{
    const char *infile;
    const char *outfile;
    FILE *in, *out;
    unsigned offset;
    unsigned width;
    unsigned height;
    unsigned bpp;
    unsigned char data[BMP_HEADER_SIZE];

    if(argc != 3) {
	fprintf(stderr, "usage: %s <in.bmp> <out.bit>\n", argv[0]);
	exit(1);
    }

    infile = argv[1];
    outfile = argv[2];

    if((in = fopen(infile, "rb")) == NULL) {
	fprintf(stderr, "fopen(%s) failed: %s.\n", infile, strerror(errno));
	exit(1);
    }

    if(fread(data, 1, BMP_HEADER_SIZE, in) < BMP_HEADER_SIZE ||
       data[0] != 'B' || data[1] != 'M') {
	fprintf(stderr, "%s: doesn't appear to be a BMP file.\n", infile);
	exit(1);
    }

    offset = data[10] | (data[11]<<8) | (data[12]<<16) | (data[13]<<24);
    width  = data[18] | (data[19]<<8) | (data[20]<<16) | (data[21]<<24);
    height = data[22] | (data[23]<<8) | (data[24]<<16) | (data[25]<<24);
    bpp    = data[28] | (data[29]<<8);

    if(bpp != 16) {
	fprintf(stderr,
		"BMP %s is %d bpp (must be 16-bit RGB 5:6:5 mode).\n",
		infile, bpp);
	exit(1);
    }

    fseek(in, offset, SEEK_SET);

    if((out = fopen(outfile, "wb")) == NULL) {
	fprintf(stderr, "fopen(%s) failed: %s.\n", outfile, strerror(errno));
	exit(1);
    }

    fprintf(out, "%c%c%c%c",
	    width & 0xff, width>>8,
	    height & 0xff, height>>8);

    for(;;) {
	int c = fgetc(in);
	if(c == EOF)
	    break;
	fputc(c, out);
    }

    fclose(in);
    fclose(out);

    fprintf(stderr, "Created %s (%d x %d pixels).\n", outfile, width, height);

    return 0;
}
