| 296 | } |
| 297 | |
| 298 | extern "C" char* edlibAlignmentToCigar(const unsigned char* const alignment, const int alignmentLength, |
| 299 | const EdlibCigarFormat cigarFormat) { |
| 300 | if (cigarFormat != EDLIB_CIGAR_EXTENDED && cigarFormat != EDLIB_CIGAR_STANDARD) { |
| 301 | return 0; |
| 302 | } |
| 303 | |
| 304 | // Maps move code from alignment to char in cigar. |
| 305 | // 0 1 2 3 |
| 306 | char moveCodeToChar[] = {'=', 'I', 'D', 'X'}; |
| 307 | if (cigarFormat == EDLIB_CIGAR_STANDARD) { |
| 308 | moveCodeToChar[0] = moveCodeToChar[3] = 'M'; |
| 309 | } |
| 310 | |
| 311 | vector<char>* cigar = new vector<char>(); |
| 312 | char lastMove = 0; // Char of last move. 0 if there was no previous move. |
| 313 | int numOfSameMoves = 0; |
| 314 | for (int i = 0; i <= alignmentLength; i++) { |
| 315 | // if new sequence of same moves started |
| 316 | if (i == alignmentLength || (moveCodeToChar[alignment[i]] != lastMove && lastMove != 0)) { |
| 317 | // Write number of moves to cigar string. |
| 318 | int numDigits = 0; |
| 319 | for (; numOfSameMoves; numOfSameMoves /= 10) { |
| 320 | cigar->push_back('0' + numOfSameMoves % 10); |
| 321 | numDigits++; |
| 322 | } |
| 323 | reverse(cigar->end() - numDigits, cigar->end()); |
| 324 | // Write code of move to cigar string. |
| 325 | cigar->push_back(lastMove); |
| 326 | // If not at the end, start new sequence of moves. |
| 327 | if (i < alignmentLength) { |
| 328 | // Check if alignment has valid values. |
| 329 | if (alignment[i] > 3) { |
| 330 | delete cigar; |
| 331 | return 0; |
| 332 | } |
| 333 | numOfSameMoves = 0; |
| 334 | } |
| 335 | } |
| 336 | if (i < alignmentLength) { |
| 337 | lastMove = moveCodeToChar[alignment[i]]; |
| 338 | numOfSameMoves++; |
| 339 | } |
| 340 | } |
| 341 | cigar->push_back(0); // Null character termination. |
| 342 | char* cigar_ = static_cast<char *>(malloc(cigar->size() * sizeof(char))); |
| 343 | memcpy(cigar_, &(*cigar)[0], cigar->size() * sizeof(char)); |
| 344 | delete cigar; |
| 345 | |
| 346 | return cigar_; |
| 347 | } |
| 348 | |
| 349 | /** |
| 350 | * Build Peq table for given query and alphabet. |