uses crt, dos;

const
VGA=$a000;

TYPE
  Virtualscreen = Array[1..65535] of byte;
  Virscr = ^VirtualScreen;

var
 scr, scr2, scr3: virscr;
 vaddr, vaddr2, vaddr3 : word;

  Aantal, T1: longint;
  Timer                : Longint ABSOLUTE $0040:$006C;


Procedure FlipScreen(source, dest : word);
Assembler; {386 only}
asm
  mov     dx, ds
  mov     ax, [dest]
  mov     es, ax
  mov     ax, [source]
  mov     ds, ax
  xor     si, si
  xor     di, di
  mov     cx, 16000
  db      $66
  rep     movsw
  mov     ds,dx    {mov's are faster than push / pops }
end;


PROCEDURE Clear(size,where:word);assembler;
     ASM
        mov ax,where
        mov es,ax
        mov cx, size
        shr cx, 2
        db $66
        xor ax,ax
        xor di,di
        cld
        db $66
        rep stosw
END;

procedure Fblur(where:word); assembler;
 asm
  mov es, where
  mov di, 0
  mov cx, 65535
  @here:
    xor dx, dx
    xor ax, ax
    mov dl, es:[di+1]
    mov al, es:[di-1]
    add dx, ax
    mov al, es:[di+320]
    add dx, ax
    mov al, es:[di-320]
    add dx, ax

    shr dx, 2
    mov es:[di], dl
    add di, 1
    dec cx
  jnz @here
 end;


PROCEDURE SetUpVirtual(VAR screenname:virscr;VAR add : word);
BEGIN
  GetMem (Screenname,65535);
  add := seg (Screenname^);
  clear(65535,add);
END;


Procedure WaitVR; Assembler;
ASM
  mov  dx, 3DAh
@w1:
    in   al, dx
    test al, 8h
  jnz  @w1
@w2:
    in   al, dx
    test al, 8h
  jz   @w2
End;


var
TunTex            : Pointer;
TunTexSeg         : Word;

Procedure LoadTga(TgaName : String);
Var
  InF   : File; Loop : Word;
  Dummy : Array[1..18] of Byte;
  Pal   : Array[1..768] of Byte;

Begin
  Assign(Inf,TgaName);
  Reset(Inf,1);
  BlockRead(Inf,Dummy,18);
  BlockRead(Inf,Pal,768);
  BlockRead(Inf,TunTex^,64000);
  Close(Inf);
  Port[$3C8]:=0;
  Loop:=1;
  While Loop<768 Do
    Begin
      Port[$3C9]:=Pal[Loop+2] Div 4;
      Port[$3C9]:=Pal[Loop+1] Div 4;
      Port[$3C9]:=Pal[Loop] Div 4;
      Inc(Loop,3);
    End;

End;


var
fw1,fw2:file;

c, x,y,n,m:word;
col :byte;
temp:word;

fr:file;
b:byte;
size:word;

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

asm
mov ax, 13h
int 10h
end;


GetMem(TunTex,65535); TunTexSeg:=Seg(TunTex^);
LoadTga('plas_op.tga');
for n:=0 to 63999 do mem[vga:n]:=mem[TunTexSeg:n];


Assign(fw1, 'plas_op.bin');
Rewrite(fw1,1);
Reset(fw1, 1);

for y:=0 to 9 do for x:=0 to 15 do
begin

col:=mem[tuntexseg:(x*20+10)+(y*20+10)*320];
mem[vga:(x*20+10)+(y*20+10)*320]:=0;

BlockWrite(fw1, col, 1);

end;

Close(fw1);


readkey;

Aantal:=0; T1:=Timer;


repeat
{Clear(64000, vaddr);}

n:=n+1;




WaitVR;{}
{FlipScreen(vaddr,vga);{}
Inc(Aantal);
until port[$60]=1;

asm
mov ax, 3h
int 10h
end;
T1:=timer-T1;
WriteLn(Aantal/(T1/18.2):2:1,' Frames per second');
readkey;
repeat until keypressed;

end.