/**
* File: pin.java
* Date: 98.06
* Location: Card
*/

import javacard.framework.*;
import javacardx.framework.*;

public class  pin implements ST, ISO {

  static final byte ACK_SIZE                = (byte)1;
  static final byte ACK_CODE                = (byte)0;

  static final byte MYAPPCLASS       	    =(byte)0x33;
  static final byte GETINS		    =(byte)0x55;
  static final byte SETINS                  =(byte)0x66;
  static final byte SETPININS	            =(byte)0x77;
  static final byte WRONG_PIN               =(byte)0xAA; //6B10


  public static void main (String args[]) {

    byte pbuffer[]=new byte[ISO.COMMAND_LENGTH];
    byte dbuffer[]=new byte[0x30];
    byte ackByte[]=new byte[ACK_SIZE];

    _OS.Execute((short)0, (byte)0);

    byte sw=(byte)0;

    _OS.GrantSupervisorMode();

    do {

      _OS.GetMessage(pbuffer, ISO.COMMAND_LENGTH, ACK_CODE);

      if (pbuffer[0] != MYAPPCLASS){
          sw= ST.INVALID_CLASS;
      }else if ((pbuffer[1]!=GETINS) && (pbuffer[1]!=SETINS) && (pbuffer[1]!=SETPININS)){
	  sw= ST.INS_NOT_SUPPORTED;
      }else if ((pbuffer[4]!=0) && (pbuffer[1]==GETINS)) {
          sw= ST.INVALID_PARAMETER;
      }else if ((pbuffer[4]!=0x30) && (pbuffer[1]==SETINS)){
	  sw= ST.INVALID_PARAMETER;
      }else {

	  _OS.SelectFile((short)0x3331);
	  _OS.ReadBinaryFile((short)0x0000, (byte)0x30, dbuffer);

	  if((pbuffer[2]==dbuffer[0]) && (pbuffer[3]==dbuffer[1])){
             if(pbuffer[1]==GETINS){
		
		ackByte[0]=pbuffer[1];
		_OS.SendMessage(ackByte, ACK_SIZE);
		_OS.SendMessage(dbuffer,(byte)0x30);

                sw=ST.SUCCESS;
	     }else {
		_OS.GetMessage(dbuffer, (byte)0x30, pbuffer[1]);
	
		//_OS.SelectFile((short)0x3331);
		_OS.WriteBinaryFile((short)0x0000, (byte)0x30, dbuffer);
		sw=ST.SUCCESS;
	     }
	  } else {
		sw=WRONG_PIN;
	  }     
	}
  
      _OS.SendStatus(sw);
    } while (true);
  }
}