// File: /workspace/github_c_makefile_star2_O1/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, 0x40(%rsp)
movq %rcx, 0x28(%rsp)
movq %rdx, %r14
movq %rsi, %rbx
movq %rdi, 0x50(%rsp)
xorl %r15d, %r15d
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0xaede
addq $0x50, %r15
cmpq $0x13880, %r15          # imm = 0x13880
jne 0x9978
movq 0x230af(%rip), %rax     # 0x2ca48
movq %rax, 0x48(%rsp)
xorl %eax, %eax
leaq 0x38(%rsp), %rcx
movq %rax, (%rcx)
leaq 0x30(%rsp), %rcx
movq %rax, (%rcx)
xorl %r12d, %r12d
xorl %ebp, %ebp
movq $0x0, 0x20(%rsp)
movq $0x0, 0x18(%rsp)
xorl %r13d, %r13d
testl %ebp, %ebp
jne 0x9d76
movl $0x1, %edi
movl $0x38, %esi
callq 0x3310
movq %rax, %rbp
movq 0x50(%rsp), %rdi
movq %rax, %rsi
callq 0xbc59
movl %eax, %r10d
incq %r12
movq %r12, %rax
movabsq $0x790fb65668c26139, %rcx # imm = 0x790FB65668C26139
imulq %rcx, %rax
rorq $0x6, %rax
movabsq $0x10c6f7a0b5ed, %rcx   # imm = 0x10C6F7A0B5ED
cmpq %rcx, %rax
movq %r10, (%rsp)
ja 0x9a34
leaq 0x1918c(%rip), %rdi     # 0x22bb2
movq %r12, %rsi
xorl %eax, %eax
callq 0x3210
movq (%rsp), %r10
leal 0x1(%r13), %ecx
cmpl $0xd, %r10d
movq %r12, 0x58(%rsp)
jne 0x9aa1
xorl %ebp, %ebp
movq 0x20(%rsp), %rdi
testq %rdi, %rdi
je 0x9bb9
movl %ecx, %r13d
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x40(%rsp), %r8
callq 0x7da0
testl %eax, %eax
je 0x9c2b
movl %r15d, %ecx
shlq $0x6, %rcx
addq %r14, %rcx
cmpl $0x5, %r15d
movq (%rsp), %r10
ja 0x9c34
movq 0x30(%rcx), %rdx
cmpl $0x2, %eax
jne 0x9c5f
addq $0x2, %rdx
jmp 0x9c62
movl %ecx, 0xc(%rsp)
cmpq $0x0, 0x48(%rsp)
je 0x9abc
movq %rbp, %rdi
movq %rbx, %rsi
callq 0x9f10
movq (%rsp), %r10
cmpq $0x0, 0x28(%rsp)
je 0x9ae3
cmpl $0x1, 0x3b4(%r14)
je 0x9ae3
movq 0x28(%rsp), %rax
movq 0x8(%rax), %rdi
movq %rbp, %rsi
callq 0x10273
movq (%rsp), %r10
movslq %r13d, %rax
leaq (%rax,%rax,4), %rax
shlq $0x4, %rax
leaq (%rsp,%rax), %rdx
addq $0x60, %rdx
movq %rbx, %rsi
movq %rdx, 0x10(%rsp)
leaq 0x38(%rsp), %rcx
leaq 0x30(%rsp), %r8
movq %r14, %r9
pushq %rbp
pushq %r10
callq 0x9302
addq $0x10, %rsp
movl %eax, %r12d
cmpl $0xd, %eax
jne 0x9b66
testq %rbp, %rbp
movq 0x20(%rsp), %r13
je 0x9b3a
movq 0x30(%rbp), %rdi
callq 0x3070
movq %rbp, %rdi
callq 0x3070
movl $0x1, %ebp
cmpq $0x0, 0x18(%rsp)
sete %al
testq %r13, %r13
sete %cl
orb %al, %cl
je 0x9bc1
movq 0x10(%rsp), %rax
movq %rax, %r13
movq %rax, %r15
movl 0xc(%rsp), %ecx
jmp 0x9c9e
leal -0x6(%r12), %eax
cmpl $0x6, %eax
ja 0x9c3a
leaq 0x14029(%rip), %rcx     # 0x1dba4
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
jmpq *%rax
movq %rbp, %rdi
movq %rbx, %rsi
movq %r14, %rdx
callq 0x77f5
testq %rbp, %rbp
je 0x9ba8
movq 0x30(%rbp), %rdi
callq 0x3070
movq %rbp, %rdi
callq 0x3070
movl %r15d, %r12d
movl %r13d, %ecx
movq (%rsp), %r10
xorl %ebp, %ebp
jmp 0x9d4e
movl %r15d, %r12d
jmp 0x9d4e
cmpl $0xd, %r12d
je 0x9bf0
cmpl $0x1, 0x3b4(%r14)
jne 0x9bf0
movq 0x28(%r13), %rdi
movq 0x10(%rsp), %rax
movq 0x28(%rax), %rsi
callq 0x3330
movq 0x18(%rsp), %rcx
testl %eax, %eax
je 0x9d65
movq %r13, %rdi
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x40(%rsp), %r8
callq 0x7da0
testl %eax, %eax
je 0x9c7e
movl %r15d, %ecx
shlq $0x6, %rcx
addq %r14, %rcx
cmpl $0x5, %r15d
ja 0x9c71
movq 0x30(%rcx), %rdx
cmpl $0x2, %eax
jne 0x9c77
addq $0x2, %rdx
jmp 0x9c7a
movl %r15d, %r12d
movq (%rsp), %r10
jmp 0x9c69
incq 0x30(%rcx)
jmp 0x9c66
movq 0x10(%rsp), %rax
movsd (%rax), %xmm0
ucomisd 0x13e25(%rip), %xmm0    # 0x1da70
jne 0x9c53
jnp 0x9b84
xorl %ebp, %ebp
movq 0x20(%rsp), %r13
jmp 0x9b3f
incq %rdx
movq %rdx, 0x30(%rcx)
movl %r15d, %r12d
movl %r13d, %ecx
jmp 0x9d4e
incq 0x30(%rcx)
jmp 0x9c7e
incq %rdx
movq %rdx, 0x30(%rcx)
leaq 0x60(%rsp), %r15
movq %r15, %rdi
movq 0x10(%rsp), %r13
movq %r13, %rsi
callq 0xaf3c
movq %r13, %rax
movl $0x1, %ecx
movq %r15, %r13
cmpl $0x3e8, %ecx            # imm = 0x3E8
movq %r13, 0x20(%rsp)
jl 0x9d45
movl %ebp, 0xc(%rsp)
movq 0x28(%rax), %rsi
leaq 0x18f07(%rip), %rdi     # 0x22bc5
xorl %eax, %eax
callq 0x3210
movsd (%r13), %xmm0
mulsd 0x8(%r13), %xmm0
movq %r13, %rbp
movq %r13, %rax
movapd %xmm0, %xmm1
movsd (%rax), %xmm0
mulsd 0x8(%rax), %xmm0
ucomisd %xmm0, %xmm1
cmovaq %rax, %rbp
minsd %xmm1, %xmm0
movq 0x48(%rax), %rax
testq %rax, %rax
jne 0x9cd7
movq 0x10(%rsp), %rsi
movsd (%rsi), %xmm1
mulsd 0x8(%rsi), %xmm1
ucomisd %xmm0, %xmm1
jbe 0x9d1d
movq 0x48(%rbp), %r15
movq %rbp, %rdi
callq 0xaf3c
movq %r15, 0x48(%rbp)
movq $0x0, 0x13888(%rsp)
movl $0x3e7, %ecx            # imm = 0x3E7
leaq 0x13840(%rsp), %rax
movq %rax, 0x18(%rsp)
movq (%rsp), %r10
movl 0xc(%rsp), %ebp
jmp 0x9d4e
movq %r15, 0x18(%rsp)
movq (%rsp), %r10
movl %r12d, %r15d
movl %ecx, %r13d
cmpl $0xd, %r10d
movq 0x58(%rsp), %r12
jne 0x99ca
jmp 0x9d76
movq 0x10(%rsp), %rax
movq %rax, 0x48(%rcx)
movl %r15d, %r12d
jmp 0x9b5a
xorl %eax, %eax
callq 0xa909
testq %rax, %rax
jle 0x9d9a
xorl %eax, %eax
callq 0xa909
leaq 0x18e73(%rip), %rdi     # 0x22c03
movq %rax, %rsi
xorl %eax, %eax
callq 0x3210
xorl %r15d, %r15d
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0xaf09
addq $0x50, %r15
cmpq $0x13880, %r15          # imm = 0x13880
jne 0x9d9d
movl 0x22c93(%rip), %esi     # 0x2ca50
testl %esi, %esi
jle 0x9dcf
leaq 0x18eb8(%rip), %rdi     # 0x22c80
xorl %eax, %eax
callq 0x3210
movq 0x38(%rsp), %rdi
leaq -0x114b(%rip), %r15     # 0x8c90
movq %r15, %rsi
callq 0x34e0
movq 0x38(%rsp), %rdi
leaq -0x1104(%rip), %r12     # 0x8ceb
movq %r12, %rsi
callq 0x3660
movq 0x30(%rsp), %rdi
movq %r15, %rsi
callq 0x34e0
movq 0x30(%rsp), %rdi
movq %r12, %rsi
callq 0x3660
movl 0x22c39(%rip), %esi     # 0x2ca50
testl %esi, %esi
je 0x9e29
leaq 0x18ef8(%rip), %rdi     # 0x22d1a
xorl %eax, %eax
callq 0x3210
addq $0x30, %r14
leaq 0x17e1c(%rip), %r12     # 0x21c50
leaq 0x18f21(%rip), %r15     # 0x22d5c
xorl %r13d, %r13d
movslq (%r13,%r12), %rsi
addq %r12, %rsi
movq -0x10(%r14), %rdx
movq -0x8(%r14), %rcx
movq %rdx, %r8
subq %rcx, %r8
movq (%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 -0x10(%r14), %rax
addq %rax, 0x78(%rbx)
movq -0x8(%r14), %rcx
subq %rcx, %rax
addq %rax, 0x80(%rbx)
addq %rcx, 0x88(%rbx)
movq (%r14), %rax
addq %rax, 0x90(%rbx)
addq $0x4, %r13
addq $0x40, %r14
cmpq $0x38, %r13
jne 0x9e3e
movq 0x88(%rbx), %rsi
leaq 0x18f05(%rip), %rdi     # 0x22db9
xorl %eax, %eax
callq 0x3210
movq 0x90(%rbx), %rsi
leaq 0x18f09(%rip), %rdi     # 0x22dd2
xorl %eax, %eax
callq 0x3210
movq 0x80(%rbx), %rsi
leaq 0x18f0d(%rip), %rdi     # 0x22deb
xorl %eax, %eax
callq 0x3210
movq 0x78(%rbx), %rsi
subq 0x90(%rbx), %rsi
leaq 0x18f0f(%rip), %rdi     # 0x22e06
xorl %eax, %eax
callq 0x3210
addq $0x138e8, %rsp          # imm = 0x138E8
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq