{$ifndef unix}
{$A+,B-,D+,E+,F-,G+,I+,L+,N+,O+,P+,Q-,R-,S+,T-,V-,X+,Y+}
{$else}
{$B-,I+,S-,T-,X+}
{$endif}
unit hsiraw;

interface
uses
 tstring,
{$ifndef unix}
 vm256N,
{$else}
 xcrt,
{$endif}
 utils,
 evbios,
 vbios;

procedure hsiread(name:string);
procedure hsishow;
procedure hsiclose;

implementation
var
 oldmode:byte;
 Colors:integer;
 colormap:array[0..255,0..2] of byte;

{$ifndef unix}
{$else}
var
	screenlines:word;

procedure linen(ox,xx,oy:word;var b);
var
	i,o:word;
	p:abyte absolute b;
begin
 if screenlines=400 then Xplotline2_8(ox,xx,oy,@b)
 else Xplotline8(ox,xx,oy,@b);
end;

procedure copyscreenN(a,b:byte);
begin
{fixme}
end;
{$endif}

procedure hsiread(name:string);
var
 f:file;
 x,y:word;
 ImgOfs,
 LineSize:word;
 b:array[0..959] of byte;
 tc:array[0..319] of byte;
 w:array[0..15] of word absolute b;
 i,j,
 ox,oy,
 r:word;
begin
 if (videomode<=3) or (videomode=7) then oldmode:=videomode;
 assign(f,name);
{$i-}
 filemode:=0;
 if ioresult=0 then;
 reset(f,1);
 if ioresult<>0 then begin
{$ifndef unix}
   init_vm256N400;
{$else}
   Xinit(640,400);
   screenlines:=400;
{$endif}
 end else begin
  blockread(f,b,32,r);
//  if r<>32 then halt;
  x:=b[8]*256+b[9];
  y:=b[10]*256+b[11];
  colors:=b[12]*256+b[13];
  if colors=-24 then colors:=0;
  ImgOfs:=colors*3+32;
  linesize:=x;
  if x>320 then x:=320;
  ox:=160-(x+1) div 2;
  if y>200 then begin
{$ifndef unix}
   init_vm256N400;
{$else}
   Xinit(640,400);
   screenlines:=400;
{$endif}
   if y>=400 then oy:=0 else oy:=(400-y)*3 div 8;
  end else begin
{$ifndef unix}
   init_VM256N;
{$else}
   Xinit(320,200);
   screenlines:=200;
{$endif}
   oy:=(200-y)*3 div 8;
  end;
  if colors>0 then begin
   fillchar(colormap[255],3,$ff);
   blockread(f,colormap,colors*3,r);
   if r<>colors*3 then halt;
{$ifndef unix}
   for i:=0 to colors-1 do begin
   	colors[i,0]:=colors[i,0] shr 2;
   	colors[i,1]:=colors[i,1] shr 2;
   	colors[i,2]:=colors[i,2] shr 2;
   end;
   setcolorblock(0,256,colormap);
{$else}
   xsetcolorblock(0,256,colormap);
{$endif}
   j:=0;
   while (j<screenlines)and(j<y) do begin
    seek(f,imgofs+j*longint(linesize));
    blockread(f,b,x,r);
    if r<>x then halt;
    linen(ox,x,oy+j,b);
{    for i:=0 to (x-1) do plotN(ox+i,oy+j,b[i]);}
    inc(j);
   end;
  end else begin
   linesize:=linesize*3;
   j:=0;
   while (j<screenlines)and(j<y) do begin
    seek(f,imgofs+j*longint(linesize));
    blockread(f,b,x*3,r);
    if r<>x*3 then halt;
    for i:=0 to (x-1)
    do tc[i]:=b[i*3  ] and $e0
	  or (b[i*3+1] and $e0) shr 3
	  or  b[i*3+2]          shr 6;
    linen(ox,x,oy+j,tc);
    inc(j);
   end;
  end;
 end;
 copyscreenN(0,1);
 if ioresult<>0 then;
 close(f);
 {$i+}
end;

procedure hsishow;
begin
 copyscreenN(1,0);
end;

procedure hsiclose;
begin
 setvideomode(oldmode);
end;

begin
 oldmode:=3;
end.