// File: /workspace/github_c_makefile_star2_O2/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
cmpq $0x13880, %r15          # imm = 0x13880
je 0x7b40
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0x9014
addq $0x50, %r15
jmp 0x7b24
movq 0x21f01(%rip), %rax     # 0x29a48
movq %rax, 0x50(%rsp)
leaq 0x40(%rsp), %rax
andq $0x0, (%rax)
leaq 0x38(%rsp), %rax
andq $0x0, (%rax)
xorl %r15d, %r15d
xorl %esi, %esi
movq $0x0, 0x10(%rsp)
xorl %ecx, %ecx
xorl %edx, %edx
movq %rcx, 0x30(%rsp)
testl %esi, %esi
sete %cl
movq %rdx, 0x20(%rsp)
movslq %edx, %rax
imulq $0x50, %rax, %rax
addq %rsp, %rax
addq $0x60, %rax
movq %rax, 0x18(%rsp)
incq %r15
movq %r15, %rax
xorl %edx, %edx
movl $0xf4240, %esi          # imm = 0xF4240
divq %rsi
testb $0x1, %cl
je 0x7ea5
imulq $0xf4240, %rax, %rbp    # imm = 0xF4240
pushq $0x1
popq %rdi
pushq $0x38
popq %rsi
callq 0x3310
movq %rax, %r12
movq 0x58(%rsp), %rdi
movq %rax, %rsi
callq 0x9b6c
movl %eax, %r13d
cmpq %r15, %rbp
jne 0x7be6
leaq 0x17006(%rip), %rdi     # 0x1ebe2
movq %r15, %rsi
xorl %eax, %eax
callq 0x3210
movl 0xc(%rsp), %ebp
cmpl $0xd, %r13d
je 0x7e6e
cmpq $0x0, 0x50(%rsp)
je 0x7c07
movq %r12, %rdi
movq %rbx, %rsi
callq 0x8046
cmpq $0x0, 0x28(%rsp)
je 0x7c2a
cmpl $0x1, 0x3b4(%r14)
je 0x7c2a
movq 0x28(%rsp), %rax
movq 0x8(%rax), %rdi
movq %r12, %rsi
callq 0xe3dc
movq %rbx, %rsi
movq 0x18(%rsp), %rdx
leaq 0x40(%rsp), %rcx
leaq 0x38(%rsp), %r8
movq %r14, %r9
pushq %r12
pushq %r13
callq 0x754c
popq %rcx
popq %rdx
movl %eax, %r13d
addl $-0x6, %eax
cmpl $0x7, %eax
ja 0x7c65
leaq 0x11f68(%rip), %rcx     # 0x19bc4
movslq (%rcx,%rax,4), %rax
addq %rcx, %rax
jmpq *%rax
movq 0x18(%rsp), %rax
movsd (%rax), %xmm0
ucomisd 0x11e12(%rip), %xmm0    # 0x19a88
jne 0x7cf5
jp 0x7cf5
movq %r12, %rdi
movq %rbx, %rsi
movq %r14, %rdx
callq 0x5c9c
testq %r12, %r12
je 0x7c9f
movq 0x30(%r12), %rdi
callq 0x3070
movq %r12, %rdi
callq 0x3070
incq %r15
movb $0x1, %cl
jmp 0x7b95
testq %r12, %r12
je 0x7cc0
movq 0x30(%r12), %rdi
callq 0x3070
movq %r12, %rdi
callq 0x3070
cmpq $0x0, 0x30(%rsp)
sete %al
movq 0x10(%rsp), %rdi
testq %rdi, %rdi
sete %cl
orb %al, %cl
pushq $0x1
popq %rax
movl %eax, %ecx
movq 0x20(%rsp), %rdx
je 0x7dfe
leal 0x1(%rdx), %r12d
movl %eax, %esi
pushq $0xd
popq %rax
movl %eax, 0xc(%rsp)
jmp 0x7d21
movq 0x20(%rsp), %rdx
leal 0x1(%rdx), %r12d
cmpq $0x0, 0x30(%rsp)
sete %al
movq 0x10(%rsp), %rdi
testq %rdi, %rdi
sete %cl
xorl %esi, %esi
orb %al, %cl
je 0x7dd0
movl %r13d, 0xc(%rsp)
movq 0x18(%rsp), %rax
movq %rax, %rdi
movq %rdi, 0x10(%rsp)
movq %rax, %rcx
cmpl $0x3e7, %edx            # imm = 0x3E7
movl %r12d, %edx
jl 0x7b70
movl %esi, %ebp
movq 0x28(%rax), %rsi
leaq 0x16ea8(%rip), %rdi     # 0x1ebf5
xorl %eax, %eax
callq 0x3210
movq 0x10(%rsp), %r12
movsd (%r12), %xmm0
mulsd 0x8(%r12), %xmm0
movq %r12, %rax
testq %rax, %rax
je 0x7d8d
movsd (%rax), %xmm1
mulsd 0x8(%rax), %xmm1
ucomisd %xmm1, %xmm0
cmovaq %rax, %r12
minsd %xmm0, %xmm1
movq 0x48(%rax), %rax
movapd %xmm1, %xmm0
jmp 0x7d69
movq 0x18(%rsp), %rsi
movsd (%rsi), %xmm1
mulsd 0x8(%rsi), %xmm1
ucomisd %xmm0, %xmm1
jbe 0x7db3
movq 0x48(%r12), %r13
movq %r12, %rdi
callq 0x906a
movq %r13, 0x48(%r12)
andq $0x0, 0x13888(%rsp)
movl $0x3e7, %edx            # imm = 0x3E7
leaq 0x13840(%rsp), %rcx
movl %ebp, %esi
jmp 0x7b70
xorl %ecx, %ecx
cmpl $0x1, 0x3b4(%r14)
jne 0x7dfe
movq 0x28(%rdi), %rdi
movq 0x18(%rsp), %rax
movq 0x28(%rax), %rsi
callq 0x3330
xorl %ecx, %ecx
movq 0x20(%rsp), %rdx
movq 0x10(%rsp), %rdi
testl %eax, %eax
je 0x7e59
movl %ecx, 0x20(%rsp)
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x48(%rsp), %r8
callq 0x61bf
shlq $0x6, %rbp
addq %r14, %rbp
movl %eax, %edi
movq %rbp, %rsi
movl 0xc(%rsp), %edx
callq 0x7ad6
leaq 0x60(%rsp), %r12
movq %r12, %rdi
movq 0x18(%rsp), %rsi
callq 0x906a
movl 0x20(%rsp), %esi
movl %r13d, 0xc(%rsp)
movq %r12, 0x10(%rsp)
movq %r12, %rcx
pushq $0x1
popq %rax
movl %eax, %edx
jmp 0x7b70
movq 0x18(%rsp), %rax
movq 0x30(%rsp), %rcx
movq %rax, 0x48(%rcx)
xorl %esi, %esi
jmp 0x7d29
cmpq $0x0, 0x10(%rsp)
je 0x7ea5
movq 0x10(%rsp), %rdi
movq %rbx, %rsi
movq %r14, %rdx
movq 0x28(%rsp), %rcx
movq 0x48(%rsp), %r8
callq 0x61bf
shlq $0x6, %rbp
addq %r14, %rbp
movl %eax, %edi
movq %rbp, %rsi
movl 0xc(%rsp), %edx
callq 0x7ad6
xorl %eax, %eax
callq 0x8acd
testq %rax, %rax
jle 0x7ec9
xorl %eax, %eax
callq 0x8acd
leaq 0x16d74(%rip), %rdi     # 0x1ec33
movq %rax, %rsi
xorl %eax, %eax
callq 0x3210
xorl %r15d, %r15d
cmpq $0x13880, %r15          # imm = 0x13880
je 0x7ee8
leaq (%rsp,%r15), %rdi
addq $0x60, %rdi
callq 0x903c
addq $0x50, %r15
jmp 0x7ecc
movl 0x21b62(%rip), %esi     # 0x29a50
testl %esi, %esi
jle 0x7f00
leaq 0x16db7(%rip), %rdi     # 0x1ecb0
xorl %eax, %eax
callq 0x3210
movq 0x40(%rsp), %rdi
leaq -0xfd1(%rip), %r15      # 0x6f3b
movq %r15, %rsi
callq 0x34e0
movq 0x40(%rsp), %rdi
leaq -0xf8c(%rip), %r12      # 0x6f94
movq %r12, %rsi
callq 0x3660
movq 0x38(%rsp), %rdi
movq %r15, %rsi
callq 0x34e0
movq 0x38(%rsp), %rdi
movq %r12, %rsi
callq 0x3660
movl 0x21b08(%rip), %esi     # 0x29a50
testl %esi, %esi
je 0x7f5a
leaq 0x16df7(%rip), %rdi     # 0x1ed4a
xorl %eax, %eax
callq 0x3210
addq $0x20, %r14
leaq 0x15d1b(%rip), %r12     # 0x1dc80
leaq 0x16e20(%rip), %r15     # 0x1ed8c
xorl %r13d, %r13d
cmpq $0x38, %r13
je 0x7fdc
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
popq %rcx
popq %rdx
movq (%r14), %rax
addq %rax, 0x78(%rbx)
movdqu 0x8(%r14), %xmm0
subq 0x8(%r14), %rax
addq %rax, 0x80(%rbx)
movdqu 0x88(%rbx), %xmm1
paddq %xmm0, %xmm1
movdqu %xmm1, 0x88(%rbx)
addq $0x4, %r13
addq $0x40, %r14
jmp 0x7f6f
movq 0x88(%rbx), %rsi
leaq 0x16dff(%rip), %rdi     # 0x1ede9
xorl %eax, %eax
callq 0x3210
movq 0x90(%rbx), %rsi
leaq 0x16e03(%rip), %rdi     # 0x1ee02
xorl %eax, %eax
callq 0x3210
movq 0x80(%rbx), %rsi
leaq 0x16e07(%rip), %rdi     # 0x1ee1b
xorl %eax, %eax
callq 0x3210
movq 0x78(%rbx), %rsi
subq 0x90(%rbx), %rsi
leaq 0x16e09(%rip), %rdi     # 0x1ee36
xorl %eax, %eax
callq 0x3210
addq $0x138e8, %rsp          # imm = 0x138E8
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq