# Convert .bmp file to BMPv4 (imagemagick doesn't like BMPv3 w/ regards to alpha channel)

import glob
import struct
import sys

def make_v4_hdr(hdr):
	hdr = hdr + bytes(0x44)
	hdr = bytearray(hdr)
	file_size, = struct.unpack('<I', hdr[0x02:0x06])
	offset, = struct.unpack('<I', hdr[0x0A:0x0E])
	hdr_size, = struct.unpack('<I', hdr[0x0E:0x12])
	file_size += 0x44
	offset += 0x44
	hdr_size += 0x44
	hdr[0x02:0x06] = struct.pack('<I', file_size)
	hdr[0x0A:0x0E] = struct.pack('<I', offset)
	hdr[0x0E:0x12] = struct.pack('<I', hdr_size)
	hdr[0x1E] = 0x03
	hdr[0x38] = 0xFF
	hdr[0x3B] = 0xFF
	hdr[0x3E] = 0xFF
	hdr[0x45] = 0xFF
	hdr[0x46] = 0x01
	hdr[0x52] = 0x01
	hdr[0x5E] = 0x01
	hdr[0x6A] = 0x01
	hdr = bytes(hdr) 
	return hdr

def convert(bmp_file):
	data = open(bmp_file, 'rb').read()
	magic = data[:0x2]
	offset, = struct.unpack('<I', data[0xA:0xE])
	if magic == b'BM' and offset == 0x36:
		hdr = data[:offset]
		image = data[offset:]
		data = make_v4_hdr(hdr) + image
		open(bmp_file, 'wb').write(data)

if __name__ == '__main__':
	if len(sys.argv) < 2:
		print('Usage: bmp2v4.pt <bmp_file(s)>')
		sys.exit(1)
	for arg in sys.argv[1:]:
		for file in glob.glob(arg):
			convert(file)
