+/// move_to_san() takes a position and a move as input, where it is assumed
+/// that the move is a legal move for the position. The return value is
+/// a string containing the move in short algebraic notation.
+
+const string move_to_san(Position& pos, Move m) {
+
+ if (m == MOVE_NONE)
+ return "(none)";
+
+ if (m == MOVE_NULL)
+ return "(null)";
+
+ assert(is_ok(m));
+
+ Bitboard attackers;
+ bool ambiguousMove, ambiguousFile, ambiguousRank;
+ Square sq, from = move_from(m);
+ Square to = move_to(m);
+ PieceType pt = type_of(pos.piece_on(from));
+ string san;
+
+ if (is_castle(m))
+ san = (move_to(m) < move_from(m) ? "O-O-O" : "O-O");
+ else
+ {
+ if (pt != PAWN)
+ {
+ san = piece_type_to_char(pt);
+
+ // Disambiguation if we have more then one piece with destination 'to'
+ // note that for pawns is not needed because starting file is explicit.
+ attackers = pos.attackers_to(to) & pos.pieces(pt, pos.side_to_move());
+ clear_bit(&attackers, from);
+ ambiguousMove = ambiguousFile = ambiguousRank = false;
+
+ while (attackers)
+ {
+ sq = pop_1st_bit(&attackers);
+
+ if (file_of(sq) == file_of(from))
+ ambiguousFile = true;
+
+ if (rank_of(sq) == rank_of(from))
+ ambiguousRank = true;
+
+ ambiguousMove = true;
+ }
+
+ if (ambiguousMove)
+ {
+ if (!ambiguousFile)
+ san += file_to_char(file_of(from));
+ else if (!ambiguousRank)
+ san += rank_to_char(rank_of(from));
+ else
+ san += square_to_string(from);
+ }
+ }
+
+ if (pos.is_capture(m))
+ {
+ if (pt == PAWN)
+ san += file_to_char(file_of(from));
+
+ san += 'x';
+ }
+
+ san += square_to_string(to);
+
+ if (is_promotion(m))
+ {
+ san += '=';
+ san += piece_type_to_char(promotion_piece_type(m));
+ }
+ }
+
+ // The move gives check? We don't use pos.move_gives_check() here
+ // because we need to test for a mate after the move is done.
+ StateInfo st;
+ pos.do_move(m, st);
+ if (pos.in_check())
+ san += pos.is_mate() ? "#" : "+";
+ pos.undo_move(m);