 			byte encoderId = rowid * 8 + colid / 2;
 			//int encoderState = encoderTable[ prevEncoderValue[ encoderId ] << 2 | encoderValue ];
 
+			int direction = 0;
 			if ( encoderValue != prevEncoderValue[encoderId]  )
 			{
 				//we have a "pulse" from rotary encoder
-				int direction = 0;
-				EncoderState[encoderId] = EncoderState[encoderId] << 2 | encoderValue;
-
-				if (EncoderState[encoderId] == CWPattern1  || EncoderState[encoderId] == CWPattern3 )
+				EncoderState[encoderId] = (EncoderState[encoderId] << 2) | encoderValue;
+
+				if ((EncoderState[encoderId] & CWCCWCompareMask) == CWPattern1  
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CWPattern3 
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CWPattern2  
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CWPattern4)
 				{
 					//this is a full CW pattern,
 					direction = 1;
 					//EncoderState[encoderId] = 0;
 				}
-				else if (EncoderState[encoderId] == CCWPattern1  || EncoderState[encoderId] == CCWPattern3 )
+				else if ((EncoderState[encoderId] & CWCCWCompareMask)== CCWPattern1  
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CCWPattern3 
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CCWPattern2  
+					|| (EncoderState[encoderId] & CWCCWCompareMask) == CCWPattern4)
 				{
 					//this is a full CCW pattern,
 					direction = -1;

		PORTA = ~( B00000001 << rowid);

		//we must have such a delay so the digital pin output can go LOW steadily, 
		//without this delay, the row PIN will not 100% at LOW during yet,
		//so check the first column pin's value will return incorrect result.
		delayMicroseconds(3);

		byte colResult[16];

			//pin 38, PD7
			colResult[0] = (PIND & B10000000 )== 0 ? 1 : 0;
			//pin 39, PG2
			colResult[1] = (PING & B00000100 )== 0 ? 1 : 0;
			//pin 40, PG1
			colResult[2] = (PING & B00000010 )== 0 ? 1 : 0;
			//pin 41, PG0
			colResult[3] = (PING & B00000001 )== 0 ? 1 : 0;

			//pin 42, PL7
			colResult[4] = (PINL & B10000000 )== 0 ? 1 : 0;
			//pin 43, PL6
			colResult[5] = (PINL & B01000000 )== 0 ? 1 : 0;
			//pin 44, PL5
			colResult[6] = (PINL & B00100000 )== 0 ? 1 : 0;
			//pin 45, PL4
			colResult[7] = (PINL & B00010000 )== 0 ? 1 : 0;

			//pin 46, PL3
			colResult[8] = (PINL & B00001000 )== 0 ? 1 : 0;
			//pin 47, PL2
			colResult[9] = (PINL & B00000100 )== 0 ? 1 : 0;
			//pin 48, PL1
			colResult[10] =( PINL & B00000010)== 0 ? 1 : 0;
			//pin 49, PL0
			colResult[11] =( PINL & B00000001)== 0 ? 1 : 0;

			//pin 50, PB3
			colResult[12] =( PINB & B00001000)== 0 ? 1 : 0;
			//pin 51, PB2
			colResult[13] =( PINB & B00000100)== 0 ? 1 : 0;
			//pin 52, PB1
			colResult[14] =( PINB & B00000010)== 0 ? 1 : 0;
			//pin 53, PB0
			colResult[15] =( PINB & B00000001)== 0 ? 1 : 0;


		for ( int colid = 0; colid < 16; colid += 2 )
		{

	uint8_t button[(NUM_BUTTONS+7)/8]; // 8 buttons per byte
};

const unsigned int ScanDelay = 4;

joyReport_t joyReport;
joyReport_t prevjoyReport;

/*
RotaryEncoder
