- File fromFile = FILE_NONE;
- Rank fromRank = RANK_NONE;
-
- // Promotion?
- if(strchr("BNRQ", str[right])) {
- promotion = piece_type_from_char(str[right]);
- right--;
- }
- else
- promotion = NO_PIECE_TYPE;
-
- // Find the moving piece:
- if(left < right) {
- if(strchr("BNRQK", str[left])) {
- pt = piece_type_from_char(str[left]);
- left++;
- }
- else
- pt = PAWN;
+ int state = START;
+
+ for (size_t i = 0; i < movestr.length(); i++)
+ {
+ char type, c = movestr[i];
+ if (pieceLetters.find(c) != std::string::npos)
+ type = 'P';
+ else if (c >= 'a' && c <= 'h')
+ type = 'F';
+ else if (c >= '1' && c <= '8')
+ type = 'R';
+ else
+ type = c;
+
+ switch (type) {
+ case 'P':
+ if (state == START)
+ {
+ pt = piece_type_from_char(c);
+ state = TO_FILE;
+ }
+ else if (state == PROMOTION)
+ {
+ promotion = piece_type_from_char(c);
+ state = (i < movestr.length() - 1) ? CHECK : END;
+ }
+ else
+ return MOVE_NONE;
+ break;
+ case 'F':
+ if (state == START)
+ {
+ pt = PAWN;
+ fromFile = toFile = file_from_char(c);
+ state = TO_RANK;
+ }
+ else if (state == TO_FILE)
+ {
+ toFile = file_from_char(c);
+ state = TO_RANK;
+ }
+ else if (state == TO_RANK && toFile != FILE_NONE)
+ {
+ // Previous file was for disambiguation
+ fromFile = toFile;
+ toFile = file_from_char(c);
+ }
+ else
+ return MOVE_NONE;
+ break;
+ case 'R':
+ if (state == TO_RANK)
+ {
+ toRank = rank_from_char(c);
+ state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
+ }
+ else if (state == TO_FILE && fromRank == RANK_NONE)
+ {
+ // It's a disambiguation rank instead of a file
+ fromRank = rank_from_char(c);
+ }
+ else
+ return MOVE_NONE;
+ break;
+ case 'x': case 'X':
+ if (state == TO_RANK)
+ {
+ // Previous file was for disambiguation, or it's a pawn capture
+ fromFile = toFile;
+ state = TO_FILE;
+ }
+ else if (state != TO_FILE)
+ return MOVE_NONE;
+ break;
+ case '=':
+ if (state == PROMOTION_OR_CHECK)
+ state = PROMOTION;
+ else
+ return MOVE_NONE;
+ break;
+ case '+': case '#':
+ if (state == PROMOTION_OR_CHECK || state == CHECK)
+ state = END;
+ else
+ return MOVE_NONE;
+ break;
+ default:
+ return MOVE_NONE;
+ break;
+ }