%option "-low-nonstandard-nocheck-nodiag-nostack-noline"

%include "MOOSE:MOUSE.INC"

%systemroutinespec phex(%integer i)

!%externalroutinespec start terminal

%externalintegerfnspec disc size(%integername s)
%externalintegerfnspec disc read(%integer block, %bytename buffer)
%externalintegerfnspec disc write(%integer block, %bytename buffer)

%begin
   %integer i, next block = 0, last block = -1, size, write status
   %bytearray buffer(0 : 511)
!     start terminal
      {} put string("Disc tester starting");  put sym(NL)
      open output(0, ":");  select output(0)
      {} put string("Get disc size");  put sym(NL)
      i = disc size(size)
      {} put string("Got ");  put long(i);  put sym(NL)
      %if i = 0 %start
         printstring("Size is ");  write(size, 0)
         newline
      %else
         printstring("Error: ");  phex(i)
         newline
         %stop
      %finish
      !! %stop;  !<<<<<<<<<<<<<<
      ! Then loop writing and reading back
      %cycle
         next block = rem((234 * next block + 456789) & 16_7FFFFFFF, size)
         buffer(i) = (next block + i) & 255 %for i = 0, 1, 511
         write status = disc write(next block, buffer(0))
         %if write status # 0 %start
            printstring("Write block ");  write(next block, 0)
            printstring(" status ");  phex(write status);  newline
         %finish
         %if last block >= 0 %start
            i = disc read(last block, buffer(0))
            %if i = 0 %start
               %for i = 0, 1, 511 %cycle
                  %if buffer(i) # (last block + i) & 255 %start
                     printstring("Mismatch: block ");  write(last block, 0)
                     printstring(" byte ");  write(i, 0)
                     printstring(" expecting ")
                     write((last block + i) & 255, 0)
                     printstring(" got ");  write(buffer(i), 0)
                     newline
                     %exit
                  %finish
               %repeat
            %else
               printstring("Read block ");  write(last block, 0)
               printstring(" status ");  phex(i);  newline
            %finish
         %finish
         %if write status = 0 %then last block = next block %c
                              %else last block = -1
      %repeat
%end %of %program      
