
function le(x){x|=0
var s=''
var i
for(i=0;i<4;++i){s+=String.fromCharCode(x&255)
x>>=8}
return s}
function le2(x){return le(x).substr(0,2)}
bmp={ps:function(w,h,b){if(b==24){return 0}return 3*(1<<b)},ds:function(w,h,b){return h*4*Math.ceil(w*b/32)},offset:function(w,h,b){return 26+this.ps(w,h,b)},fs:function(w,h,b){return this.offset(w,h,b)+this.ds(w,h,b)},make:function(w,h,b){var pal='',n=this.ps(w,h,b),data=''
while(pal.length<n){pal+='pal'}
pal=pal.substr(0,n)
n=this.ds(w,h,b)
while(data.length<n){data+=le(0)}
return'BM'+le(this.fs(w,h,b))+le(0)+le(this.offset(w,h,b))+
le(12)+le2(w)+le2(h)+le2(1)+le2(b)+
pal+data}}
function Bmp(w,h,b){this.w=w
this.h=h
this.b=b
this.binary=bmp.make(w,h,b)}
Bmp.prototype={asURL:function(){return'data:image/bmp;base64,'+btoa(this.binary)},poffset:function(){return 26},pn:function(){bmp.ps(this.w,this.h,this.b)/3},sll:function(){return 4*Math.ceil(this.w*this.b/32)},dataoffset:function(){return bmp.offset(this.w,this.h,this.b)},setPalette:function(i,r,g,b){var j,s
if(i>=this.pn()){throw'setPalette: index out of range'}
i=i*3+this.poffset()
s=''
for(j=0;j<3;++j){s+=String.fromCharCode(arguments[3-j])}
this.binary=this.binary.substr(0,i)+s+
this.binary.substr(i+s.length)
return this},copyPaletteFrom:function(src){if(this.b!=src.b){throw'Palette: incompatible sizes.'}
var pal=src.binary.substr(src.poffset(),bmp.ps(this.w,this.h,this.b))
var po=this.poffset()
this.binary=this.binary.substr(0,po)+pal+
this.binary.substr(po+pal.length)
return this},wherePixel:function(x,y){x|=0
y|=0
if(x<0||x>this.w){throw'Pixel: x out of range'}
if(y<0||y>this.h){throw'Pixel: y out of range'}
var xb=x*this.b
var xo=Math.floor(xb/8)
xb-=8*xo
xb^=7
var i=this.dataoffset()+y*this.sll()+xo
return[i,xb]},getPixel:function(x,y){var ob=this.wherePixel(x,y)
var o=ob[0],b=ob[1]
var p=0
if(this.b<8){p=this.binary.charCodeAt(o)
p>>=b
p&=(1<<this.b)-1}else{var i
for(i=0;i<this.b/8;++i){p|=(this.binary.charCodeAt(o+i)<<(8*i))}}
return p},setPixel:function(x,y,n){n|=0
if(n>=(1<<this.b)){throw'setPixel: n out of range'}
var ob=this.wherePixel(x,y)
var i=ob[0]
var xb=ob[1]
var t=this.binary.charCodeAt(i)
if(this.b<8){var m=(1<<this.b)-1
t&=~(m<<xb)
t|=n<<xb
t=String.fromCharCode(t)}else{t=''
var j
for(j=0;j<this.b/8;++j){t+=String.fromCharCode(n&255)
n>>=8}}
this.binary=this.binary.substr(0,i)+t+
this.binary.substr(i+t.length)
return this}}
function hex2(x){x='0'+x.toString(16)
return x.substr(x.length-2)}

