uses screen, memory, crt, dos;

const
VGA=$a000;

procedure setonecolor(c,r,g,b:byte);assembler;
asm
  mov dx,3c8h
  mov al,c
  out dx,al
  inc dx
  mov al,r
  out dx,al
  mov al,g
  out dx,al
  mov al,b
  out dx,al
end;

procedure readonecolor(c:byte;var r,g,b:byte);assembler;
asm
  mov dx,3c7h
  mov al,c
  out dx,al
  add dx,2
  in  al,dx
  les di,r
  mov [es:di],al
  in  al,dx
  les di,g
  mov [es:di],al
  in  al,dx
  les di,b
  mov [es:di],al
end;


var palitra, palitra2:array[0..767] of byte;

Procedure LoadTga(TgaName : String; size:longint; where:word);
Var
  InF   : File of byte; Loop : Word;
  Dummy : Array[1..18] of Byte;
  Pal   : Array[1..768] of Byte;
  n,l:longint;
  tmp,r,g,b:byte;
Begin
  Assign(Inf,TgaName);
  Reset(Inf);
  for n:=0 to 17 do read(inf,tmp);
  for n:=1 to 768 do read(inf,pal[n]);
  l:=0;
  for n:=1 to size do begin
      read(inf, mem[where:l]);
      inc(l);
  end;
  Close(Inf);
{  Port[$3C8]:=0;}
  Loop:=1;
  n:=0;
  While Loop<768 Do
    Begin
      r:=Pal[Loop+2] Div 4;
      g:=Pal[Loop+1] Div 4;
      b:=Pal[Loop] Div 4;
      palitra[n]:=r;
      palitra[n+1]:=g;
      palitra[n+2]:=b;

      Port[$3C9]:=r;
      Port[$3C9]:=g;
      Port[$3C9]:=b;
      n:=n+3;
      Inc(Loop,3);
    End;
End;

procedure save_palitra(name:string);
var fw1:file;
i:word;
z:byte;
begin
Assign(fw1, name);
Rewrite(fw1,1);
Reset(fw1, 1);
z:=0;
for i:=0 to 767 do begin
   BlockWrite(fw1, z, 1);
   BlockWrite(fw1, palitra[i], 1);
end;
Close(fw1);
end;

procedure save_bitmap(name:string; size:longint);
var fw1:file;
i,n:longint;
begin
Assign(fw1, name);
Rewrite(fw1,1);
Reset(fw1, 1);
n:=0;
for i:=1 to size do begin
   BlockWrite(fw1, mem[vaddr:n], 1);
   inc(n);
end;
Close(fw1);
end;


var
fw1,fw2:file;

c, i, x,y,n,m,yy,xx:word;
fr:file;
col, r,g,b:byte;
size:word;

begin
SetUpVirtual(scr,vaddr);
SetUpVirtual(scr2, vaddr2);
SetUpVirtual(scr3, vaddr3);

asm
mov ax, 13h
int 10h
end;

LoadTga('manwe3.tga', 320*200, vaddr);

{poloski}
for y:=0 to 199 do for x:=0 to 319 do begin
    if mem[vaddr:x+y*320]=64 then mem[vaddr:x+y*320]:= y and 15+65;
    if mem[vaddr:x+y*320]=255 then mem[vaddr:x+y*320]:=y and 15+65 +16;
end;

for n:=0 to 15 do begin
palitra[(65+n)*3]:=palitra[255*3];
palitra[(65+n)*3+1]:=palitra[255*3+1];
palitra[(65+n)*3+2]:=palitra[255*3+2];

palitra[(65+n+16)*3]:=palitra[255*3];
palitra[(65+n+16)*3+1]:=palitra[255*3+1];
palitra[(65+n+16)*3+2]:=palitra[255*3+2];
end;

for y:=0 to 199 do for x:=0 to 319 do mem[vga:x+y*320]:=mem[vaddr:x+y*320];

save_palitra('manwe3.pal');
save_bitmap('manwe3.bin', 64000);


readkey;

asm
mov ax, 3h
int 10h
end;

end.