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

typedef struct tagBITMAPFILEHEADER {
    unsigned int        bfType;         // 2 must be "BM"
    unsigned long       bfSize;         // 4 ファイルサイズ(バイト)
    unsigned int        bfReserved1;    // 2 リザーブ
    unsigned int        bfReserved2;    // 2 リザーブ
    unsigned long       bfOffBits;      // 4 イメージまでのオフセット
} BITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER {
    unsigned long       biSize;         // 4 当構造体のサイズ(バイト)
    long                biWidth;        // 4 イメージの幅           [*1]
    long                biHeight;       // 4 イメージの高さ         [*1]
    unsigned int        biPlanes;       // 2 must be 1
    unsigned int        biBitCount;     // 2 色数                   [*2]
    unsigned long       biCompression;  // 4 圧縮タイプ             [*3]
    unsigned long       biSizeImage;    // 4 イメージのサイズ       [*3]
    long                biXPixPerMeter; // 4 水平解像度             [*4]
    long                biYPixPerMeter; // 4 垂直解像度             [*4]
    unsigned long       biClrUsed;      // 4 →カラーテーブルを参照
    unsigned long       biClrImporant;  // 4 →カラーテーブルを参照
} BITMAPINFOHEADER;

void DisplayHelp( void );

char Header[54];
unsigned char Color[4*256];
char SrcPath[129];
char DstPath[129];

int main( int argc, char *argv[] )
{
	FILE *SrcFp;
	FILE *DstFp;
	int i;
	/* ----------------------------------------	ヘルプ表示 */
	if ( argc < 2 ) DisplayHelp();
	if ( strcmp( argv[1],"/?") == 0 ) DisplayHelp();
	if ( strcmp( argv[1],"-?") == 0 ) DisplayHelp();
	/* 変換 */
	strcpy( SrcPath, argv[1] );
	strcat( SrcPath, ".BMP" );
	strcpy( DstPath, argv[1] );
	strcat( DstPath, ".ASM" );
	if ( ( SrcFp = fopen( SrcPath, "rb" ) ) != NULL ) {
		fread( Header, 1, 54, SrcFp );
		if ( ( Header[0] == 'B' ) && ( Header[1] == 'M' ) ) {
			int nBitCount;
			nBitCount = Header[28] + Header[29] * 256;
			if ( ( nBitCount == 4 ) || ( nBitCount == 8 ) ) {
				int nColor;
				int nCount;
				if ( nBitCount == 4 ) {
					nColor = 16;
				} else {
					nColor = 256;
				}
				fread( Color, 4, nColor, SrcFp );
				fclose( SrcFp );
				if ( ( DstFp = fopen( DstPath, "w" ) ) != NULL ) {
					nCount = 0;
					fprintf( DstFp, "; %s.BMP Palette data.\n", argv[1] );
					fprintf( DstFp, "\tDW\t" );
					for( i=0; i<nColor; i++ ) {
						int nRgb;
						nRgb = Color[ i * 4 ] / 16 + Color[ i * 4 + 1 ] / 16 * 16 + Color[ i * 4 + 2 ] / 16 * 256;
						if ( nCount == 7 ) {
							fprintf( DstFp, "%04Xh", nRgb );
						} else {
							fprintf( DstFp, "%04Xh, ", nRgb );
						}
						nCount++;
						if ( nCount > 7 ) {
							fprintf( DstFp, "\n" );
							if ( i != nColor - 1 ) {
								fprintf( DstFp, "\tDW\t" );
							}
							nCount = 0;
						}
					}
					fclose( DstFp );
				} else {
					printf( "ファイルを書き込むことができません.\n" );
				}
			} else {
				printf( "BMP ファイルは 16 色、256 色のものを指定してください.\n" );
			}
		} else {
			printf( "BMP ファイルではありません.\n" );
		}
	}
}

void DisplayHelp( void )
{
	printf( "USAGE:\n" );
	printf( "GETPAL [BMP file] [Enter]\n" );
}
