// File: /workspace/github_c_makefile_star2_O3/sc932[P]ALE/src/ALElike.c
// Function: computeReadPlacements
void computeReadPlacements(samfile_t *ins, assemblyT *theAssembly, libraryParametersT *libParams, samfile_t *placementBam, FILE *snpPhaseFile) {
  int i;

  // creates an empty set of containers for reads and alignments
  alignSet_t alignments[N_PLACEMENTS];
  for(i=0; i < N_PLACEMENTS; i++) {
    initAlignment(&alignments[i]);
  }

  int samReadPairIdx = 0;
  int qOff = libParams->qOff;

  alignSet_t *currentAlignment = NULL;
  alignSet_t *head = NULL;

  int doRealign = realignParameters == NULL ? 0 : 1;
  long readCount = 0;

  void *mateTree1 = NULL;
  void *mateTree2 = NULL;
  enum MATE_ORIENTATION orientation, lastOrientation;
  int numberMapped;
  int stop = 0;
  while(stop == 0){ // read through all reads
    bam1_t *thisRead = bam_init1(); // allocate new memory for every read
    alignSet_t *thisAlignment = &alignments[samReadPairIdx]; // starts empty
    samReadPairIdx++;

    // reads in the next read from file (ins)
    orientation = readNextBAM(ins, thisRead);

    readCount++;
    if (readCount%1000000 == 0){
      printf("Read %ld reads...\n", readCount);
    }
    if (orientation == NO_READS){
      if (head != NULL) {
    	//fprintf(stderr, "last alignment.\n");
        numberMapped = applyPlacement(head, theAssembly, libParams, placementBam, snpPhaseFile);
        countPlacements(numberMapped, &libParams->mateParameters[lastOrientation], lastOrientation);
      }
      break; // end of file
    }

    // realign the read around the existing alignment if desired
    if (doRealign) {
    	realign(thisRead, theAssembly);
    }
    if (placementBam != NULL && libParams->isSortedByName != 1) {
    	// preserve the ordering of the bamfile (i.e. do not wait for mate to be found)
    	bam_write1(placementBam->x.bam, thisRead);
    }

    // populates thisAlignment, finds orientation relative to mate (if any)
    orientation = setAlignment(ins->header, theAssembly, thisAlignment, &mateTree1, &mateTree2, libParams, orientation, thisRead);
    libraryMateParametersT *mateParameters = &libParams->mateParameters[orientation];
    //fprintf(stderr, "Processing %s %d %s\n", bam1_qname(thisRead), orientation, MATE_ORIENTATION_LABELS[orientation]);


    if (orientation == NO_READS){
      bam_destroy1(thisRead); thisRead = 0;
      stop = 1;
      //fprintf(stderr, "no reads\n");
      // need to continue to apply the last alignment
    }else if (orientation == HALF_VALID_MATE) {
      // wait for the mate to be read
      // we placed current half mate in a tree to be retrieved when the mate is found
      // do not destroy thisRead
      samReadPairIdx--; // overwrite container we just used on next read
      //fprintf(stderr, "half valid mate\n");
      continue;
    }else if (orientation == UNMAPPED_PAIR || orientation == UNMAPPED_SINGLE || orientation == UNMAPPED_MATE || thisAlignment->likelihood == 0.0) {
      applyUnmapped(thisRead, theAssembly, libParams);
      samReadPairIdx--; // overwrite container we just used on next read
      bam_destroy1(thisRead); thisRead = 0;
      countPlacements(0, &libParams->mateParameters[orientation], orientation);
      //fprintf(stderr, "unmapped pair\n");
      continue;
    }

    // organize linked list of alignments for a specific read based on current state of input stream
    if(currentAlignment == NULL || head == NULL){ // first alignment
      //copyAlignment(&alignments[0], thisAlignment);
      currentAlignment = thisAlignment;
      head = currentAlignment;
      lastOrientation = orientation;
      //fprintf(stderr, "first alignment\n");
    } else if(stop == 0 && thisAlignment != NULL && libParams->isSortedByName == 1 && strcmp(head->name, thisAlignment->name) == 0){
      // if there is more than one placement/mapping/alignment per read the bam file must be sorted by name
      // test to see if this is another alignment of the current set or a new one
      // extend the set of alignments
      currentAlignment->nextAlignment = thisAlignment;
      currentAlignment = thisAlignment;
      //fprintf(stderr, "looking for another alignment\n");
    } else if (head == NULL) {
      assert(0);
    } else {
      numberMapped = applyPlacement(head, theAssembly, libParams, placementBam, snpPhaseFile);
      //fprintf(stderr, "new alignment: %s\n", thisAlignment->name);
      countPlacements(numberMapped, &libParams->mateParameters[lastOrientation], lastOrientation);

      // set this read as next head
      currentAlignment = &alignments[0];
      copyAlignment(currentAlignment, thisAlignment);
      samReadPairIdx = 1;
      head = currentAlignment;
      lastOrientation = orientation;
    } // end of setting a new alignment

    // make sure we do not overflow the number of placements
    if (samReadPairIdx >= N_PLACEMENTS) {
      printf("WARNING: Exceeded maximum number of duplicate placements: %s\n", thisAlignment->name);
      int previous = N_PLACEMENTS-2;
      currentAlignment = &alignments[previous];
      alignSet_t *tmp = head;
      alignSet_t *leastLikely = head;
      double least = head->likelihood*head->likelihoodInsert;
      while (tmp != NULL) {
        if (tmp->likelihood*tmp->likelihoodInsert < least) {
          least = tmp->likelihood*tmp->likelihoodInsert;
          leastLikely = tmp;
        }
        tmp = tmp->nextAlignment;
      }
      if (thisAlignment->likelihood*thisAlignment->likelihoodInsert > least) {
        // overwrite previous with current
        // printf("WARNING: exceeded maximum placements. Replacing %f with %f\n", leastLikely->likelihood, thisAlignment->likelihood);
        tmp = leastLikely->nextAlignment;
        copyAlignment(leastLikely, thisAlignment);
        leastLikely->nextAlignment = tmp;
      } else {
        // printf("WARNING: exceeded maximum placements.  Dropping low probability placement %f\n", thisAlignment->likelihood);
      }
      currentAlignment->nextAlignment = NULL;
      samReadPairIdx = N_PLACEMENTS-1;
    } // end of placement overflow protection
  } // end of BAM reading

  if (getMultiplePrimaryAlignments() > 0)
	  printf("WARNING: There were %ld reads with multiple primary alignments.  ALE ignored these and treated them as secondary alignments\n", getMultiplePrimaryAlignments());

  // tear down array cached variables
  for(i=0; i < N_PLACEMENTS; i++) {
    destroyAlignment(&alignments[i]);
  }

  if (mateTreeCount > 0) {
      printf("WARNING: There were  (%d) inconsistant/remaining/missing/orphaned mated reads.\nThese should not exist... Consider fixing your input BAM.... For example:\n", mateTreeCount);
      // //printf("Orphaned Read1:\n");
  }
  twalk(mateTree1, mateTreeApplyRemainderPlacement);
  tdestroy(mateTree1,mateTreeFreeNode);

  if (mateTreeCount > 0) {
      //printf("Orphaned Read2 %d\n", mateTreeCount);
  }
  twalk(mateTree2, mateTreeApplyRemainderPlacement);
  tdestroy(mateTree2,mateTreeFreeNode);

  //printf("Destroyed mateTree (%d)\n", mateTreeCount);
  if (mateTreeCount != 0)
	  printf("WARNING: twalk & tdestroy did not clean up the %d orphaned reads\n", mateTreeCount);

  for(orientation = 0; orientation < MATE_ORIENTATION_MAX; orientation++) {
    libraryMateParametersT *mateParams = &libParams->mateParameters[orientation];

    printf("%s orientation with %ld reads, %ld mapped, %ld unmapped, %ld placed, %ld mappedButNotPlaced\n", MATE_ORIENTATION_LABELS[orientation], mateParams->count, mateParams->mapped, mateParams->count - mateParams->mapped, mateParams->placed, mateParams->mapped - mateParams->placed);
    theAssembly->totalReads += mateParams->count;
    theAssembly->totalUnmappedReads += mateParams->count - mateParams->mapped;
    theAssembly->totalMappedReads += mateParams->mapped;
    theAssembly->totalPlacedReads += mateParams->placed;
  }
  printf("Total mapped reads: %ld\n", theAssembly->totalMappedReads);
  printf("Total placed reads: %ld\n", theAssembly->totalPlacedReads);
  printf("Total unmapped reads: %ld\n", theAssembly->totalUnmappedReads);
  printf("Total unplaced reads: %ld\n", theAssembly->totalReads - theAssembly->totalPlacedReads);

  // this is done in applyUnmapped now...
  // theAssembly->totalScore += getMinLogLike()*theAssembly->totalUnmappedReads;

}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x138e8, %rsp          # imm = 0x138E8
movq %r8, 0x48(%rsp)
movq %rcx, 0x28(%rsp)
movq %rdx, %r14
movq %rsi, %rbx
movq %rdi, 0x58(%rsp)
xorl %r15d, %r15d
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0xb18f
addq $0x50, %r15
cmpq $0x13880, %r15          # imm = 0x13880
jne 0x9c2d
movq 0x22dfa(%rip), %rax     # 0x2ca48
movq %rax, 0x50(%rsp)
xorl %eax, %eax
leaq 0x40(%rsp), %rcx
movq %rax, (%rcx)
leaq 0x38(%rsp), %rcx
movq %rax, (%rcx)
movl $0x0, 0xc(%rsp)
movq $0x0, 0x20(%rsp)
xorl %r15d, %r15d
movq $0x0, 0x30(%rsp)
movl $0x1, %edi
movl $0x38, %esi
callq 0x3310
movq %rax, %rbp
movq 0x58(%rsp), %rdi
movq %rax, %rsi
callq 0xbed2
movl %eax, %r12d
movq 0x30(%rsp), %rcx
incq %rcx
movq %rcx, %rax
movq %rcx, 0x30(%rsp)
movabsq $0x790fb65668c26139, %rcx # imm = 0x790FB65668C26139
imulq %rcx, %rax
rorq $0x6, %rax
movabsq $0x10c6f7a0b5ed, %rcx   # imm = 0x10C6F7A0B5ED
cmpq %rcx, %rax
ja 0x9ce8
leaq 0x18f36(%rip), %rdi     # 0x22c12
movq 0x30(%rsp), %rsi
xorl %eax, %eax
callq 0x3210
cmpl $0xd, %r12d
je 0x9fad
cmpq $0x0, 0x50(%rsp)
je 0x9d05
movq %rbp, %rdi
movq %rbx, %rsi
callq 0xa197
cmpq $0x0, 0x28(%rsp)
je 0x9d28
cmpl $0x1, 0x3b4(%r14)
je 0x9d28
movq 0x28(%rsp), %rax
movq 0x8(%rax), %rdi
movq %rbp, %rsi
callq 0x1060c
movslq 0xc(%rsp), %rax
leaq (%rax,%rax,4), %rax
shlq $0x4, %rax
leaq (%rsp,%rax), %rdx
addq $0x60, %rdx
movq %rbx, %rsi
movq %rdx, 0x10(%rsp)
leaq 0x40(%rsp), %rcx
leaq 0x38(%rsp), %r8
movq %r14, %r9
pushq %rbp
pushq %r12
callq 0x95d3
addq $0x10, %rsp
movl %eax, %r12d
xorl %edx, %edx
addl $-0x6, %eax
cmpl $0x7, %eax
ja 0x9dac
leaq 0x13e82(%rip), %rcx     # 0x1dbf4
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
jmpq *%rax
movq %rbp, %rdi
movq %rbx, %rsi
movq %r14, %rdx
callq 0x7b4c
testq %rbp, %rbp
je 0x9d9f
movq 0x30(%rbp), %rdi
callq 0x3070
movq %rbp, %rdi
callq 0x3070
movl %r13d, %r12d
movq %r15, %rbp
xorl %edx, %edx
jmp 0x9f8c
movq 0x10(%rsp), %rax
movsd (%rax), %xmm0
ucomisd 0x13cd3(%rip), %xmm0    # 0x1da90
jne 0x9dc1
jnp 0x9d7b
movq 0x20(%rsp), %rbp
testq %rbp, %rbp
sete %al
testq %r15, %r15
sete %cl
xorl %edx, %edx
orb %al, %cl
je 0x9eed
movl %r12d, %esi
movq 0x10(%rsp), %rcx
movq %rcx, %rbp
jmp 0x9e33
movl %r13d, %r12d
movq %r15, %rbp
jmp 0x9f8c
testq %rbp, %rbp
je 0x9e0a
movq 0x30(%rbp), %rdi
callq 0x3070
movq %rbp, %rdi
callq 0x3070
cmpq $0x0, 0x20(%rsp)
sete %al
testq %r15, %r15
sete %cl
orb %al, %cl
movl $0xd, %esi
movl $0x1, %edx
movq 0x10(%rsp), %rcx
movq %rcx, %rbp
je 0x9f1a
movl 0xc(%rsp), %eax
cmpl $0x3e7, %eax            # imm = 0x3E7
jl 0x9eda
movl %esi, %r13d
movl %edx, 0x1c(%rsp)
movq 0x28(%rcx), %rsi
leaq 0x18dd1(%rip), %rdi     # 0x22c25
xorl %eax, %eax
callq 0x3210
movsd (%rbp), %xmm0
mulsd 0x8(%rbp), %xmm0
movq %rbp, %r15
movq %rbp, %rax
movapd %xmm0, %xmm1
movsd (%rax), %xmm0
mulsd 0x8(%rax), %xmm0
ucomisd %xmm0, %xmm1
cmovaq %rax, %r15
minsd %xmm1, %xmm0
movq 0x48(%rax), %rax
testq %rax, %rax
jne 0x9e6b
movq 0x10(%rsp), %rsi
movsd (%rsi), %xmm1
mulsd 0x8(%rsi), %xmm1
ucomisd %xmm0, %xmm1
jbe 0x9eb1
movq 0x48(%r15), %r12
movq %r15, %rdi
callq 0xb1ed
movq %r12, 0x48(%r15)
movq $0x0, 0x13888(%rsp)
movl $0x3e7, 0xc(%rsp)       # imm = 0x3E7
movl %r13d, %r12d
leaq 0x13840(%rsp), %rax
movq %rax, 0x20(%rsp)
jmp 0x9f88
incl %eax
movl %eax, 0xc(%rsp)
movl %esi, %r12d
movq %rcx, 0x20(%rsp)
jmp 0x9f8c
xorl %edx, %edx
cmpl $0x1, 0x3b4(%r14)
jne 0x9f1a
movq 0x28(%r15), %rdi
movq 0x10(%rsp), %rax
movq 0x28(%rax), %rsi
callq 0x3330
movq 0x10(%rsp), %rcx
xorl %edx, %edx
testl %eax, %eax
je 0x9f9c
movl %edx, 0x1c(%rsp)
movq %r15, %rdi
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x48(%rsp), %r8
callq 0x80df
movq 0x10(%rsp), %rsi
testl %eax, %eax
je 0x9f6b
movl %r13d, %ecx
shlq $0x6, %rcx
addq %r14, %rcx
cmpl $0x5, %r13d
ja 0x9f5e
movq 0x30(%rcx), %rdx
cmpl $0x2, %eax
jne 0x9f64
addq $0x2, %rdx
jmp 0x9f67
incq 0x30(%rcx)
jmp 0x9f6b
incq %rdx
movq %rdx, 0x30(%rcx)
leaq 0x60(%rsp), %r15
movq %r15, %rdi
callq 0xb1ed
movl $0x1, 0xc(%rsp)
movq %r15, %rbp
movq %r15, 0x20(%rsp)
movl 0x1c(%rsp), %edx
movq %rbp, %r15
movl %r12d, %r13d
testl %edx, %edx
je 0x9c82
jmp 0x9ffa
movq %rcx, 0x48(%rbp)
xorl %edx, %edx
movl %r13d, %esi
movq %r15, %rbp
jmp 0x9e33
testq %r15, %r15
je 0x9ffa
movq %r15, %rdi
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x48(%rsp), %r8
callq 0x80df
testl %eax, %eax
je 0x9ffa
movl %r13d, %ecx
shlq $0x6, %rcx
addq %r14, %rcx
cmpl $0x5, %r13d
ja 0x9fed
movq 0x30(%rcx), %rdx
cmpl $0x2, %eax
jne 0x9ff3
addq $0x2, %rdx
jmp 0x9ff6
incq 0x30(%rcx)
jmp 0x9ffa
incq %rdx
movq %rdx, 0x30(%rcx)
xorl %eax, %eax
callq 0xabd1
testq %rax, %rax
jle 0xa01e
xorl %eax, %eax
callq 0xabd1
leaq 0x18c4f(%rip), %rdi     # 0x22c63
movq %rax, %rsi
xorl %eax, %eax
callq 0x3210
xorl %r15d, %r15d
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0xb1ba
addq $0x50, %r15
cmpq $0x13880, %r15          # imm = 0x13880
jne 0xa021
movl 0x22a0f(%rip), %esi     # 0x2ca50
testl %esi, %esi
jle 0xa053
leaq 0x18c94(%rip), %rdi     # 0x22ce0
xorl %eax, %eax
callq 0x3210
movq 0x40(%rsp), %rdi
leaq -0x10f9(%rip), %r15     # 0x8f66
movq %r15, %rsi
callq 0x34e0
movq 0x40(%rsp), %rdi
leaq -0x10b2(%rip), %r12     # 0x8fc1
movq %r12, %rsi
callq 0x3660
movq 0x38(%rsp), %rdi
movq %r15, %rsi
callq 0x34e0
movq 0x38(%rsp), %rdi
movq %r12, %rsi
callq 0x3660
movl 0x229b5(%rip), %esi     # 0x2ca50
testl %esi, %esi
je 0xa0ad
leaq 0x18cd4(%rip), %rdi     # 0x22d7a
xorl %eax, %eax
callq 0x3210
addq $0x20, %r14
leaq 0x17bf8(%rip), %r12     # 0x21cb0
leaq 0x18cfd(%rip), %r15     # 0x22dbc
xorl %r13d, %r13d
movslq (%r13,%r12), %rsi
addq %r12, %rsi
movq (%r14), %rdx
movq 0x8(%r14), %rcx
movq %rdx, %r8
subq %rcx, %r8
movq 0x10(%r14), %r9
movq %rcx, %r10
subq %r9, %r10
subq $0x8, %rsp
movq %r15, %rdi
xorl %eax, %eax
pushq %r10
callq 0x3210
addq $0x10, %rsp
movq (%r14), %rax
addq %rax, 0x78(%rbx)
subq 0x8(%r14), %rax
movdqu 0x8(%r14), %xmm1
addq %rax, 0x80(%rbx)
movdqu 0x88(%rbx), %xmm0
paddq %xmm1, %xmm0
movdqu %xmm0, 0x88(%rbx)
addq $0x4, %r13
addq $0x40, %r14
cmpq $0x38, %r13
jne 0xa0c2
movq %xmm0, %rsi
leaq 0x18cde(%rip), %rdi     # 0x22e19
xorl %eax, %eax
callq 0x3210
movq 0x90(%rbx), %rsi
leaq 0x18ce2(%rip), %rdi     # 0x22e32
xorl %eax, %eax
callq 0x3210
movq 0x80(%rbx), %rsi
leaq 0x18ce6(%rip), %rdi     # 0x22e4b
xorl %eax, %eax
callq 0x3210
movq 0x78(%rbx), %rsi
subq 0x90(%rbx), %rsi
leaq 0x18ce8(%rip), %rdi     # 0x22e66
xorl %eax, %eax
callq 0x3210
addq $0x138e8, %rsp          # imm = 0x138E8
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq