--[[
bmplib
version 1
by sam

functions:
Image.bmpload(filename) - loads and returns an 24 bit bitmap image
]]--

function b(byte_number, byte_length)
if byte_length == 1 then
	return string.byte(string.sub(filestring, byte_number, byte_number))
elseif byte_length == 2 then
	byte1 = string.byte(string.sub(filestring, byte_number, byte_number))
	byte2 = string.byte(string.sub(filestring, byte_number + 1, byte_number + 1))
	return dec_to_dec2(byte1,byte2)

elseif byte_length == 4 then
	byte1 = string.byte(string.sub(filestring, byte_number, byte_number))
	byte2 = string.byte(string.sub(filestring, byte_number + 1, byte_number + 1))
	byte3 = string.byte(string.sub(filestring, byte_number + 2, byte_number + 2))
	byte4 = string.byte(string.sub(filestring, byte_number + 3, byte_number + 3))
	return dec_to_dec4(byte1,byte2,byte3,byte4)
end
end
function dec_to_dec2(hexvalue1, hexvalue2)
first_byte = hexvalue1
second_byte = hexvalue2
sample = (second_byte * 256) + first_byte
if sample > 32767  then
  sample = 0 - (65536 - sample)
end
return sample
end
function dec_to_dec4(hexvalue1, hexvalue2, hexvalue3,hexvalue4)
sample = (hexvalue4 * 16777216) + (hexvalue3 * 65536) + (hexvalue2 * 256) + hexvalue1
return sample
end

function Image.bmpload(Bmp_filename)
file = io.open(Bmp_filename, "rb")
if file then
filestring = file:read("*all")
file:close()
else
error("BMPLIB: NO SUCH FILE",2)
end
if b(29,2) ~= 24 then error("BMPLIB: "..b(29,2) .. " BIT (MUST BE 24 BIT)",2) end
width = b(19,4) * 4
real_width = b(19,4)
height = b(23,4)
row_length = width - math.floor(b(19,4)*.25)*4
pixel_length = b(19,4) * 3
image = Image.createEmpty(real_width,height)
image_r = {}
image_g = {}
image_b = {}
for columns=55,55+(row_length*height)-row_length,row_length do
for a=columns,columns+pixel_length-1,3 do
table.insert(image_r,b(a+2,1))
table.insert(image_g,b(a+1,1))
table.insert(image_b,b(a,1))
end
end
num_x = 0
num_y = 0
for b=height,1,-1 do
for a=1,real_width do
num = (real_width*b)-real_width+a
image:drawLine(num_x,num_y,num_x,num_y,Color.new(image_r[num],image_g[num],image_b[num]))
num_x = num_x + 1
end
num_y = num_y + 1
num_x = 0
end
return image
end