#by Shrim
class mbmfile:
 def __init__(s):
  import os,graphics,struct
  s.O,s.G,s.unpack,s.pack=os,graphics.Image,struct.unpack,struct.pack
 def image(s,path,index):
  if not s.O.path.exists(path):raise IOError('file not exists')
  file=open(path)
  if file.read(16)!='\x37\x00\x00\x10\x42\x00\x00\x10\x00\x00\x00\x00\x39\x64\x39\x47':
   file.close()
   raise IOError('file not mbm')
  file.seek(s.unpack('i',file.read(4))[0])
  k=s.unpack('i',file.read(4))[0]
  if index>=k:
   file.close()
   raise IndexError('list index out of range')
  file.seek(index*4,1)
  position=s.unpack('i',file.read(4))[0]
  file.seek(position)
  dlina=s.unpack('i',file.read(4))[0]
  file.seek(4,1)
  x,y=s.unpack('ii',file.read(8))
  file.seek(8,1)
  bit=s.unpack('i',file.read(4))[0]
  if bit>23:bit='RGB'
  elif bit>14:bit='RGB16'
  elif bit>11:bit='RGB12'
  elif bit>7:bit='L'
  else:bit='1'
  file.seek(position)
  tempfile=open(path+'.temp.mbm','w')
  tempfile.write('\x37\x00\x00\x10\x42\x00\x00\x10\x00\x00\x00\x00\x39\x64\x39\x47'+s.pack('i',dlina+20)+file.read(dlina)+'\x01\x00\x00\x00\x14\x00\x00\x00')
  file.close(),tempfile.close()
  img=s.G.new((x,y),bit)
  try:img.load(path+'.temp.mbm')
  except:
   s.O.remove(path+'.temp.mbm')
   raise IOError('image not load')
  s.O.remove(path+'.temp.mbm')
  return img
image=mbmfile().image
del mbmfile
