package org.cryptonit;

import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;


public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }

    public void sendBuffer(byte[] buf, short length, APDU apdu) {
        short le = apdu.setOutgoing();

        if(le == 0) {
            le = (short) (APDU.getOutBlockSize() - 2);
        }

        if(le > length) {
            le = length;
        }

        if(le < length) {
            short l = (short) (length - le);
            if(l > (short) this.buffer.length) {
                ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
            }
            Util.arrayCopy(buf, (short) le, this.buffer, (short) 0, l);
            this.bools[isLOADED] = true;
            this.bools[isFILE] = false;
        }

        apdu.setOutgoingLength(le);
        apdu.sendBytesLong(buf, (short) 0, le);
    }
}

@@ -1012,18 +1012,25 @@
 tgoing()
+, r = 0
 ;%0A
-
 %0A       
@@ -1210,23 +1210,17 @@
         
-short l
+r
  = (shor
@@ -1252,17 +1252,17 @@
      if(
-l
+r
  %3E (shor
@@ -1367,80 +1367,8 @@
   %7D%0A
-            Util.arrayCopy(buf, (short) le, this.buffer, (short) 0, l);%0A
     
@@ -1487,24 +1487,24 @@
 Length(le);%0A
-
         apdu
@@ -1534,21 +1534,116 @@
 ort) 0, le);
+%0A%0A        if(r %3E 0) %7B%0A            Util.arrayCopy(buf, le, this.buffer, (short) 0, r);%0A        %7D
 %0A    %7D%0A%7D%0A

Rename variable containing size of remaining data, change its scope and move copy towards the end