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, where:word);
Var
  InF   : File of byte; Loop : Word;
  Dummy : Array[1..18] of Byte;
  Pal   : Array[1..768] of Byte;
  n:word;
  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]);
  for n:=0 to size do read(inf, mem[where:n]);
  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, palitra2[i], 1);
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('test2_p2.tga', 320*200, vaddr);

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

for x:=0 to 255 do begin
mem[vga:x+320*190]:=x;
mem[vga:x+320*191]:=x;
end;

{первая палитра (результат чередуем через один)}
for x:=0 to 127 do begin
   xx:=x;
   yy:=30;
   col:=mem[vaddr:xx+yy*320];
   readonecolor(col, r,g,b);
   palitra2[(x*6  )+3 ]:=r;
   palitra2[(x*6+1)+3 ]:=g;
   palitra2[(x*6+2)+3 ]:=b;
   mem[vga: xx + yy*320]:=0;
end;

{вторая палитра}
for x:=0 to 127 do begin
   xx:=x;
   yy:=130;
   col:=mem[vaddr:xx+yy*320];
   readonecolor(col, r,g,b);
   palitra2[(x*6  )+0 ]:=r;
   palitra2[(x*6+1)+0 ]:=g;
   palitra2[(x*6+2)+0 ]:=b;
   mem[vga: xx + yy*320]:=0;
end;

readkey;

{тестируем получившуюся палитру}
Port[$3C8]:=0;
for x:=0 to 767 do
   begin
      Port[$3C9]:=palitra2[x];
   end;


save_palitra('test2_p2.pal');



readkey;

asm
mov ax, 3h
int 10h
end;

end.