#!/usr/bin/perl
##---------------------------------------------------------------------------##
##  File:
##      @(#) ProcessRepeats
##  Author:
##      Arian Smit <asmit@systemsbiology.org>
##      Robert Hubley <rhubley@systemsbiology.org>
##      original ExtractObjects module by Chris Abadjian
##      and Todd Smith.
##  Description:
##      Takes RepeatMasker output to produce an annotation table.
##
#******************************************************************************
#* Copyright (C) University of Washington 1996-1999 Developed by Arian Smit,
#* Philip Green and Colin Wilson of the University of Washington Department of
#* Genomics.
#*
#* Copyright (C) Arian Smit 2000-2001
#*
#* Copyright (C) Institute for Systems Biology 2002-2004 Developed by
#* Arian Smit and Robert Hubley.
#*
#* This work is licensed under the Open Source License v2.1.  To view a copy
#* of this license, visit http://www.opensource.org/licenses/osl-2.1.php or
#* see the license.txt file contained in this distribution.
#*
###############################################################################
# ChangeLog
#
#   $Log: ProcessRepeats,v $
#   Revision 1.40  2004/09/09 22:43:47  rhubley
#   Cleanup before a distribution
#
#
###############################################################################
#
# To Do:
# The two alignments of L1 elements presented on one line (L1..extended
# appear in reverse order in the .ali file (no effect in .out file)
#
# includes
use FindBin;
use lib $FindBin::RealBin;
use Getopt::Long;
use Taxonomy;

# A bug in 5.8 produces way too many warnings
if ( $] && $] >= 5.008003 ) {
  use warnings;
}

my $DIRECTORY = "$FindBin::Bin";

my ( $script ) = ( $0 =~ m|([^/]*)$| );
$USAGE = "usage: $script [-options] <RepeatMasker .cat file(s)>

The following species options are available (choose only one):
-m(us), -rat, -rodent, -cow, -pig, -artiodactyl = -cetacea
-cat, -dog, -carnivore, -mammal, -chicken, -fugu, -danio
-drosophila, -elegans, -arabidopsis, -rice, -wheat, -maize
or
-species  <query species>   (currently only allows species listed above)
The -species option will replace the individual species options in the next release
-lib   skips most of processing, does not produce a .tbl file unless the
       custom library is in the >name#class format.

-nolow does not display simple repeats or low_complexity DNA in the annotation
-noint skips steps specific to interspersed repeats, saving lots of time
-u     creates an untouched annotation file besides the manipulated file
-xm    creates an additional output file in cross_match format (for parsing)
-ace   creates an additional output file in ACeDB format
-gff   creates an additional Gene Feature Finding format
-poly  creates an output file listing only potentially polymorphic simple repeats
-no_id leaves out final column with unique number for each element (was default)
-fixed creates an (old style) annotation file with fixed width columns
-excln calculates repeat densities excluding long stretches of Ns in the query
-orf2   results in sometimes negative coordinates for L1 elements; all L1 subfamilies
       are aligned over the ORF2 region, sometimes improving interpretation of data
-a     shows the alignments in a .align output file
";

die $USAGE if ( $#ARGV == -1 );

#arg list
@opts =
    qw (a ace debug excln fixed gff lib=s noint nolow orf2 orifile=s no_id poly species=s u xm mammal mus rat rod|rodent cow pig artiodactyl cat dog carnivore chicken fugu danio drosophila elegans arabidopsis rice wheat maize primate);
$opt_a = $opt_ace = $opt_debug = $opt_excln = $opt_fixed = $opt_gff =
    $opt_no_id = $opt_lib = $opt_nolow = $opt_noint = $opt_orf2 = $opt_orifile =
    $opt_poly = $opt_species = $opt_u = $opt_xm = 0;
$opt_mammal = $opt_mus = $opt_rat = $opt_rod = $opt_cow = $opt_pig =
    $opt_artiodactyl = $opt_cat = $opt_dog = $opt_carnivore = $opt_chicken =
    $opt_fugu = $opt_danio = $opt_drosophila = $opt_elegans = $opt_arabidopsis =
    $opt_rice = $opt_wheat = $opt_maize      = $opt_primate = 0;

# offering all these species options just to not confuse the user who is used to a certain option in reepatmasker
# currently processrepeats only has special treatment for primates, rodents, and "other mammals".

# get the supplied command line options, and set flags
unless ( GetOptions( @opts ) ) {
  printf STDERR $USAGE;
  exit( 1 );
}

##
## Species Options and Taxonomy Processing
##
if ( $opt_species ) {

  # Need to set opt_species, opt_mammal, opt_mus
  my $tax = Taxonomy->new( taxonomyDataFile => "$DIRECTORY/taxonomy.dat" );

  if ( $tax->isA( $opt_species, "primates" ) ) {
    $opt_primate = 1;
  }
  elsif ( $tax->isA( $opt_species, "rodentia" ) ) {
    $opt_mus = 1;
  }
  elsif ( $tax->isA( $opt_species, "mammalia" ) ) {
    $opt_mammal = 1;
  }
  undef $tax;
}
else {
  $opt_species = "Homo";
  $opt_primate = 1;
}

#RMH#&checkformultiplespeciesoptions; # basically identical to repeatmasker script's
# necessary to run processrepeats separately
#RMH#if ($opt_species =~ /^mus$|^rattus$|__rodent$/i || $opt_rod) {
#RMH#    $opt_mus = 1;
#RMH#} elsif ($opt_species =~ /^mammal$|__carnivore$|__artiodactyl$|^felis$|^canis$|^bos$|^sus$|^equus$/i) {
#RMH#    $opt_mammal = 1;
#RMH#} elsif ($opt_mus) {
#RMH#    $opt_species = "rodent";	# right now, only to get $opt_species to be something
#RMH#} elsif ($opt_mammal) {
#RMH#    $opt_species = "mammalian";	# only to get $opt_species to be something
#RMH#}
#RMH#$opt_species = "Homo" unless $opt_species || $opt_lib;

##################################################

$poundformat = "";
if ( $opt_lib ) {
  open( IN, "$opt_lib" );
  while ( <IN> ) {
    if ( /^>\S+\#\S+/ ) {
      $poundformat = 1;

      #assuming that this represents my classification formatting; no sure thing
      #could make it more restrictive by also requiring a backslash
      last;
    }
  }
}
else {
  $poundformat = 1;
}

#test to do: if there's one sequence in it without classification, does it croak?
# as happened to me; not real bad, just some error messages

foreach $file ( @ARGV ) {
  open( INCAT, $file ) || die "Can\'t open file $file\n";

  # clear the buffer, counts between files
  &ZeroCounts();
  &ResetPrevious();
  unless ( $opt_fixed ) {
    $widthSW       = $widthBeginAlign = $widthSeq2Begin = 5;
    $widthPctSubst = $widthPctDelete  = $widthPctInsert = 4;
    $widthSeq1Name = $widthHitName    = 8;
    $widthEndAlign = $widthLeftOver   = $widthSeq2End   = 4;
    $widthclass    = 10;
    $widthLeftUnaligned = 6;
    $widthID            = 3;
  }

  # get some data from .cat file
  $runningtot = $runningnonN = $totalSeqLen = $nonNSeqLen = $frac_GC = 0;
  $exclnote   = $versionmode = $engine      = $dbversion  = "";

  while ( <INCAT> ) {
    if ( /^Fragment length:/ ) {
      my @bit = split;
      $runningtot -= 1000 if $runningtot;    # 1000 bp overlap, doesn't change
      $runningtot += $bit[ 2 ];
      $bit[ 4 ] =~ s/\(//;
      $runningnonN -= 1000 if $runningnonN;
      $runningnonN += $bit[ 4 ];
    }
    elsif ( /^\d+ sequences? with \d+/ ) {
      my @bit = split;
      $seq_cnt     = $bit[ 0 ];
      $totalSeqLen = $bit[ 3 ];
      ( $nonNSeqLen = $bit[ 5 ] ) =~ s/\(//;
    }
    elsif ( $totalSeqLen && /\w+/ ) {
      my @bit = split;
      $maskedlength = $bit[ 0 ] if $bit[ 2 ] eq 'masked';
      $frac_GC      = $bit[ 2 ] if $bit[ 0 ] eq 'GC';
      $versionmode  = $_        if $bit[ 0 ] eq 'RepeatMasker';
      $engine = $_ if /^run with/;
      if ( /^RepBase/ ) {
        $dbversion = $_;
        last;
      }
    }
  }
  close INCAT;
  if ( $runningnonN && !$totalSeqLen && !$nonNSeqLen ) {
    print
"The total sequence lengths given in the .tbl file may not be accurate\n"
        if $seq_cnt > 1;

#This isn't working for batches with large sequences hidden in it. The .cat file will contain lines
#starting with "Fragment length:", but there are also unfragmented sequences in the total.
    $totalSeqLen = $runningtot;
    $nonNSeqLen  = $runningnonN;
  }
  if ( $totalSeqLen ) {
    $totseqlen = $totalSeqLen;
    if ( $opt_excln ) {
      ( $totseqlen = $nonNSeqLen ) =~ s/\( (\d+).*/$1/;
      $exclnote = "Runs of >20 Ns in query were excluded in % calcs\n";
    }
  }
  else {
    $totseqlen = 100000;
    print
"Total sequence length unknown. The fractions in the .tbl file are incorrect.\n";
  }
  $nonNSeqLen    = "(" . "$nonNSeqLen" . " bp excl N-runs)";
  $maskedpercent = $maskedlength / $totseqlen if $totseqlen;

  # extract the parse- or alignment lines from the raw cross_match files
  my $xm   = new ExtractObjects( $file );
  my $lRef = $xm->getHits();
  $catfile = $file;
  $file =~ s/\.(temp)?cat$//;
  ( $filename = $file ) =~ s/(.*\/)//;
  unless ( @{$lRef} ) {
    my $filenaam = $file;
    $filenaam = $opt_orifile if $opt_orifile;
    open( OUT, ">$file.out" );
    print STDERR "\n\n\nNo repetitive sequences were detected in $filenaam\n";
    print OUT "There were no repetitive sequences detected in $filenaam\n";
    close( OUT );
    next;
  }

  if ( $opt_a ) {
    my $gcaliinfo = $lastaliid = "";
    %aligninfo = %gcaliinfo = ();
    $alignid = "";
    for ( @catfile ) {    # comes from ExtractObjects package
      if ( /\(\d+\)/ ) {
        my @bit      = split;
        my $savename = quotemeta $bit[ 4 ];
        $alignid = "$savename" . "_$bit[5]" . "_$bit[6]";
        next if $aligninfo{$alignid};    # eliminates exact duplicates
        $aligninfo{$alignid} = $_;
        $gcaliinfo{$alignid} = $gcaliinfo;
      }
      elsif ( $alignid ) {
        $aligninfo{$alignid} .= $_;
        $alignid = "" if /^Gap_init/;
      }
      if ( /^Score matrix/ ) {
        /.*p(\d\d)g.matrix/;
        $gcaliinfo = $1 if $1;
      }
    }
    open( OUTALIGN, ">$file.align" );
  }
  @catfile = ();    # can be huge and not needed anymore

  print STDERR "processing output: ";
  @sortedHits  = sort byNameThenByBegin ( @{$lRef} );
  %Seq1Lengths = ();

  open( OUTRAW, ">$file.ori.out" ) if ( $opt_u || !$poundformat );
  $opt_xm
      && ( open( OUTXM, ">$file.out.xm" )
           || die "can't create $file.out.xm\n" );
  $opt_ace
      && ( open( OUTACE, ">$file.out.ace" )
           || die "can't create $file.out.ace\n" );
  $opt_poly
      && ( open( OUTPOLY, ">$file.polyout" )
           || die "can't create $file.out.polyout\n" );

  if ( $opt_gff ) {
    open( OUTGFF, ">$file.out.gff" ) || die "can't create $file.out.gff\n";
    print OUTGFF "##gff-version 2\n";
    printf OUTGFF "##date %4d-%02d-%02d\n", ( localtime )[ 5 ] + 1900,
        ( localtime )[ 4 ] + 1, ( localtime )[ 3 ];    # date as 1999-09-24...
    ( my $seqname = $file ) =~ s/^.*\///;
    print OUTGFF "##sequence-region $seqname",
        ( $totseqlen ? " 1 $totseqlen" : '' ), "\n";
  }

CYCLE0:
  for ( $i = 0 ; $i <= $#sortedHits ; $i++ ) {
    print STDERR "." if ( $i + 1 ) % 1000 == 0;
    &NameCurrent( $i );
    $LeftOver =~ tr/[\(\)]//d;
    $ID                = $i + 1;
    $id{$ID}           = $ID;
    $div{$ID}          = $PctSubst;
    $class{$ID}        = $ClassName;
    $numberoffragments = $#sortedHits + 1;

    $HitName =~ s/_short_$//;

    # remove exact duplicates; though taken care of later on
    # necessary at this spot to eliminate poly A tails that have been
    # reported twice in overlaps of fragments; obviously need to merge
    # into one check for duplicates and overlaps.
    if (    $i
         && $SW == $sortedHits[ $i - 1 ]->getSW()
         && $PctSubst == $sortedHits[ $i - 1 ]->getPctSubst()
         && $Seq1Name eq $sortedHits[ $i - 1 ]->getSeq1Name()
         && $BeginAlign == $sortedHits[ $i - 1 ]->getSeq1Beg()
         && $EndAlign == $sortedHits[ $i - 1 ]->getSeq1End() )
    {
      next;
    }
    if ( $opt_u || !$poundformat ) {
      next
          if $i
          && $BeginAlign == $sortedHits[ $i - 1 ]->getSeq1Beg()
          && $EndAlign == $sortedHits[ $i - 1 ]->getSeq1End();
      my $Overlapped = "";
      $LeftOverPrint = $sortedHits[ $i ]->getLeftOver();

      if ( $RevComp eq "C" ) {
        $Seq2BeginPrint = "(" . $sortedHits[ $i ]->get3PrimeUnaligned() . ")";
        $LeftUnalignedPrint = $sortedHits[ $i ]->getSeq2Beg();
      }
      else {
        $Seq2BeginPrint     = $sortedHits[ $i ]->getSeq2Beg();
        $LeftUnalignedPrint =
            "(" . $sortedHits[ $i ]->get3PrimeUnaligned() . ")";
      }
      if (    $i >= 1
           && $BeginAlign <= $sortedHits[ $i - 1 ]->getSeq1End()
           && $SW < $sortedHits[ $i - 1 ]->getSW()
           || $i < $#sortedHits
           && $EndAlign >= $sortedHits[ $i + 1 ]->getSeq1Beg()
           && $SW < $sortedHits[ $i + 1 ]->getSW() )
      {
        $Overlapped = "*";
      }
      $ClassName = "" unless $ClassName;

      # sequence names get truncated to 20 letters. Too
      # cumbersome to change.  However, names like
      # /mnt/user/users/FlipvanTiel/mystuff/sequence1 better be
      # clipped from the end. Thus:
      $Seq1Name = substr( $Seq1Name, -20 )
          if length $Seq1Name > 20 && $Seq1Name =~ /^\//;
      write OUTRAW;
    }

    if ( $opt_a ) {
      my $savename = quotemeta $Seq1Name;
      my $curid    = "$savename" . "_$BeginAlign" . "_$EndAlign";
      if (    $gcaliinfo{$curid}
           && ( !$lastaliid || $gcaliinfo{$curid} != $gcaliinfo{$lastaliid} )
           && $aligninfo{$curid} !~ /\#Simple|\#Low_/ )
      {
        print OUTALIGN
"Assumed background GC level in scoring matrices is $gcaliinfo{$curid} \%\n\n";
      }
      $lastaliid = $curid;
      print OUTALIGN "$aligninfo{$curid}\n\n";
    }

    if ( !$poundformat ) {
      if ( $opt_ace ) {
        if ( $RevComp eq "C" ) {
          print OUTACE
"Motif_homol \"$HitName\" \"RepeatMasker\" $PctSubst $BeginAlign $EndAlign - $Seq2End $Seq2Begin\n";
        }
        else {
          print OUTACE
"Motif_homol \"$HitName\" \"RepeatMasker\" $PctSubst $BeginAlign $EndAlign + $Seq2Begin $Seq2End\n";
        }
      }
      if ( $opt_xm ) {
        my $tempclassname = "";
        $tempclassname = "\#" . "$ClassName" if $ClassName;
        print OUTXM
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign "
            . "$LeftOverPrint $RevComp $HitName$tempclassname $Seq2BeginPrint $Seq2End $LeftUnalignedPrint\n";
      }
      if ( $opt_gff ) {
        my $source;
        if ( $HitName =~ /Alu/ ) {
          $source = 'RepeatMasker_SINE';
        }
        else {    #
          $source = 'RepeatMasker';
        }
        print OUTGFF "$Seq1Name\t$source\tsimilarity\t",
            "$BeginAlign\t$EndAlign\t$PctSubst\t",
            ( $RevComp eq 'C' ? '-' : '+' ), "\t.\t",
            "Target \"Motif:$HitName\" $Seq2Begin $Seq2End\n";
      }
      &MoveToPast();
    }
    else {

      # calculate original lengths of seqs for readjustment
      # "$LeftOver" from excised sequences
      if ( !defined $smallestLastField{$Seq1Name}
           || $LastField < $smallestLastField{$Seq1Name} )
      {
        $Seq1Lengths{$Seq1Name}       = $EndAlign + $LeftOver;
        $smallestLastField{$Seq1Name} = $LastField;
        push @Seq1Name, $Seq1Name unless $pushed{$Seq1Name};

        # changed from push @Seq1Name, $Seq1Name if $i == 0 || $Seq1Name ne
        # $pastSeq1Name[0]; because sometimes the first entry gets skipped
        # before creating a $pastSeq1Name[0]
        ++$pushed{$Seq1Name};
      }

      $length{$ID} = $EndAlign - $BeginAlign + 1;

      $ClassName = "Satellite" if $HitName =~ /HSATII|SUBTEL/;

      # join poly A tails to SINE or LINE1 annotation; do the same for
      # simple repeat tails of other SINEs and LINEs? Maybe not.  Also
      # could consider limiting this to diverged simple repeats
      if ( ( $HitName eq '(A)n' || $HitName =~ /^\(.A{3,6}\)/ ) && !$opt_noint )
      {
        my $k = 1;
        while ( $k < 5 ) {
          if (
               $k <= $i
               && (    $pastHitName[ $k - 1 ] =~ /^Alu|^FLAM/
                    && $pastLeftUnaligned[ $k - 1 ] < 32
                    || $pastHitName[ $k - 1 ] =~
                    /^FR?AM$|^L1.*_3end$|^L1.*extended$|^SVA$/
                    && $pastLeftUnaligned[ $k - 1 ] < 26 )
               && $BeginAlign - $pastEndAlign[ $k - 1 ] < 4
               && $RevComp  eq $pastRevComp[ $k - 1 ]
               && $Seq1Name eq $pastSeq1Name[ $k - 1 ]
              )
          {
            if ( $RevComp eq '+' && $pastEndAlign[ $k - 1 ] - $EndAlign < 32 ) {
              my $newend = $EndAlign;
              $length{$ID} = 0;    # should not be counted as insert anymore
              &NameCurrent( $i - $k );
              $ID = $i + 1;
              $id{$ID} = $ID - $k;
              $SW += 1;            # to get this line first in cycle 1
              if ( $EndAlign < $newend ) {
                $Seq2End += $newend - $EndAlign;
                $EndAlign = $newend;
              }
              else {
                $Seq2End += $LeftUnaligned;
              }
              $LeftUnaligned = 0;
              $LeftOver =~ tr/[\(\)]//d;
            }
            elsif (    $RevComp eq 'C'
                    && $BeginAlign - $pastBeginAlign[ $k - 1 ] < 32 )
            {
              $length{$ID} = 0;
              &NameCurrent( $i - $k );
              $ID = $i + 1;
              $id{$ID} = $ID - $k;
              $SW      += 1;                # to get this line first in cycle 1
              $Seq2End += $LeftUnaligned;
              $LeftUnaligned = 0;
              $LeftOver =~ tr/[\(\)]//d;
            }
            $k += 100;
          }
          elsif (
                     $i + $k <= $#sortedHits
                  && $RevComp  eq 'C'
                  && $Seq1Name eq $sortedHits[ $i + $k ]->getSeq1Name()
                  && $sortedHits[ $i + $k ]->getRevComp() eq 'C'
                  && $sortedHits[ $i + $k ]->getSeq1Beg() - $EndAlign < 3
                  && (    $sortedHits[ $i + $k ]->getSeq2Name() =~ /^Alu|^FLAM/
                       && $sortedHits[ $i + $k ]->get3PrimeUnaligned() < 32
                       || $sortedHits[ $i + $k ]->getSeq2Name() =~
                       /^FR?AM$|^L1.*_3end|^L1.*extended/
                       && $sortedHits[ $i + $k ]->get3PrimeUnaligned() < 26 )
              )
          {
            my $newbegin = $BeginAlign;
            $length{$ID} = 0;
            &NameCurrent( $i + $k );
            $ID = $i + 1;
            $id{$ID} = $ID + $k;
            $Seq2End += $BeginAlign - $newbegin;
            $BeginAlign    = $newbegin;
            $LeftUnaligned = 0;
            $LeftOver =~ tr/[\(\)]//d;
            $k += 100;
          }
          $ClassName =~ s/_[no][el][dw](\d{1,2})?$//
              ;    # obtained from NameCurrent sub, which still have this label
          $length{$ID} = $EndAlign - $BeginAlign + 1;    # may have changed
          ++$k;
        }
      }
      if ( $ClassName =~ /Satellite/ ) {
        $HitName =~ s/_$//;

# name_ is the name for consensus units starting halfway of the 'name' consensus unit sequence
        $HitName =~ s/[a-z]$//;

      # lower case letters for varieties that can overlap and are not in repbase
      }

# Adjustment for elements 'spanning' a deleted insertion by 5 bp or less
# this match can cause annotation problems and is almost never real;
# we can raise this number a bit when the masking  is based on the final RM output
# currently discrepancies between annotation and masked DNA is limiting
      if (
           $LastField == 5
        && $i < $#sortedHits
        &&

        # check on $LastField == 5 requirement
        $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
        && $EndAlign > $sortedHits[ $i + 1 ]->getSeq1End()
          )
      {
        my $dif;
        my $z = $i + 1;

        # the following loop takes care of situations like
        # -x------------> or -x<------------- (orientation insignificant
        # -x-x------------>, -xxx------------> etc
        # where x is an cut-out insertion and a dash is 7 bp or less
        while (    $z <= $#sortedHits
                && $Seq1Name eq $sortedHits[ $z ]->getSeq1Name()
                && $BeginAlign >= $sortedHits[ $z ]->getSeq1Beg() - 7
                && $BeginAlign <= $sortedHits[ $z ]->getSeq1Beg()
                && $LastField > $sortedHits[ $z ]->getLastField() )
        {
          $dif += $sortedHits[ $z ]->getSeq1Beg() - $BeginAlign + 1;
          $BeginAlign = $sortedHits[ $z ]->getSeq1End() + 1;
          ++$z;

          # the following takes care of situations like
          # -x------------> or   -x-x------------>  etc ($sequence $i)
          #    ----------->          ------------>   (sequence $z)
          # Seq $z necessarily has a higher SW score than seq $i.
          # It applies the masklevel 90 rule as in the cross_match run after
          # elimination of the insignificant extension (masklevel is sometimes
          # set lower, where it's unlikely that this step have any effect)
          # It also eliminates shorter overlaps by requiring that there is > 20
          # bp between the cut-out element and the overlapped sequence and > 10
          # bp at the other end
          if (    $z <= $#sortedHits
               && $Seq1Name eq $sortedHits[ $z ]->getSeq1Name()
               && $LastField == $sortedHits[ $z ]->getLastField()
               && $EndAlign > $sortedHits[ $z ]->getSeq1Beg() + 20 )
          {
            my $nextoverlapend = $sortedHits[ $z ]->getSeq1End();
            $nextoverlapend = $EndAlign if $EndAlign < $nextoverlapend;
            if (    $BeginAlign >= $sortedHits[ $z ]->getSeq1Beg() - 20
                 && $EndAlign - $sortedHits[ $z ]->getSeq1End() < 10
                 || ( $nextoverlapend - $sortedHits[ $z ]->getSeq1Beg() + 1 ) /
                 ( $EndAlign - $BeginAlign + 1 ) >= 0.9 )
            {
              $id{$ID} = 0;
              next CYCLE0;
            }
          }
        }
        if ( $dif ) {
          if ( $RevComp eq "C" ) {
            $Seq2End -= $dif;
            $LeftUnaligned += $dif;
          }
          else {
            $Seq2Begin += $dif;
          }
        }

        # same for this loop but then for
        # <--------------x- , -------------->xx- etc
        my $enddif = 0;
        $z = 4;
        while (    $i + $z > $#sortedHits
                || $Seq1Name ne $sortedHits[ $i + $z ]->getSeq1Name() )
        {
          --$z;
          last unless $z;
        }
        while ( $z > 0 ) {
          if (    $EndAlign > $sortedHits[ $i + $z ]->getSeq1End()
               && $LastField > $sortedHits[ $i + $z ]->getLastField()
               && $EndAlign <= $sortedHits[ $i + $z ]->getSeq1End() + 7 )
          {
            $enddif +=
                $EndAlign - $sortedHits[ $i + $z ]->getSeq1End() + 1; # +1 for X
            $EndAlign = $sortedHits[ $i + $z ]->getSeq1Beg() - 1;

            # for <-------------x-
            #     <-------------    etc. (see above)
            if (
                    $z
                 && $LastField == $sortedHits[ $i + $z ]->getLastField()
                 && (
                   (
                        $EndAlign <= $sortedHits[ $i + $z ]->getSeq1End() + 20
                     && $BeginAlign >= $sortedHits[ $i + $z ]->getSeq1Beg() - 10
                   )
                   || ( $sortedHits[ $i + $z ]->getSeq1End() -
                        $sortedHits[ $i + $z ]->getSeq1Beg() + 1 ) /
                   ( $EndAlign - $BeginAlign + 1 ) >= 0.9
                 )
                )
            {
              $id{$ID} = 0;
              next CYCLE0;
            }
          }
          --$z;
        }
        if ( $enddif ) {
          if ( $RevComp eq "C" ) {
            $Seq2Begin += $enddif;
          }
          else {
            $Seq2End -= $enddif;
            $LeftUnaligned += $enddif;
          }
        }
        $length{$ID} = $EndAlign - $BeginAlign + 1;    # may have changed

   # And finally, we sometimes have the situation
   # -------------------------> sequence $i
   # ----------> -------------> sequences $i+1 and $i+2 (or more)
   # Meaning that all reported fragments $i+n have a higher SW score than seq $i
   # There can be numerous insertions to complicate matters ...
        my $coveredlength = 0;
        my $lastname;
        my $lastend = 0;
        my $fin     = 0;
        $z = $i + 1;
        while (    $z <= $#sortedHits
                && $Seq1Name eq $sortedHits[ $z ]->getSeq1Name()
                && $LastField >= $sortedHits[ $z ]->getLastField()
                && $EndAlign > $sortedHits[ $z ]->getSeq1Beg() )
        {
          if ( $LastField > $sortedHits[ $z ]->getLastField() ) {
            unless (
              $BeginAlign > $sortedHits[ $z ]->getSeq1Beg()
              ||

              # unless $BeginAlign had been adjusted in previous steps;
              $sortedHits[ $z ]->getSeq1End() <= $lastend
                )
            {

# or the last removed element was inserted in this one
# or, as in the case of L1_extended elements and the following single unmerged match
# represents a subsequence of the last one
              my $subtract = $sortedHits[ $z ]->getSeq1End() -
                  $sortedHits[ $z ]->getSeq1Beg() + 1;
              $length{$ID}   -= $subtract;
              $coveredlength -= $subtract
                  if $sortedHits[ $z ]->getSeq1End() < $fin;

              # these inserts were also included in the covered length
              push( @{ $inserts{$ID} }, $z + 1 );

# that ugly push creates a list of IDs inserted in the current ID
# in this cycle $ID = $i+1, so the ID of line $z is $z+1
# usually no worries about overlapping inserts; L1_extended element exception handled above
            }
            $lastend = $sortedHits[ $z ]->getSeq1End();
          }
          else {
            my $debut = $sortedHits[ $z ]->getSeq1Beg() - 1;
            $debut = $sortedHits[ $z - 1 ]->getSeq1End()
                if $z - 1 > $i && $debut < $sortedHits[ $z - 1 ]->getSeq1End();

            # overlaps of the overlapping sequences. sigh.
            $fin = $EndAlign;
            $fin = $sortedHits[ $z ]->getSeq1End()
                if $fin > $sortedHits[ $z ]->getSeq1End();
            $coveredlength += $fin - $debut;
            $lastname = $sortedHits[ $z ]->getSeq2Name();
          }
          ++$z;
        }
        if ( $coveredlength ) {
          my $suffix = $HitName;
          $suffix =~ s/.*[-_]//;
          if (
                  $length{$ID} - $coveredlength <= 10
               || $length{$ID} - $coveredlength <= 30
               && (    $coveredlength / $length{$ID} >= 0.9
                    || $lastname =~ /$suffix\#/ )
              )
          {    # remember that getSeq2Name looks like hitname#classname
            $id{$ID} = 0;
            next CYCLE0;
          }
        }
      }

      # These steps cause some further discrepancy between masked bases and
      # annotated bases When we mask based on the annotation, we shoul be
      # careful only in the last step that too much truly repetitive DNA
      # doesn't escape masking (so keep the $thislength - $coveredlength
      # cutoff low

      &PrintReady();

      my $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign $LeftOver $RevComp $HitName#$ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $LastField $ID";
      push @imout, $outline;

      print "$outline\n" if $opt_debug;
      &MoveToPast();
    }
  }
  close( OUTRAW ) if ( $opt_u || !$poundformat );
  close( OUTALIGN ) if $opt_a;
  %aligninfo = ();    # not used anymore; hogs memory

  if ( !$poundformat ) {
    rename( "$file.ori.out", "$file.out" );
  }
  else {
    open( OUTFULL, ">$file.out" ) || die "can't create $file.out\n";

    # print header
    if ( $opt_fixed ) {
      if ( $opt_no_id ) {
        print OUTFULL
"   SW    %    %    %   name query   position in query (bp left)   name matching   type of repeat   pos. in repeat (bp left)
 score  div  del  ins  sequence        begin      end   (over)     repeat         class/family      begin     end (unaligned)\n";
      }
      else {
        print OUTFULL
"   SW    %    %    %   name query   position in query (bp left)   name matching   type of repeat   pos. in repeat (bp left)  ID  age
 score  div  del  ins  sequence        begin      end   (over)     repeat         class/family      begin     end (unaligned)\n";
      }
    }

    # sort array by sequence name, classname, and startposition

    my $my   = new ExtractObjects;
    my $lRef = $my->getHits();

    print STDERR "\ncycle 1 ";
    @sortedHits = sort byClassNameThenByBegin ( @{$lRef} );

# March 04 changed the sorting so that the short element starting at the same position
# (and thereore having a better SW score) precedes the longer element
# may have a big impact; check all over
    &ResetPrevious();
    %curid = %id;
    $cycle = 1;

CYCLE1:
    for ( $i = 0 ; $i <= $#sortedHits ; $i++ ) {
      print STDERR "." if ( $i + 1 ) % 1000 == 0;
      &NameCurrent( $i );
      $fusedwithprev = $nextoverlap = 0;

#I may replace all $PctSubst and $ClassName etc. with associated arrays; any problems?
      $curid{$ID} = $id{$ID};
      $div{$ID}   = $PctSubst;
      $class{$ID} = $ClassName;

      if (    $i > 0
           && $EndAlign <= $pastEndAlign[ 0 ]
           && $SW <= $pastSW[ 0 ]
           && $Seq1Name  eq $pastSeq1Name[ 0 ]
           && $ClassName eq $pastClassName[ 0 ]
           && $LastField >= $pastLastField[ 0 ]
           || $sortedHits[ $i + 1 ]
           && $BeginAlign == $sortedHits[ $i + 1 ]->getSeq1Beg()
           && $SW <= $sortedHits[ $i + 1 ]->getSW()
           && $Seq1Name  eq $sortedHits[ $i + 1 ]->getSeq1End()
           && $ClassName eq $sortedHits[ $i + 1 ]->getClassName()
           && $LastField >= $sortedHits[ $i + 1 ]->getLastField() )
      {
        $id{$ID} = 0;
        next CYCLE1;
      }

      #merge long simple repeats which were initially partly spliced out
      # Note that not all satellite entries represent (multiple)
      # units. Some are complex sequences that can contain
      # minisatellites in it; overlapping matches to such
      # subsequences cause 'funny' annotation (in particular,
      # the location of the match in the consensus sequence is off)
      if ( $ClassName =~ /Simple|Satellite/ ) {
        if (    $i < $#sortedHits
             && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
             && $RevComp  eq $sortedHits[ $i + 1 ]->getRevComp()
             && $EndAlign > $sortedHits[ $i + 1 ]->getSeq1End() )
        {
          my $tempname = quotemeta $HitName;
          if ( $sortedHits[ $i + 1 ]->getSeq2Name() =~ /$tempname/ ) {
            $thislength = $Seq2End - $Seq2Begin + 1;
            my $nextlength = $sortedHits[ $i + 1 ]->getSeq2End() -
                $sortedHits[ $i + 1 ]->getSeq2Beg() + 1;
            $SW = $sortedHits[ $i + 1 ]->getSW()
                if $sortedHits[ $i + 1 ]->getSW() > $SW;
            my $Seq2Length = $thislength + $nextlength;
            $PctSubst = (
                $PctSubst * $thislength + $sortedHits[ $i + 1 ]->getPctSubst() *
                    $nextlength ) / $Seq2Length;
            $PctInsert = (
              $PctInsert * $thislength + $sortedHits[ $i + 1 ]->getPctInsert() *
                  $nextlength ) / $Seq2Length;
            $PctDelete = (
              $PctDelete * $thislength + $sortedHits[ $i + 1 ]->getPctDelete() *
                  $nextlength ) / $Seq2Length;
          }
        }
        elsif (
             $i > 0
          && $Seq1Name eq $pastSeq1Name[ 0 ]
          && $HitName  eq $pastHitName[ 0 ]
          && $RevComp  eq $sortedHits[ $i - 1 ]
          ->getRevComp()    # $pastRevComp[0] may be 'compromised'
          && $EndAlign < $pastEndAlign[ 0 ]
            )
        {
          $id{$ID} = 0;     # to be used to see that element has been skipped
          next CYCLE1
              ; # these cut-out elements were included in the last entry in above loop
        }
        if ( $PctSubst + $PctInsert + $PctInsert > 15 ) {
          if ( $HitName =~ /AAAA|\(A\)/ ) {
            if ( $RevComp eq '+' ) {
              $HitName = "A-rich";
            }
            else { $HitName = "T-rich"; }
          }
          elsif ( $HitName =~ /GGGG|\(G\)/ ) {
            if ( $RevComp eq '+' ) {
              $HitName = "G-rich";
            }
            else { $HitName = "C-rich"; }
          }
          if ( $HitName =~ /\([GA]+\)/ ) {
            if (
                 $SW < ( $Seq2End - $Seq2Begin + 1 ) * (
                   9 - $PctSubst * 16 / 100 - ( $PctInsert + $PctDelete ) * 23 /
                       100
                 )
                )
            {
              if ( $RevComp eq '+' ) {
                $HitName = "GA-rich";
              }
              else {
                $HitName = "CT-rich";
              }
            }
            else {
              if ( $RevComp eq '+' ) {
                $HitName = "polypurine";
              }
              else {
                $HitName = "polypyrimidine";
              }
            }
          }
        }
        if ( $HitName =~ /^\(/ ) {
          my $unit = $HitName;
          $unit =~ s/\((\w+)\)n/$1/;
          my $merness = length $unit;
          if ( $RevComp eq "C" ) {
            unless ( $HitName =~ /\(TA\)|\(TTAA\)|\(CG\)|\(CCGG\)/ ) {
              $unit = reverse $unit;
              $unit =~ tr/ACGT/TGCA/;
              $HitName = "($unit)n";
            }
          }
          while ( $Seq2Begin > $merness ) {
            $Seq2Begin -= $merness;
            $Seq2End   -= $merness;
          }
        }
        $RevComp = '+' unless $HitName =~ /HSATII|SUBTEL/;
        if ( $HitName eq 'HSATII' && $RevComp eq "C" ) {
          $HitName = 'HSATIIrev';
          $RevComp = '+';
        }
        $LeftUnaligned = 0;
      }

      #give generic names to too precisely called Alus
      if ( $ClassName =~ /SINE/ ) {
        if (    $ClassName eq "SINE/Alu"
             && $HitName !~ /B1/
             && ( $Seq2End < 176 || $Seq2Begin > 64 ) )
        {
          &preprocessalus;
        }
        elsif ( $HitName eq 'MIR3' ) {
          if ( $Seq2Begin < 16 || $Seq2End > 153 ) {
            $HitName = 'MIRc';
          }
          else {
            $HitName = 'MIR';
          }
        }
      }

      elsif ( $ClassName =~ /LINE/ ) {

        #preprocessing can be done in cycle 0
        # adjust start position LINE1 termini and
        # give generic names to too precisely categorized LINEs
        if ( $ClassName eq "LINE/L1" ) {
          &preprocesslines;
        }
        elsif ( $ClassName eq "LINE/L2" ) {
          if ( $HitName =~ /2[ab]/ ) {
            $Seq2Begin += 2803;
            $Seq2End   += 2803;
            $HitName = "L2";
          }
          else {
            $LeftUnaligned += 337;
          }
        }
        elsif ( $ClassName eq "LINE/CR1" ) {
          if ( $opt_species eq 'gallus' ) {
            if ( $HitName =~ /_3end$/ ) {
              $HitName =~ s/_3end//;
              if ( $HitName eq "CR1-B2" ) {
                $Seq2Begin += 3339;
                $Seq2End   += 3339;
              }
              elsif ( $HitName eq "CR1-C2" ) {
                $Seq2Begin += 3322;
                $Seq2End   += 3322;
              }
              elsif ( $HitName eq "CR1-D2" ) {
                $Seq2Begin += 3457;
                $Seq2End   += 3457;
              }
              elsif ( $HitName =~ /CR1-[FX][012]/ ) {
                $Seq2Begin += 3036;
                $Seq2End   += 3036;
              }
              elsif ( $HitName =~ /CR1-Y/ ) {
                $Seq2Begin += 3301;
                $Seq2End   += 3301;
              }
            }
          }
          if ( $HitName eq L3b ) {
            $Seq2Begin += 4026;
            $Seq2End   += 4026;
          }
        }
      }
      elsif ( $ClassName eq "Low_complexity" ) {
        $RevComp = '+';    # AT-rich and GC rich not strand specific
        $Seq2End       = $Seq2End - $Seq2Begin + 1;
        $Seq2Begin     = 1;
        $LeftUnaligned = 0;
      }

      #handle common internal deletion products of DNA transposons
      elsif ( $ClassName =~ /DNA/ ) {
        &preprocessdnatransp;
      }
      elsif ( $HitName =~ /^MLT2/ )
      {    #  middle region of MLT2 variable in length in subfamilies
        &preprocessltrs;
      }

      if (    $i > 0
           && $Seq1Name  eq $pastSeq1Name[ 0 ]
           && $ClassName eq $pastClassName[ 0 ]
           && $ID - $pastID[ 0 ] < 21
           && $pastID[ 0 ] - $ID < 21 )
      {

        if ( $RevComp eq "C" ) {
          $cycdir = 1;
        }
        else { $cycdir = 2; }

        my $j = 0;
        @QueryOverlap = ();

  # not all matches get same number of $#QueryOverlap; checked on in FuseO.. sub
        while ( $j < 7 && $j <= $#pastID ) {
          $QueryGap[ $j ] = $BeginAlign - $pastEndAlign[ $j ] - 1;
          if ( $EndAlign <= $pastEndAlign[ $j ] )
          {    # contained in previous match (but not an insert)
            $QueryGap[ $j ] = $BeginAlign - $EndAlign -
                1;    # -length of match (inserts are taken out in adjustsubst
          }
          $QueryOverlap[ $j ] = -$QueryGap[ $j ];

     #		    last if $QueryOverlap[$j] > 33;
     # earlier overlaps already combined with the last overlapping match
     # > 33 for occasional accidental overlaps by inserted (but not cut) element
          ++$j;
        }
        &FuseOverlappingSeqs( 1 );

        &AdjustNames( 1 ) unless $fusedwithprev || $opt_noint;
      }

      &PrintReady();

      my $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign $LeftOver $RevComp $HitName#$ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $LastField $ID $id{$ID}";
      push @imout, $outline;

      print "$outline\n" if $opt_debug;
      &MoveToPast();
    }

    undef %sortedHits;
    $my   = new ExtractObjects;
    $lRef = $my->getHits();

    print STDERR "\ncycle 2 ";
    @sortedHits = sort byNameClassThenByBegin ( @{$lRef} );
    &ResetPrevious();
    $cycle = 2;
    for ( $i = 0 ; $i <= $#sortedHits ; $i++ ) {
      print STDERR "." if ( $i + 1 ) % 1000 == 0;
      &NameCurrent( $i );

      if (    $i > 0
           && $SW <= $pastSW[ 0 ]
           && $Seq1Name eq $pastSeq1Name[ 0 ]
           && $BeginAlign >= $pastBeginAlign[ 0 ]
           && $EndAlign <= $pastEndAlign[ 0 ]
           && $ClassName eq $pastClassName[ 0 ]
           && $LastField >= $pastLastField[ 0 ] )
      {
        $id{$ID} = 0;
        next;
      }
      elsif ( $shrink5end{$ID} ) {
        if (    $i > 0
             && $LastField == $pastLastField[ 0 ]
             && $BeginAlign < $pastEndAlign[ 0 ] - 33 )
        {
          $EndAlign  = $pastBeginAlign[ 0 ] - 1;
          $Seq2Begin = $Seq2End + $BeginAlign - $EndAlign;  # assume no gaps ...
        }
      }

      $fusedwithprev = $nextoverlap = $matchedup{$ID} = 0;
      $curid{$ID}    = $id{$ID};
      $div{$ID}      = $PctSubst;
      $class{$ID}    = $ClassName;

      #merge long simple repeats which were initially partly spliced out
      #in this cycle only functions when outside repeat has been renamed
      if ( $ClassName =~ /Simple|Satellite/ ) {
        if (    $i < $#sortedHits
             && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
             && $EndAlign < $sortedHits[ $i + 1 ]->getSeq1End() )
        {
          my $tempname = quotemeta $HitName;
          if ( $sortedHits[ $i + 1 ]->getSeq2Name() =~ /$tempname/ ) {
            $thislength = $Seq2End - $Seq2Begin + 1;
            my $nextlength = $sortedHits[ $i + 1 ]->getSeq2End() -
                $sortedHits[ $i + 1 ]->getSeq2Beg() + 1;
            $SW = $sortedHits[ $i + 1 ]->getSW()
                if $sortedHits[ $i + 1 ]->getSW() > $SW;
            $PctSubst = (
                $PctSubst * $thislength + $sortedHits[ $i + 1 ]->getPctSubst() *
                    $nextlength ) / ( $thislength + $nextlength );
            $PctInsert = (
              $PctInsert * $thislength + $sortedHits[ $i + 1 ]->getPctInsert() *
                  $nextlength ) / ( $thislength + $nextlength );
            $PctDelete = (
              $PctDelete * $thislength + $sortedHits[ $i + 1 ]->getPctDelete() *
                  $nextlength ) / ( $thislength + $nextlength );
            $BeginAlign = $sortedHits[ $i + 1 ]->getSeq1Beg();
            $EndAlign   = $sortedHits[ $i + 1 ]->getSeq1End();
            $LeftOver   = $sortedHits[ $i + 1 ]->getLeftOver();
            $Seq2End    = $thislength + $nextlength;
            $LastField  = 3;
          }
        }
        elsif (    $i > 0
                && $Seq1Name eq $pastSeq1Name[ 0 ]
                && $HitName  eq $pastHitName[ 0 ]
                && $BeginAlign >= $pastBeginAlign[ 0 ]
                && $EndAlign <= $pastEndAlign[ 0 ] )
        {
          $id{$ID} = 0;
          next;
        }
      }

      if (    $i > 0
           && $Seq1Name  eq $pastSeq1Name[ 0 ]
           && $ClassName eq $pastClassName[ 0 ]
           && $ID - $pastID[ 0 ] < 21
           && $pastID[ 0 ] - $ID < 21 )
      {

        if ( $RevComp eq "C" ) {
          $cycdir = 2;
        }
        else {
          $cycdir = 1;
        }
        my $j = 0;
        @QueryOverlap = ();
        while ( $j < 7 && $j <= $#pastID ) {
          $QueryGap[ $j ] = $pastBeginAlign[ $j ] - $EndAlign - 1;

          # if beginalign == pastbeginalign, now situation is fine
          $QueryOverlap[ $j ] = -$QueryGap[ $j ];

          #		    last if $QueryOverlap[$j] > 33;
          ++$j;
        }

        &FuseOverlappingSeqs( 2 );

        &AdjustNames( 2 ) unless $fusedwithprev || $opt_noint;
      }

      &PrintReady();

      unless (    $i > 0
               && $BeginAlign eq $pastBeginAlign[ 0 ]
               && $HitName    eq $pastHitName[ 0 ]
               && $EndAlign <= $pastEndAlign[ 0 ]
               && $Seq1Name eq $pastSeq1Name[ 0 ]
               || $#pastID > 0
               && $BeginAlign eq $pastBeginAlign[ 1 ]
               && $HitName    eq $pastHitName[ 1 ]
               && $EndAlign <= $pastEndAlign[ 1 ]
               && $Seq1Name eq $pastSeq1Name[ 1 ] )
      {

        my $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign $LeftOver $RevComp $HitName#$ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $LastField $ID $id{$ID}";
        push @imout, $outline;

        print "$outline\n" if $opt_debug;
      }

      &MoveToPast();
    }

    undef %sortedHits;
    $my   = new ExtractObjects;
    $lRef = $my->getHits();

    print STDERR "\ncycle 3 ";
    @sortedHits = sort byNameBeginAndEnd ( @{$lRef} );

    &ResetPrevious();
    $cycle = 3;
CYCLE3:
    for ( $i = 0 ; $i <= $#sortedHits ; $i++ ) {
      print STDERR "." if ( $i + 1 ) % 1000 == 0;
      &NameCurrent( $i );

      # skip fragments included in a previous line
      for ( $k = 1 ; $k < 10 ; $k++ ) {
        if ( $i >= $k && $Seq1Name eq $sortedHits[ $i - $k ]->getSeq1Name() ) {
          if (
               $LastField eq $sortedHits[ $i - $k ]->getLastField()
               && (
                    $EndAlign <= $sortedHits[ $i - $k ]->getSeq1End()
                    && (  $Seq2Name eq $sortedHits[ $i - $k ]->getSeq2Name()
                       || $Seq2Name                             =~ /LTR8$/
                       && $sortedHits[ $i - $k ]->getSeq2Name() =~ /Harlequin/ )
                    || (
                        (
                             $EndAlign == $sortedHits[ $i - $k ]->getSeq1End()
                          || $BeginAlign == $sortedHits[ $i - $k ]->getSeq1Beg()
                        )
                        && $sortedHits[ $i - $k ]->getSeq2Name() =~ /$ClassName/
                    )
               )
              )
          {
            next CYCLE3;
          }
          elsif (
                     $LastField == 4
                  && $sortedHits[ $i - $k ]->getLastField() == 5
                  && $Seq2Name eq $sortedHits[ $i - $k ]->getSeq2Name()
                  && (    $EndAlign == $sortedHits[ $i - $k ]->getSeq1End()
                       || $BeginAlign == $sortedHits[ $i - $k ]->getSeq1Beg() )
              )
          {
            next CYCLE3;
          }
        }
        else {
          last;
        }
      }

      # March 2004; moved this block to cycle 3, so that recombined elements
      # with inserts can be joined properly. Do after sub readjusthitname??

      # I have seen insertions in human vs chimp (and chimp vs human) in
      # which the gap in the consensus was up to 175 bp
      # With new ORF2 consensus seqs less chance of false joining and more
      # consistent divergence of fragments, I've reset the allowed gap in the
      # consensus from 33 to a calculated distance based on difference in
      # divergence level, gap between fragments in query sequence. The gap
      # allowed is doubled when the fragments have the same subfamily
      # designation.
      if ( $ClassName =~ /^LINE/ ) {

# special case of (the quite common case of) LINEs integrated after recombination
# this appears as an inversion of part of the element giving a <- -> structure
# sub matchL1frags matches up IDs of fragments and improves subfamily name if possible a
        my ( $j, $matched );
        for ( $n = 0 ; $n <= 5 ; ++$n ) {
          if (
               $i > $n
            && $pastSeq1Name[ $n ]
            &&

# sometimes first entry is skipped and $i > $n but $pastSeq1Name[$n] doesn't exist
               $Seq1Name            eq $pastSeq1Name[ $n ]
            && $pastClassName[ $n ] eq "LINE/L1"
            && $BeginAlign - $pastEndAlign[ $n ] <= 20
            && $RevComp           eq '+'
            && $pastRevComp[ $n ] eq "C"
              )
          {
            $j = $i - 1 - $n;
            my $gap = $BeginAlign - $pastEndAlign[ $n ];
            $gap = 0
                if $gap < 0
                ; #overlaps always indicate false extension; neither bad nor good
            my $gapallowed =
                175 - 20 * abs( $PctSubst - $pastPctSubst[ $n ] ) - 5 * $gap;

# the more different the divergnce and the further apart the fragments, the stricter the requirements
            $gapallowed += 50
                if $HitName eq $pastHitName[ $n ]
                ;    # same subfamily name is a big bonus
            if (
              $Seq2End - $pastSeq2Begin[ $n ] < $gapallowed / 2
              &&     # overlap should be smaller, but ones seen up to 46 bp
              $pastSeq2Begin[ $n ] - $Seq2End < $gapallowed
                )
            {
              if (    &matchL1frags( $sortedHits[ $j ]->getSeq2Name() )
                   || $HitName =~ /^L1.*_3end$/
                   && $Seq2End < 6015
                   && $sortedHits[ $j ]->getSeq2End() -
                   $sortedHits[ $j ]->getSeq2Beg() > 100 )
              {
                $matched = 1;
                last;
              }
            }
          }
          elsif (    $i < $#sortedHits - $n
                  && $sortedHits[ $i + 1 + $n ]->getSeq2Name() =~ /LINE\/L1/
                  && $Seq1Name eq $sortedHits[ $i + 1 + $n ]->getSeq1Name()
                  && $sortedHits[ $i + 1 + $n ]->getSeq1Beg() - $EndAlign <= 20
                  && $RevComp                                 eq "C"
                  && $sortedHits[ $i + 1 + $n ]->getRevComp() eq '+' )
          {
            $j = $i + 1 + $n;
            my $gap = $sortedHits[ $j ]->getSeq1Beg() - $EndAlign;
            $gap = 0 if $gap < 0;
            my $gapallowed =
                175 - 20 * abs( $PctSubst - $sortedHits[ $j ]->getPctSubst() ) -
                5 * $gap;
            $gapallowed += 50
                if $sortedHits[ $j ]->getSeq2Name() =~ /^$HitName\#/;
            if (    $Seq2End - $sortedHits[ $j ]->getSeq2Beg() < $gapallowed / 2
                 && $sortedHits[ $j ]->getSeq2Beg() - $Seq2End < $gapallowed )
            {
              if (    &matchL1frags( $sortedHits[ $j ]->getSeq2Name() )
                   || $HitName =~ /^L1.*_3end$/
                   && $Seq2End < 6015
                   && $sortedHits[ $j ]->getSeq2End() -
                   $sortedHits[ $j ]->getSeq2Beg() > 100 )
              {
                $matched = 1;
                last;
              }
            }
          }
        }
        if ( $matched ) {
          $minned{ $id{ $sortedHits[ $j ]->getID() } } = $minned{ $id{$ID} }
              if defined $minned{ $id{$ID} };
          $id{$ID} = $id{ $sortedHits[ $j ]->getID() };
          $HitName = $sortedHits[ $j ]->getSeq2Name();
        }
      }

      unless ( $opt_noint ) {
        &ReAdjustHitName;

  # unhide elements inserted in older elements by breaking up the older elements
        $j = $i + 1;
        my $beginadjusted = 0;
        my $newSeq2Begin  = $Seq2Begin;
        my $newSeq2End    = $Seq2End;
        while (    $j <= $#sortedHits
                && $sortedHits[ $j ]->getSeq1End() <= $EndAlign
                && $Seq1Name eq $sortedHits[ $j ]->getSeq1Name() )
        {    #
          if (
            $sortedHits[ $j ]->getSeq2Name() =~ $ClassName
            && (    $sortedHits[ $j ]->getSeq1Beg() == $BeginAlign
                 || $sortedHits[ $j ]->getSeq1End() <= $EndAlign )
            && $LastField == $sortedHits[ $j ]->getLastField()
            ||

            # 3' ends of LINE1 bodies cut out, adjusted, but not yet eliminated:
            $sortedHits[ $j ]->getSeq1End() == $EndAlign
            && $sortedHits[ $j ]->getLastField() == 4
            ||

        # i.e. ignore not yet eliminated overlapping matches to the same element
            $sortedHits[ $j ]->getSeq1Beg() < $BeginAlign
              )
          {    # when j has inserted in j-1
            $j++;

# skip immediate flanking inserts, and don't bother to report fragments smaller than 5 bp
          }
          elsif (    $j == $i + 1
                  && $sortedHits[ $j ]->getSeq1Beg() <= $BeginAlign + 5 )
          {
            my $diff = $sortedHits[ $j ]->getSeq1Beg() - $BeginAlign;
            if ( $RevComp eq '+' ) {
              $Seq2Begin += $diff;
            }
            else { $Seq2End -= $diff; }
            $BeginAlign = $sortedHits[ $j ]->getSeq1End() + 1;
            $j++;
          }
          elsif ( $sortedHits[ $j ]->getSeq1End() >= $EndAlign - 5 ) {
            my $diff =
                $EndAlign - $sortedHits[ $j ]->getSeq1End()
                ;    # could do + 1, but penalty for gap == match to X
            if ( $RevComp eq 'C' ) {
              $Seq2Begin += $diff;
            }
            else { $Seq2End -= $diff; }
            $EndAlign = $sortedHits[ $j ]->getSeq1Beg() - 1;
            $j++;    # always last; could do 'last'
          }
          else {
            $newEndAlign   = $sortedHits[ $j ]->getSeq1Beg() - 1;
            $newBeginAlign = $sortedHits[ $j ]->getSeq1End() + 1;

# estimating the seq2 fragment sizes based on the shortest fragment (closest to known point in consensus)
            $firstFragment =
                ( $newEndAlign - $BeginAlign ) + ( $newEndAlign - $BeginAlign )
                * ( $PctDelete - $PctInsert ) / 100;
            $secondFragment = $newSeq2End - $newSeq2Begin + 1 - $firstFragment;
            unless (
              $firstFragment < $secondFragment
              || (
                   $j < $#sortedHits
                && $Seq1Name eq $sortedHits[ $j + 1 ]->getSeq1Name()
                && (
                  $EndAlign > $sortedHits[ $j + 1 ]->getSeq1End()
                  &&    # multiple inserts
                  $newBeginAlign < $sortedHits[ $j + 1 ]->getSeq1End()
                  ||                      # but not insert within insert
                  $j + 1 < $#sortedHits
                  && $Seq1Name eq $sortedHits[ $j + 2 ]->getSeq1Name()
                  && $EndAlign > $sortedHits[ $j + 2 ]->getSeq1End()
                )
              )
                )
            {

# AS fixed March 15; added requirments for the $j+1 and $j+2 entries to refer to the same query sequence
              $secondFragment =
                  ( $EndAlign - $newBeginAlign ) +
                  ( $EndAlign - $newBeginAlign ) * ( $PctDelete - $PctInsert ) /
                  100;
              $firstFragment =
                  $newSeq2End - $newSeq2Begin + 1 - $secondFragment;
            }
            $firstFragment  = sprintf( "%d", $firstFragment );
            $secondFragment = sprintf( "%d", $secondFragment );
            if ( $RevComp eq '+' ) {
              $Seq2BeginPrint     = $newSeq2Begin;
              $Seq2EndPrint       = $newSeq2Begin + $firstFragment;   # estimate
              $LeftUnalignedPrint = "("
                  . ( $sortedHits[ $i ]->getSeq2Len() - $Seq2EndPrint ) . ")";
            }
            else {
              $Seq2BeginPrint =
                  "(" . ( $sortedHits[ $i ]->getSeq2Len() - $newSeq2End ) . ")";
              $Seq2EndPrint       = $newSeq2End;
              $LeftUnalignedPrint = $newSeq2End - $firstFragment;     # estimate
            }

            my $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $newEndAlign $LeftOver $RevComp $HitName#$ClassName $Seq2BeginPrint $Seq2EndPrint $LeftUnalignedPrint $LastField $ID\n";
            push @imout, $outline;

            print "$outline\n" if $opt_debug;

            $beginadjusted = 1;
            $BeginAlign    = $newBeginAlign;

# sometimes 3' end of LINE, Alu severed from rest by A rich simple repeat and contained in following repeat.
            if (    $j < $#sortedHits
                 && $BeginAlign >= $sortedHits[ $j + 1 ]->getSeq1Beg()
                 && $LastField == $sortedHits[ $j + 1 ]->getLastField()
                 && $EndAlign < $sortedHits[ $j + 1 ]->getSeq1End()
                 && $EndAlign - $BeginAlign <= 33 )
            {    # > 33 are all fused
              next CYCLE3;
            }
            if ( $RevComp eq "C" ) {
              $newSeq2End    -= $firstFragment;
              $LeftUnaligned -= $firstFragment;
            }
            else {
              $newSeq2Begin += $firstFragment;
              $LeftUnaligned = $sortedHits[ $i ]->get3PrimeUnaligned();
            }
            $j++;
          }
        }
        if ( $beginadjusted ) {
          if ( $RevComp eq "C" ) {    # Seq2Begin has not been changed
            $Seq2End       = $Seq2Begin + $secondFragment;
            $LeftUnaligned = $sortedHits[ $i ]->getSeq2Len() - $Seq2End;
          }
          else {                      # Seq2End has not been changed
            $Seq2Begin     = $Seq2End - $secondFragment;
            $LeftUnaligned = $sortedHits[ $i ]->get3PrimeUnaligned();
          }
        }
      }

      &PrintReady();

      my $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign $LeftOver $RevComp $HitName#$ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $LastField $ID $id{$ID}";
      push @imout, $outline;

      print "$outline\n" if $opt_debug;

      &MoveToPast();
    }

    undef %sortedHits;
    $my   = new ExtractObjects;
    $lRef = $my->getHits();

    print STDERR "\ncycle 4 ";
    @sortedHits = sort byNameBeginAndEnd ( @{$lRef} );

    &ResetPrevious();
    my $lastid = 0;

    #CYCLE4
    for ( $i = 0 ; $i <= $#sortedHits ; $i++ ) {
      print STDERR "." if ( $i + 1 ) % 1000 == 0;
      &NameCurrent( $i );
      $Overlapped     = "";
      $RealBeginAlign = $BeginAlign;
      my $annotatedlength;

      #indicate overlapping sequences in table
      if (
           (
                $i > 0
             && $Seq1Name eq $pastSeq1Name[ 0 ]
             && $BeginAlign <= $pastEndAlign[ 0 ]
             && $SW < $pastSW[ 0 ]
             && $LastField eq $pastLastField[ 0 ]
           )
           || (    $i < $#sortedHits
                && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
                && $EndAlign >= $sortedHits[ $i + 1 ]->getSeq1Beg()
                && $SW < $sortedHits[ $i + 1 ]->getSW()
                && $LastField eq $sortedHits[ $i + 1 ]->getLastField() )
          )
      {
        $Overlapped = "*";
      }

      if ( $ClassName =~ /^LINE/ ) {

        #rename unresolved LINEs
        $HitName =~ s/_orf2$//;
        $HitName =~ s/(.*)_[35](end)?$/$1/;
        $HitName =~ s/_strong$//;

        # could use latter as a general tool to indicate a diagnostic fragment
      }

      # count tandemly repeated fragments of a repeat as one insert
      # only recognizes constant monomers; croaks on diverged dimers
      if (
        $pastHitName[ 0 ] && $ClassName !~ /^SINE/ &&    # March 2002

        # SINEs are too common and often miss > 10 bp of tail
        # probably safe with LINEs because of variable 5' ends
           $BeginAlign - $pastEndAlign[ 0 ] < 30
        && $HitName  eq $pastHitName[ 0 ]
        && $Seq1Name eq $pastSeq1Name[ 0 ]
        && ( $Seq2Begin > 10 || $LeftUnaligned > 10 )
        && $Seq2Begin - $pastSeq2Begin[ 0 ] < 15
        && $pastSeq2Begin[ 0 ] - $Seq2Begin < 15
        && $Seq2End - $pastSeq2End[ 0 ] < 15
        && $pastSeq2End[ 0 ] - $Seq2End < 15
          )
      {
        $id{$ID} = $id{ $pastID[ 0 ] };
      }
      unless ( $ClassName =~ /Low_complexity|Simple_repeat|Satellite/ ) {

#adjust overlapping sequences when begin or end of one of repeats is probably known
        if (    $RevComp eq '+' && ( $LeftUnaligned >= 4 )
             || ( $RevComp eq "C" && $Seq2Begin >= 5 )
             || ( $ClassName =~ /^L1|^Unknown|Composite/ ) )
        {
          if (    $i < $#sortedHits
               && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
               && $EndAlign >= $sortedHits[ $i + 1 ]->getSeq1Beg()
               && $EndAlign < $sortedHits[ $i + 1 ]->getSeq1End()
               && ( $sortedHits[ $i + 1 ]->getSeq2Name() =~ /LTR|SINE|DNA/ ) )
          {
            if (
                 (
                      $sortedHits[ $i + 1 ]->getRevComp() eq '+'
                   && $sortedHits[ $i + 1 ]->getSeq2Beg() < 5
                 )
                 || (    $sortedHits[ $i + 1 ]->getRevComp() eq "C"
                      && $sortedHits[ $i + 1 ]->get3PrimeUnaligned() < 4
                      && $sortedHits[ $i + 1 ]->getSeq2Name() !~ /SINE/ )
                )
            {
              $overlap = $EndAlign - $sortedHits[ $i + 1 ]->getSeq1Beg() + 1;
              if ( $RevComp eq '+' ) {
                $Seq2End -= $overlap;
                $LeftUnaligned += $overlap;
              }
              else {
                $Seq2Begin += $overlap;
              }
              $EndAlign -= $overlap;
              $Overlapped = "";
            }
          }
        }
        if (    $RevComp eq '+' && ( $Seq2Begin >= 5 )
             || ( $RevComp eq "C" && $LeftUnaligned >= 4 )
             || ( $ClassName =~ /^L1|^Unknown|Composite/ ) )
        {
          if (    $i > 0
               && $Seq1Name eq $pastSeq1Name[ 0 ]
               && $BeginAlign <= $pastEndAlign[ 0 ]
               && $EndAlign > $pastEndAlign[ 0 ] + 25 )
          {
            if ( $pastClassName[ 0 ] =~ /^LTR|^SINE|^DNA/ ) {
              if (
                   (
                        $pastRevComp[ 0 ] eq '+'
                     && $pastLeftUnaligned[ 0 ] < 4
                     && $pastClassName[ 0 ] =~ /^[^S]/
                   )
                   || ( $pastRevComp[ 0 ] eq "C" && $pastSeq2Begin[ 0 ] < 5 )
                  )
              {
                $overlap = $pastEndAlign[ 0 ] - $BeginAlign + 1;
                if ( $RevComp eq '+' ) {
                  $Seq2Begin += $overlap;
                }
                else {
                  $Seq2End -= $overlap;
                  $LeftUnaligned += $overlap;
                }
                $BeginAlign = $pastEndAlign[ 0 ] + 1;
                $Overlapped = "";
              }
            }
          }
        }

   # count fragments of the same interspersed elements as one element for table.
        $shortHitName = $HitName;
        if ( $HitName =~ /^MER\d{2}|^LTR\d{2}|^L1M|^Alu/ ) {
          $shortHitName =~ s/(^\w{5}).*/$1/;
        }
        elsif ( $HitName =~ /^MER\d[A-Z_a-z]|^LTR\d[A-Z_a-z]|ORR1/ ) {
          $shortHitName =~ s/(^\w{4}).*/$1/;
        }
        elsif ( $opt_mammal && $HitName =~ /^L1_/ ) {
          $shortHitName = "L1_";
        }
        else {
          $shortHitName =~ s/(\S+\d)[a-zA-Z]$/$1/;

          #		    $shortHitName =~ s/[a-f]$//; # small letters
          #		    $shortHitName =~ s/^(MT2?)[A-F]$/$1/ if $opt_mus;
        }
        $shortHitName = quotemeta $shortHitName;

        if ( $i > 0 && $Seq1Name eq $pastSeq1Name[ 0 ] ) {
          if (    $BeginAlign <= $pastEndAlign[ 0 ]
               && $EndAlign > $pastEndAlign[ 0 ] )
          {
            $RealBeginAlign = $pastEndAlign[ 0 ] +
                1;    # discounts overlaps in length calculations
            if (
                    $ClassName eq $pastClassName[ 0 ]
                 && $RevComp   eq $pastRevComp[ 0 ]
                 && (    $pastHitName[ 0 ] =~ /^$shortHitName/
                      && $BeginAlign <= $pastEndAlign[ 0 ] - 12
                      || $BeginAlign <= $pastEndAlign[ 0 ] - 33 )
                )
            {

              # latter to eliminate accidental overlaps
              if ( $minned{ $id{$ID} } && $Seq2Begin < $pastSeq2Begin[ 0 ] ) {
                $minned{ $id{ $pastID[ 0 ] } } = $minned{ $id{$ID} };
              }
              my $k = $ID + 1;
              while ( $k < $ID + 10 && defined $id{$k} ) {
                $id{$k} = $id{ $pastID[ 0 ] } if $id{$k} == $id{$ID};
                ++$k;
              }
              $id{$ID} = $id{ $pastID[ 0 ] };
            }
          }
          else {
            $RealBeginAlign = $BeginAlign;
          }

#Seq2Begin and Seq2End have not been adjusted dramatically in this cycle: use of objects okay
          my $j          = 1;
          my $gapallowed = 2500;

          while (
            !$checked{ $id{$ID}
            }            # repeat has not yet been connected with upstream piece
            && $j <= $i
            && $j < 5
            && $Seq1Name eq $sortedHits[ $i - $j ]->getSeq1Name()

            #to include distance limit:
            && $BeginAlign < $sortedHits[ $i - $j ]->getSeq1End() + 10000

# problem with just looking at LastField (should be same or bigger
# than $i-$j+1 lastfield) is that deleted LINEs may be continued upstream of an undeleted intervening element
#			   && $LastField >= $sortedHits[$i-$j+1]->getLastField() ) {
            && (   $sortedHits[ $i - $j + 1 ]->getPctSubst() <= 1.33 * $PctSubst
                || $sortedHits[ $i - $j + 1 ]->getSeq2Name() =~ /^Low|^Simple/ )

            #current repeat can not interrupt other element:
            && (    $i == $#sortedHits
                 || $id{ $sortedHits[ $i - $j ]->getID() } ne
                 $id{ $sortedHits[ $i + 1 ]->getID() } )
              )
          {
            my $consgap;
            if (
                    $sortedHits[ $i - $j ]->getSeq2Name() =~ /$shortHitName/
                 && $RevComp eq $sortedHits[ $i - $j ]->getRevComp()
                 && (    $j > $i - 1
                      || $id{ $sortedHits[ $i - $j + 1 ]->getID() } ne
                      $id{ $sortedHits[ $i - $j - 1 ]->getID() } )
                )
            {
              unless ($ClassName =~ /DNA/
                   && $BeginAlign < $sortedHits[ $i - $j ]->getSeq1End() + 500 )
              {

# March 16 changed $sortedHits[$i-$j+1] to $sortedHits[$i-$j] in following two code lines; typos!
# large deletions common; DNA transposons copies rare; often different names; rarely larger than 2.5 kb anyway
                $gapallowed *= 1.5
                    if $HitName                              =~ /\S{4,}/
                    && $sortedHits[ $i - $j ]->getSeq2Name() =~ /^$HitName\#/;

                #if exact same, pretty unusual, unless name is L1 or L1M
                my $diff = $PctSubst - $sortedHits[ $i - $j ]->getPctSubst();
                $diff = -$diff if $diff < 0;
                $gapallowed *= ( 10 - $diff ) / 10;

# this decreases the allowed gap based on the difference in mismatch level of both fragments;
# the more difference there is the smaller the gap is. If the difference is >=10% there is no gap allowed in between.
# bit forgiving on low divergence; however low divergence suffers from errors in consensus and high has superimposed subs
              }
              $gapallowed *=
                  ( 10 - $j ) /
                  10;    # the more intervening elements, the less likely
              if ( $RevComp eq "C" ) {
                $consgap = $sortedHits[ $i - $j ]->getSeq2Beg() - $Seq2End;
              }
              else {
                $consgap = $Seq2Begin - $sortedHits[ $i - $j ]->getSeq2End();
              }
              if ( $consgap > -33 && $consgap < $gapallowed ) {

                #final ID adjustments:
                if (    $minned{ $id{$ID} }
                     && $Seq2Begin < $sortedHits[ $i - $j ]->getSeq2Beg() )
                {
                  $minned{ $id{ $sortedHits[ $i - $j ]->getID() } } =
                      $minned{ $id{$ID} };
                }

                # repeats previously linked ought to tag along:
                my $k = $ID + 1;
                while ( $k < $ID + 10 && defined $id{$k} ) {
                  $id{$k} = $id{ $sortedHits[ $i - $j ]->getID() }
                      if $id{$k} == $id{$ID};
                  ++$k;
                }
                $id{$ID} = $id{ $sortedHits[ $i - $j ]->getID() };
              }
            }
            ++$j;
          }
        }
        if ( $ClassName =~ /^SINE/ ) {
          $ClassName = "srpRNA" if $HitName eq "7SLRNA";
          $ClassName = "scRNA"  if $HitName eq "BC200" || $HitName =~ /^BC1_/;

#                   $ClassName = "scRNA" if $HitName eq "BC200" && $Seq2End > 100;
          if ( $HitName eq "ID_B1" && $Seq2End < 90 ) {
            $ClassName = "SINE/ID";
            $HitName   = "ID";
          }
        }
      }

      #calculate $Leftover from scratch
      $LeftOver = $Seq1Lengths{$Seq1Name} - $EndAlign;
      $length   = $EndAlign - $RealBeginAlign + 1;

      # get rid of negative LINE1 positions; also readjust MLT2 fragments
      if ( $minned{ $id{$ID} } ) {
        if (    $ClassName eq 'LINE/L1' && !$opt_orf2
             || $HitName =~ /^MLT2\w\d?/ && $HitName =~ /^MLT2B[34]$/ )
        {    # the adjusted pos are right for B3 & 4
          $Seq2Begin += $minned{ $id{$ID} };
          $Seq2End   += $minned{ $id{$ID} };
        }
      }
      elsif ( $HitName =~ /MER33|Charlie5/ && $Seq2Begin < 1 ) {
        $Seq2Begin = 1;
      }

      ## following happens sometimes with overlapping simple repeats:
      if (    $i < $#sortedHits
           && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
           && $EndAlign > $sortedHits[ $i + 1 ]->getSeq1End() )
      {
        $length -= $sortedHits[ $i + 1 ]->getSeq1End() -
            $sortedHits[ $i + 1 ]->getSeq1Beg() + 1;
        $Overlapped = "";
      }

      if ( $ClassName =~ /Simple_repeat|Satellite/ ) {
        $ClassName = "Low_complexity" if $HitName =~ /rich|purine|pyrimidin/;
        if ( $HitName eq 'HSATIIrev' ) {
          $RevComp = 'C';
          $HitName = 'HSATII';
        }
        if ( $HitName =~ /\(CATTC\)n|\(GAATG\)n/ ) {
          my $hitname = quotemeta $HitName;
          if (
               $Seq2End > 200
               || (    $i > 0
                    && $pastHitName[ 0 ] =~ /$hitname|HSATII/
                    && $BeginAlign - $pastEndAlign[ 0 ] < 100
                    && $Seq2End + $pastSeq2End[ 0 ] > 200 )
               || (
                       $i < $#sortedHits
                    && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /$hitname|HSATII/
                    && $sortedHits[ $i + 1 ]->getSeq1Beg() - $EndAlign < 100
                    && (
                        ( $Seq2End + $sortedHits[ $i + 1 ]->getSeq2End() > 200 )
                        || (    $i > 0
                             && $pastHitName[ 0 ] eq $HitName
                             && $Seq2End + $pastSeq2End[ 0 ] +
                             $sortedHits[ $i + 1 ]->getSeq2End() > 200 )
                    )
               )
              )
          {
            $ClassName = "Satellite";
          }
        }
        $HitName .= '/Alpha' if $HitName eq 'ALR';
        $HitName .= '/Beta'  if $HitName eq 'BSR';
        if ( $pastHitName[ 0 ] && $Seq1Name eq $pastSeq1Name[ 0 ] ) {
          if (    $pastHitName[ 0 ] eq $HitName
               && $pastRevComp[ 0 ] eq $RevComp
               && $BeginAlign - $pastEndAlign[ 0 ] < 65 )
          {
            $id{$ID} = $id{ $pastID[ 0 ] };
          }
          if (    $BeginAlign <= $pastEndAlign[ 0 ]
               && $EndAlign > $pastEndAlign[ 0 ] )
          {
            $length -= ( $pastEndAlign[ 0 ] - $BeginAlign + 1 );
          }
        }
        if ( $ClassName =~ /Satellite/ ) {
          $ClassName =~ s/[Cc]entromeric$/centr/;
          $ClassName =~ s/telomeric$/telo/;
          $ClassName =~ s/acromeric$/acro/;
        }
      }
      my $CN = $ClassName;
      $CN =~ s/\?$//;   # I'm counting them with the class, even if I'm not sure
      if ( !defined $count{$CN} ) {
        $count{$CN} = 0;
        $totlength{$CN} = 0 if !defined $totlength{$CN};
      }

      $count{$CN}++ unless $checked{ $id{$ID} };
      $totlength{$CN}  += $length;
      $annotatedlength += $length;

      if ( $CN =~ /SINE/ ) {
        $sinecnt++ unless $checked{ $id{$ID} };
        $sinelength += $length;
        $HitName = 'MIR3' if $HitName eq 'MIRc';
      }
      elsif ( $CN =~ /^LINE/ ) {
        $linecnt++ unless $checked{ $id{$ID} };
        $linelength += $length;
        if ( $CN =~ /\/CR1$|\/L2$|\/Rex-Babar$/ ) {
          $lineCR1cnt++ unless $checked{ $id{$ID} };
          $lineCR1length += $length;
        }
        elsif ( $CN =~ /\/R1$|\/LOA$|\/I$|\/Jockey$/ ) {
          $lineIcnt++ unless $checked{ $id{$ID} };
          $lineIlength += $length;
        }
        elsif ( $CN =~ /\/RTE|\/Bov-B/ ) {
          $lineRTEcnt++ unless $checked{ $id{$ID} };
          $lineRTElength += $length;
        }
        elsif ( $CN =~ /\/NeSL|\/R[24]|\/Dong/ ) {
          $lineR2cnt++ unless $checked{ $id{$ID} };
          $lineR2length += $length;
        }
      }
      elsif ( $CN =~ /^LTR/ ) {
        $ltrcnt++ unless $checked{ $id{$ID} };
        $ltrlength += $length;
        if ( $CN =~ /ERV|MaLR/ ) {
          $ltrERVcnt++ unless $checked{ $id{$ID} };
          $ltrERVlength += $length;
        }
        elsif ( $CN =~ /PAO$|BEL$/i ) {
          $ltrBELcnt++ unless $checked{ $id{$ID} };
          $ltrBELlength += $length;
        }
        elsif ( $CN =~ /DIRS$|Gypsy$/ ) {
          $ltrGYPcnt++ unless $checked{ $id{$ID} };
          $ltrGYPlength += $length;
        }
      }
      elsif ( $CN =~ /^DNA/ ) {
        $dnacnt++ unless $checked{ $id{$ID} };
        $dnalength += $length;
        if ( $CN =~ /\/Mariner|\/Tc[124]$|\/MER2|\/Tigger|\/Pogo|\/Stowaway/ ) {
          $dnaTC1cnt++ unless $checked{ $id{$ID} };
          $dnaTC1length += $length;
        }
        elsif (
              $CN =~ /\/[hH]AT|\/AcHobo|Tam3$|Tol2$|\/Tip100|\/MER1|\/Charlie/ )
        {
          $dnaHATcnt++ unless $checked{ $id{$ID} };
          $dnaHATlength += $length;
        }
        elsif ( $CN =~ /\/T2$|\/PiggyBac/ ) {
          $dnaPIGcnt++ unless $checked{ $id{$ID} };
          $dnaPIGlength += $length;
        }
        elsif ( $CN =~ /Harbing|Tourist/ ) {
          $dnaHcnt++ unless $checked{ $id{$ID} };
          $dnaHlength += $length;
        }
        elsif ( $CN =~ /\/P$|\/Mirage|\/Transib/ ) {
          $dnaPcnt++ unless $checked{ $id{$ID} };
          $dnaPlength += $length;
        }
      }
      elsif ( $CN =~ /^Unknown|^Composite|^Other/ ) {
        $othercnt++ unless $checked{ $id{$ID} };
        $otherlength += $length;
      }
      elsif ( $CN =~ /RNA$/ ) {
        $rnacnt++ unless $checked{ $id{$ID} };
        $rnalength += $length;
      }
      elsif ( $CN =~ /Satel/ ) {
        $satelcnt++ unless $checked{ $id{$ID} };
        $satellength += $length;
      }
      elsif ( $CN =~ /Simple/ ) {
        $simplecnt++ unless $checked{ $id{$ID} };
        $simplelength += $length;
      }
      elsif ( $CN =~ /^Low/ ) {
        $lowcompcnt++ unless $checked{ $id{$ID} };
        $lowcomplength += $length;
      }
      $checked{ $id{$ID} }++;

      # do not print (near) duplicates created  by fusing overlapping matches
      unless (
        (
             $i > 0
          && $Seq1Name eq $pastSeq1Name[ 0 ]
          && $EndAlign <= $pastEndAlign[ 0 ]
          && $SW <= $pastSW[ 0 ]
          && $ClassName eq $pastClassName[ 0 ]
          && $LastField eq $pastLastField[ 0 ]
        )
        || (    $ClassName !~ /Simple/ && $EndAlign - $BeginAlign < 10
             || $EndAlign - $BeginAlign < 5 )
        ||

      #nor low complexity DNA or simple repeats when people don't want to see it
        ( $opt_nolow && $ClassName =~ /Low_complexity|Simple_repeat/ )
          )
      {
        $LeftOverPrint = "(" . $LeftOver . ")";
        &PrintReady();
        if ( $opt_no_id ) {
          $printid = "";
        }
        else {
          if ( $opt_debug ) {
            $printid = $id{$ID};
          }
          else {

    # make the IDs start at 1 and not skip any numbers as suggested by Gustavo
    # I'm ambivalent about it as it makes it harder to trace back the annotation
            if ( $doneid{ $id{$ID} } ) {    # sorry for all the IDs
              $printid = $doneid{ $id{$ID} };
            }
            else {
              ++$lastid;                    # $lastid set to 0 at cycle 4
              $doneid{ $id{$ID} } = $printid = $lastid;
            }
          }
        }
        if ( $opt_fixed ) {
          write OUTFULL;
        }
        else {
          $PctSubst  = sprintf "%4.1f", $PctSubst;
          $PctInsert = sprintf "%4.1f", $PctInsert;
          $PctDelete = sprintf "%4.1f", $PctDelete;
          &Adjustwidths;
          my $outline;
          $lineage{ $id{$ID} } = '' unless $lineage{ $id{$ID} };
          $outline =
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign $LeftOverPrint $RevComp $HitName $ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $printid $lineage{$id{$ID}} $Overlapped";
          push @imout, $outline;
        }

        if ( $opt_xm ) {
          print OUTXM
"$SW $PctSubst $PctInsert $PctDelete $Seq1Name $BeginAlign $EndAlign "
              . "$LeftOverPrint $RevComp $HitName\#$ClassName $Seq2BeginPrint $Seq2End $LeftUnalignedPrint $Overlapped\n";
        }
        if ( $opt_ace ) {
          if ( $RevComp eq "C" ) {
            print OUTACE
"Motif_homol \"$HitName\" \"RepeatMasker\" $PctSubst $BeginAlign $EndAlign - $Seq2End $Seq2Begin\n";
          }
          else {
            print OUTACE
"Motif_homol \"$HitName\" \"RepeatMasker\" $PctSubst $BeginAlign $EndAlign + $Seq2Begin $Seq2End\n";
          }
        }
        if (    $opt_poly
             && $ClassName eq "Simple_repeat"
             && $PctSubst + $PctInsert + $PctDelete < 10 )
        {
          write OUTPOLY;
        }
        if ( $opt_gff ) {
          my $source;
          if ( $HitName =~ /Alu/ ) {
            $source = 'RepeatMasker_SINE';
          }
          else {
            $source = 'RepeatMasker';
          }
          print OUTGFF "$Seq1Name\t$source\tsimilarity\t",
              "$BeginAlign\t$EndAlign\t$PctSubst\t",
              ( $RevComp eq 'C' ? '-' : '+' ), "\t.\t",
              "Target \"Motif:$HitName\" $Seq2Begin $Seq2End\n";
        }
      }
      &MoveToPast();
    }

    unless ( $opt_fixed ) {
      $widthLeftOver += 2;
      my $widthposquery =
          $widthBeginAlign + $widthEndAlign + $widthLeftOver + 2;
      my $widthposrepeat =
          $widthSeq2Begin + $widthSeq2End + $widthLeftUnaligned + 2;
      printf OUTFULL
"%${widthSW}s  %${widthPctSubst}s %${widthPctInsert}s %${widthPctDelete}s  %-${widthSeq1Name}s  %-${widthposquery}s    %-${widthHitName}s %-${widthclass}s %${widthposrepeat}s\n",
          'SW', 'perc', 'perc', 'perc', 'query', 'position in query',
          'matching', 'repeat', 'position in  repeat';
      unless ( $opt_no_id ) {
        printf OUTFULL
"%${widthSW}s  %${widthPctSubst}s %${widthPctInsert}s %${widthPctDelete}s  %-${widthSeq1Name}s  %${widthBeginAlign}s %${widthEndAlign}s %${widthLeftOver}s   %-${widthHitName}s %-${widthclass}s %${widthSeq2Begin}s %${widthSeq2End}s %${widthLeftUnaligned}s %${widthID}s\n\n",
            'score', 'div.', 'del.', 'ins.', 'sequence', 'begin', 'end',
            '(left)', 'repeat', 'class/family', 'begin', 'end', '(left)', 'ID';
      }
      else {
        printf OUTFULL
"%${widthSW}s  %${widthPctSubst}s %${widthPctInsert}s %${widthPctDelete}s  %-${widthSeq1Name}s  %${widthBeginAlign}s %${widthEndAlign}s %${widthLeftOver}s   %-${widthHitName}s %-${widthclass}s %${widthSeq2Begin}s %${widthSeq2End}s %${widthLeftUnaligned}s\n\n",
            'score', 'div.', 'del.', 'ins.', 'sequence', 'begin', 'end',
            '(left)', 'repeat', 'class/family', 'begin', 'end', '(left)';
      }
      foreach $lineinimout ( @imout ) {
        my @fields = split " ", $lineinimout;
        $fields[ 15 ] = "" unless $fields[ 15 ];
        $fields[ 16 ] = "" unless $fields[ 16 ];
        unless ( $opt_no_id ) {
          printf OUTFULL
"%${widthSW}d  %${widthPctSubst}s %${widthPctInsert}s %${widthPctDelete}s  %-${widthSeq1Name}s  %${widthBeginAlign}s %${widthEndAlign}s %${widthLeftOver}s %1s  %-${widthHitName}s %-${widthclass}s %${widthSeq2Begin}s %${widthSeq2End}s %${widthLeftUnaligned}s %${widthID}s %3s %1s\n",
              @fields;
        }
        else {
          $fields[ 14 ] = "" unless $fields[ 14 ];
          printf OUTFULL
"%${widthSW}d  %${widthPctSubst}s %${widthPctInsert}s %${widthPctDelete}s  %-${widthSeq1Name}s  %${widthBeginAlign}s %${widthEndAlign}s %${widthLeftOver}s %1s  %-${widthHitName}s %-${widthclass}s %${widthSeq2Begin}s %${widthSeq2End}s %${widthLeftUnaligned}s %3s %1s\n",
              @fields;
        }
      }
    }

    $totallength =
        $sinelength + $linelength + $ltrlength + $dnalength + $otherlength;
    $opt_species =~
        s/^__(\S+)$/$1/;    # for the orders (rodent, artiodactyl, carnivore)
    $opt_species = "\u$opt_species";    # capitalizes
    $opt_species =~ s/(\S+)__\w+$/$1/;  # deletes the __order suffix

    #sgot to be a simpler way than those three lines to capitalize a word.
    if ( $opt_primate ) {
      open( humanPERCENTTABLE, ">$file.tbl" ) || die "can't create $file.tbl\n";
      write humanPERCENTTABLE;
      close humanPERCENTTABLE;

#when using on multiple .cats would not close until next file is done; just takes too long...
    }
    elsif ( $opt_mus ) {
      open( mousePERCENTTABLE, ">$file.tbl" ) || die "can't create $file.tbl\n";
      write mousePERCENTTABLE;
      close mousePERCENTTABLE;
    }
    elsif ( $opt_mammal ) {
      open( cowPERCENTTABLE, ">$file.tbl" ) || die "can't create $file.tbl\n";
      write cowPERCENTTABLE;
      close cowPERCENTTABLE;
    }
    else {
      local $queryorigin;
      if ( $opt_species ) {
        $queryorigin = "The query species was assumed to be \"$opt_species\".";
      }
      elsif ( $opt_lib ) {
        $opt_lib =~ s/.*(\/.*?$)/\.\.\.$1/
            ;    # is that ugly or what? full path name too long
        $queryorigin = "The query was compared to sequences in \"$opt_lib\".";
      }
      open( genPERCENTTABLE, ">$file.tbl" ) || die "can't create $file.tbl\n";
      write genPERCENTTABLE;
      close genPERCENTTABLE;
    }
  }
  close OUTFULL;
  close OUTXM   if $opt_xm;
  close OUTACE  if $opt_ace;
  close OUTGFF  if $opt_gff;
  close OUTPOLY if $opt_poly;
  print STDERR "\ndone\n";
}

################################################################################################
##subroutines

##sorting subroutines

sub byNameThenByBegin {
  ( $a->getSeq1Name() ) cmp( $b->getSeq1Name() )
      || ( $a->getSeq1Beg() ) <=> ( $b->getSeq1Beg() )
      || ( $b->getSeq1End() ) <=> ( $a->getSeq1End() );
### note: takes the longer sequence starting at the same position first
}

sub byClassNameThenByBegin {
  my ( $aSeqName, $aClassName ) = $a->getSeq2Name() =~ /(.*)#(.*)/;
  my ( $bSeqName, $bClassName ) = $b->getSeq2Name() =~ /(.*)#(.*)/;
  ( $a->getSeq1Name() ) cmp( $b->getSeq1Name() )
      || ( $aClassName ) cmp( $bClassName )
      || ( $a->getSeq1Beg() ) <=> ( $b->getSeq1Beg() )
      || ( $a->getSeq1End() ) <=> ( $b->getSeq1End() )
      || ( $b->getSW() ) <=> ( $a->getSW() );
}

sub byNameClassThenByBegin {
  my ( $cSeqName, $cClassName ) = $a->getSeq2Name() =~ /(.*)#(.*)/;
  my ( $dSeqName, $dClassName ) = $b->getSeq2Name() =~ /(.*)#(.*)/;
  ( $a->getSeq1Name() ) cmp( $b->getSeq1Name() )
      || ( $cClassName ) cmp( $dClassName )
      || ( $b->getSeq1Beg() ) <=> ( $a->getSeq1Beg() )
      || ( $b->getSeq1End() ) <=> ( $a->getSeq1End() )
      || ( $b->getSW() ) <=> ( $a->getSW() );
}

sub byNameBeginAndEnd {
  ( $a->getSeq1Name() ) cmp( $b->getSeq1Name() )
      || ( $a->getSeq1Beg() ) <=> ( $b->getSeq1Beg() )
      || ( $b->getSeq1End() ) <=> ( $a->getSeq1End() )
      || ( $b->getSW() ) <=>      ( $a->getSW() );
}

sub checkformultiplespeciesoptions {

  # quits if more than one species chosen
  # sets $opt_species to 'homo' if none is chosen
  # unifies nomenclature
  my $count = 0;

  if ( $opt_arabidopsis ) {
    $opt_species = "arabidopsis";
  }
  elsif ( $opt_cat ) {
    $opt_species = "felis";
  }
  elsif ( $opt_chicken ) {
    $opt_species = "gallus";
  }
  elsif ( $opt_cow ) {
    $opt_species = "bos";
  }
  elsif ( $opt_danio ) {
    $opt_species = "danio";
  }
  elsif ( $opt_dog ) {
    $opt_species = "canis";
  }
  elsif ( $opt_drosophila ) {
    $opt_species = "drosophila";
  }
  elsif ( $opt_elegans ) {
    $opt_species = "caenorhabditis";
  }
  elsif ( $opt_fugu ) {
    $opt_species = "fugu";
  }
  elsif ( $opt_maize ) {
    $opt_species = "zea";
  }
  elsif ( $opt_mus ) {
    $opt_species = "mus";
  }
  elsif ( $opt_pig ) {
    $opt_species = "sus";
  }
  elsif ( $opt_rat ) {
    $opt_species = "rattus";
  }
  elsif ( $opt_rice ) {
    $opt_species = "oryza";
  }
  elsif ( $opt_wheat ) {
    $opt_species = "triticum";
  }

  # some lingering generalized species options:
  ++$count if $opt_artiodactyl;
  ++$count if $opt_carnivore;
  ++$count if $opt_mammal;
  ++$count if $opt_rod;
  if ( $opt_species ) {
    if ( $opt_species =~ /^__/ )
    { # opt_rod, _artio, and _car get inherited like __rodent etc from repeatmasker
      if    ( $opt_species eq "__rodent" )      { $opt_rod         = 1; }
      elsif ( $opt_species eq "__artiodactyl" ) { $opt_artiodactyl = 1; }
      elsif ( $opt_species eq "__carnivore" )   { $opt_carnivore   = 1; }
    }
    elsif ( $opt_species eq 'mammal' ) {
      $opt_mammal = 1;
    }
    else {
      $opt_species = &unifyspecies( $opt_species );
      my $spec = $opt_species;
      $spec =~ s/__\w+$//;
      %okspecies =
          qw(homo 1 mus 1 rattus 1 felis 1 canis 1 bos 1 sus 1 gallus 1 fugu 1 danio 1 xenopus 1 cionaint 1 cionasav 1 drosophila 1 anopheles 1 elegans 1 diatom 1 arabidopsis 1 oryza 1 zea 1 triticum 1);
      die
"RepeatMasker does not (yet) have a function for the species \"$opt_species\".
Currently the -species option can only be used with (case insensitive)
human, mouse, rat, cat, dog, cow, pig, chicken, fugu, danio,
drosophila, anopheles, caenorhabditis,
arabidopsis, rice, wheat, and maize.\n" unless $okspecies{$spec} || -s $opt_lib;
    }
    ++$count;
  }

  die
"You can choose only one species option (including -species and -lib) at the time.\n"
      if $count > 1;
  unless ( $count || $opt_lib ) {
    $opt_species = "homo";
    $opt_primate = 1;
  }
}

sub unifyspecies {
  my $spec = shift;
  $spec =~ tr/A-Z/a-z/;
  if ( $spec eq "human" ) {
    $spec = "homo";
  }
  elsif ( $spec eq "mouse" ) {
    $spec = "mus";
  }
  elsif ( $spec eq "rat" ) {
    $spec = "rattus";
  }
  elsif ( $spec eq "cat" ) {
    $spec = "felis";
  }
  elsif ( $spec eq "dog" ) {
    $spec = "canis";
  }
  elsif ( $spec eq "cow" ) {
    $spec = "bos";
  }
  elsif ( $spec eq "pig" ) {
    $spec = "sus";
  }
  elsif ( $spec eq "chicken" ) {
    $spec = "gallus";
  }
  elsif ( $spec eq "pufferfish" || $spec eq "takifugu" ) {
    $spec = "fugu";
  }
  elsif ( $spec eq "zebrafish" ) {
    $spec = "danio";
  }
  elsif ( $spec eq "fruitfly" ) {
    $spec = "drosophila";
  }
  elsif ( $spec eq "worm" || $spec eq "caenorhabditis" ) {
    $spec = "elegans";
  }
  elsif ( $spec eq "mustard" ) {
    $spec = "arabidopsis";
  }
  elsif ( $spec eq "rice" ) {
    $spec = "oryza";
  }
  elsif ( $spec eq "corn" || $spec eq "maize" ) {
    $spec = "zea";
  }
  elsif ( $spec eq "wheat" ) {
    $spec = "triticum";
  }
  if ( $spec =~ /^mus$|^rattus$/ || $opt_rod ) {
    $spec .= "__rodent";
  }
  elsif ( $spec =~ /^felis$|^canis$/ || $opt_carnivore ) {
    $spec .= "__carnivore";
  }
  elsif ( $spec =~ /^sus$|^bovis$/ || $opt_artiodactyl ) {
    $spec .= "__artiodactyl";
  }
  return $spec;
}

# zero count and totlength for each type reported in summary table
sub ZeroCounts {
  %count = %totlength = %doneid = ();
  ## the following need to be defined from the .tbl format: not all sequence contain items listed in there
  foreach $type (
                  "SINE/Alu",      "SINE/MIR",
                  "SINE/B2",       "SINE/B4",
                  "SINE/ID",       "SINE/BovA",
                  "SINE/BovD",     "LINE/L1",
                  "LINE/L2",       "LINE/CR1",
                  "LINE/BovB",     "LINE/CRE",
                  "LINE/Penelope", "LTR/ERVL",
                  "LTR/ERVK",      "LTR/ERV1",
                  "LTR/MaLR",      "LTR/PAO",
                  "LTR/Gypsy",     "LTR/Copia",
                  "DNA/MER1_type", "DNA/MER2_type",
                  "DNA/Mariner",   "DNA/AcHobo",
                  "DNA/Tc2",       "DNA/Tc1",
                  "DNA/Pogo",      "DNA/T2_type",
                  "DNA/hAT",       "DNA/MuDR",
                  "DNA/En-Spm",    "DNA/Harbinger",
                  "RC/Helicop"
      )
  {
    $count{$type} = $totlength{$type} = 0;
  }
  %id = %curid = %div = %class = %length = %inserts = %checked = %minned =
      %shrink5end = %matchedup = ();
  %Seq1Lengths = %smallestLastField = %ltrscore = %pushed = ();
  @Seq1Name      = ();
  $seq_cnt       = $totalSeqLen = 0;
  $maskedpercent = $maskedlength = 0;
  $sinecnt       = $sinelength = 0;
  $linecnt       = $linelength = 0;
  $lineCR1cnt    = $lineCR1length = 0;
  $lineIcnt      = $lineIlength = 0;
  $lineR2cnt     = $lineR2length = 0;
  $lineRTEcnt    = $lineRTElength = 0;
  $ltrcnt        = $ltrlength = 0;
  $ltrERVcnt     = $ltrERVlength = 0;
  $ltrBELcnt     = $ltrBELlength = 0;
  $ltrGYPcnt     = $ltrGYPlength = 0;
  $dnacnt        = $dnalength = 0;
  $dnaHATcnt     = $dnaHATlength = 0;
  $dnaTC1cnt     = $dnaTC1length = 0;
  $dnaPIGcnt     = $dnaPIGlength = 0;
  $dnaHcnt       = $dnaHlength = 0;
  $dnaPcnt       = $dnaPlength = 0;
  $othercnt      = $otherlength = 0;
  $rnacnt        = $rnalength = 0;
  $satelcnt      = $satellength = 0;
  $simplecnt     = $simplelength = 0;
  $lowcompcnt    = $lowcomplength = 0;
}

sub NameCurrent {
  my $i = shift;
  $SW         = $sortedHits[ $i ]->getSW();
  $PctSubst   = $sortedHits[ $i ]->getPctSubst();
  $PctInsert  = $sortedHits[ $i ]->getPctInsert();
  $PctDelete  = $sortedHits[ $i ]->getPctDelete();
  $Seq1Name   = $sortedHits[ $i ]->getSeq1Name();
  $BeginAlign = $sortedHits[ $i ]->getSeq1Beg();
  $EndAlign   = $sortedHits[ $i ]->getSeq1End();
  $LeftOver   = $sortedHits[ $i ]->getLeftOver();
  $RevComp    = $sortedHits[ $i ]->getRevComp();
  $Seq2Name   = $sortedHits[ $i ]->getSeq2Name();
  ( $HitName, $ClassName ) = split( /\#/, $Seq2Name );
  $Seq2Begin     = $sortedHits[ $i ]->getSeq2Beg();
  $Seq2End       = $sortedHits[ $i ]->getSeq2End();
  $LeftUnaligned = $sortedHits[ $i ]->get3PrimeUnaligned();
  $LastField     = $sortedHits[ $i ]->getLastField();
  $ID            = $sortedHits[ $i ]->getID();
}

sub ResetPrevious {
  @imout              = ();
  @QueryGap           = ();
  @QueryOverlap       = ();
  @pastBeginAlign     = ();
  @pastClassName      = ();
  @pastEndAlign       = ();
  @pastHitName        = ();
  @pastID             = ();
  @pastLastField      = ();
  @pastLeftOver       = ();
  @pastLeftUnaligned  = ();
  @pastPctDelete      = ();
  @pastPctInsert      = ();
  @pastPctSubst       = ();
  @pastRevComp        = ();
  @pastSeq1Name       = ();
  @pastSeq2Begin      = ();
  @pastSeq2End        = ();
  @pastSW             = ();
  $LeftOverPrint      = 0;
  $LeftUnalignedPrint = 0;
  $Seq2BeginPrint     = 0;
}

## splices poly A tails out of the inserts array when they are found
## ('too late') to be attached to an Alu or LINE1;
## also adds the length of the poly A tail to those elements
sub CheckinInsertsArray {
  my $number      = shift;
  my @insertarray = @{ $inserts{$number} };
  for ( my $n = 0 ; $n <= $#insertarray ; ++$n ) {
    if ( $insertarray[ $n ] == $i + 1 ) {

      # given $ID is $i+1, this array contains IDs
      splice( @{ $inserts{$number} }, $n, 1 );
      $length{$number} += $EndAlign - $BeginAlign + 1;
    }
  }
}

##preprocessing subroutines
## any changes here effect the fuseoverlapping subroutine a.o., keep track!
sub preprocesslines {
  if ( $opt_mus && $HitName !~ /^L1[MP][\dABCDE]/ ) {
    if ( $HitName =~ /_3end$/ ) {
      $Seq2Begin += 5586;
      $Seq2End   += 5586;
      if ( $HitName =~ /L[xX]$/ ) {
        $Seq2Begin += 330 if $Seq2Begin >= 6026;
        $Seq2End   += 330 if $Seq2End >= 6029;
      }
    }
    elsif ( $HitName =~ /_5end$/ ) {
      if ( $HitName eq "L1Md_A_5end" ) {

# L1Md-A is taken as the standard for position
# this choice doesn't really matter as the positions are adjusted again at the end
        $LeftUnaligned += 5380;
      }
      elsif ( $HitName eq L1Md_F_5end ) {
        &ChangePos( -97, 5380 );
      }
      elsif ( $HitName eq L1Md_Gf_5end ) {
        &ChangePos( 3, 5380 );
      }
      elsif ( $HitName eq L1VL1_5end ) {    #@mus
        &ChangePos( -216, 5294 );           # L1_Mm/L1_Mus3_3end
      }
      elsif ( $HitName eq L1VL2_5end ) {    #@mus
        &ChangePos( -299, 5290 );           #L1_Mur/L1_Mus4_3end
      }
      elsif ( $HitName eq L1VL4_5end ) {    #@mur
        &ChangePos( -355, 5313 );           # L1_Mur/Lx
      }
      elsif ( $HitName eq L1VL4a_5end ) {    #@rat
        &ChangePos( -356, 5309 );            #L1_Mur/L1_Rat4
      }
      elsif ( $HitName eq L1_RN_5end ) {     #@rat
        &ChangePos( 362, 5292 );             #L1_Rn/L1_Rn
      }
      elsif ( $HitName eq L1_Mur1_5end ) {    #@mur
        &ChangePos( -2, 5640 );               #L1_Mur/Lx3A
      }
      elsif ( $HitName eq L1_Mur2_5end ) {    #@mur
        &ChangePos( -374, 5742 );             #L1_Mur2/Lx4A
      }
      elsif ( $HitName eq L1_Mur3_5end ) {    #@mur
        &ChangePos( -16, 6384 );              #L1_Mur3/Lx7
      }
      elsif ( $HitName eq L1_Rod_5end ) {     #@rod
        &ChangePos( -436, 6252 );             #L1_Rod/Lx9
      }
      elsif ( $HitName =~ /RNHAL1/ ) {
        &ChangePos( 167, 2313 );
      }
      elsif ( $HitName =~ /MusHAL1/ ) {
        &ChangePos( -561, 2570 );
      }
    }
    elsif ( $HitName eq 'L1_Cric' ) {
      $Seq2Begin += 6425;
      $Seq2End   += 6425;
    }
    elsif ( $HitName =~ /^L1_|extended$|^RNHAL1|^MusHAL1/ ) {
      $Seq2Begin += 1202;
      $Seq2End   += 1202;
      $HitName =~ s/extended$//;
      if ( $HitName =~ /HAL1/ ) {
        if (    $HitName eq 'MusHAL1' && $Seq2End > 3640
             || $HitName eq 'RNHAL1' && $Seq2End > 2430 )
        {
          $HitName .= "_strong";
        }
      }
    }
  }
  elsif ( $opt_mammal && $HitName !~ /^L1[MP][\dABCDE]/ )
  {    # all adjusted to L1_Canis (longest)
    if ( $HitName =~ /_3end$/ ) {
      if ( $HitName =~ /L1_Cf|L1_Canid/ ) {
        $Seq2Begin += 5600;
        $Seq2End   += 5600;
      }
      elsif ( $HitName =~ /L1_Fc|L1_Felid/ ) {
        $Seq2Begin += 5528;
        $Seq2End   += 5528;
      }
    }
    elsif ( $HitName eq "L1_Canid" ) {
      $Seq2Begin += 3107;
      $Seq2End   += 3107;
    }
    elsif ( $HitName eq "L1_Carni" ) {
      $Seq2Begin += 3716;
      $Seq2End   += 3716;
    }
    elsif ( $HitName eq "L1_Fc" ) {
      $Seq2Begin += 244;
      $Seq2End   += 244;
    }
  }
  elsif ( $HitName =~ /^L1.*_3end$/ && $HitName !~ /5end|orf2|extended/ ) {
    $Seq2Begin += 5253;
    $Seq2End   += 5253;
    if ( $HitName eq "L1MC5_3end" ) {
      $Seq2Begin += 1357;
      $Seq2End   += 1357;
    }
    if ( $Seq2End < 5430 ) {
      if ( $HitName =~ /L1M/ ) {
        $HitName = "L1M";
      }
      elsif ( $opt_primate ) {
        $HitName = "L1P";
      }
    }
    elsif ( $Seq2End < 5825 || $Seq2End + $SW < 6165 ) {
      if ( $HitName =~ /L1H|PA[23]_3end/ ) {
        $HitName = "L1P1";
      }
      elsif ( $HitName =~ /PA[4-6]_3end/ ) {
        $HitName = "L1P2";
      }
      elsif ( $HitName =~ /PA[7-9]_3end/ ) {
        $HitName = "L1P3";
      }
      elsif ( $HitName =~ /PA1[0-7]_3end/ ) {
        $HitName = "L1P4";
      }
      elsif ( $HitName =~ /L1PB/ ) {
        $HitName = "L1P5";
      }
      elsif ( $HitName =~ /MA[1-4]A?_3end/ ) {
        $HitName = "L1M1";
      }
      elsif ( $HitName =~ /MA[5-9]A?_3end/ ) {
        $HitName = "L1M2";
      }
      elsif ( $HitName =~ /MA10|MB[1-4]/ ) {
        $HitName = "L1M3";
      }
      elsif ( $HitName =~ /MB[5-8]/ ) {
        $HitName = "L1M4";
      }
      elsif ( $HitName =~ /M[CD]/ ) {
        $HitName =~ s/(L1M[CD]).*/$1/;
      }
      elsif ( $HitName =~ /ME/ ) {
        $HitName = "L1M5";
      }
    }
    elsif ( $HitName eq "L1MA10_3end" && $LeftUnaligned >= 145 ) {
      $HitName = "L1MB1_3end";
      $LeftUnaligned -= 145;
    }
  }
  elsif ( $HitName eq L1 ) {
    $LeftUnaligned += 743;
  }
  elsif ( $HitName =~ /_orf2/ ) {
    $Seq2Begin     += 2109;
    $Seq2End       += 2109;
    $LeftUnaligned += 743;
  }
  elsif ( $HitName =~ /extended$/ ) {
    $Seq2Begin += 2109;
    $Seq2End   += 2109;
    $HitName =~ s/extended$//;
  }
  elsif ( $HitName =~ /5end$/ ) {

    # LINE subfamilies have widely variable length 5' ends. To be able to
    # merge closely related LINE subfamilies, the positions need to be
    # adjusted to a standard. The ORF2 is basically of identical length
    # between all known subfamilies, so the start of ORF2 is probably the
    # best place to match the positions of the 5' end consensus
    # sequences. I've taken L1PA2 as a standard for L1, where ORF2 starts
    # at 2110. Many 5' end consensus sequences extend to overlap 150 bp
    # with the ORF2, but many others only describe sequences further 5' in
    # the element, usually because another subfamily has a very closely
    # matching sequence over ORF1. It may be a good idea to eventually
    # change the set of consensus sequences from the current
    # "5'end-ORF2-3'UTR" set up to "5'end-ORF2-3'UTR".
    # The "left over in the consensus sequence" number (now reflecting how
    # far the 5' end consensus extends) is adjusted to reflect what would
    # be left in a full element (add 3294 for ORF2 + length best matching
    # 3' end consensus - 2x 150 bp for overlaps)
    # When making adjustments dependent on position in consensus with the
    # subroutine ChangePos begin-limit of doing so should be >= or <
    # end-limit when the position number is decreased or increased, resp.
    # L1PA4 ORF2 start 2110; L1 ORF2 length 3294 bp
    if ( $HitName eq 'L1HS_5end' || $HitName eq 'L1Pt_5end' ) {
      &ChangePos( -123, 3896 );
    }
    elsif ( $HitName =~ /^L1P/ ) {
      if ( $HitName eq 'L1P1_5end' ) {
        &ChangePos( 0, 3896 );
      }
      elsif ( $HitName =~ /L1P3b?_5end/ ) {
        &ChangePos( 315, 4734 );
      }
      elsif ( $HitName eq L1P3c_5end ) {
        &ChangePos( 1438, 4509 );
      }
      elsif ( $HitName eq L1P4a_5end ) {    # L1PA16 913 bp
        &ChangePos( 337, 3907 );
      }
      elsif ( $HitName eq L1P4b_5end ) {    # adj to L1P4a_5end
        &ChangePos( 1168, 5551 );
      }
      elsif ( $HitName eq L1P4c_5end ) {    # adj to L1P4a_5end
        &ChangePos( 468, 5051 );
      }
      elsif ( $HitName eq L1P4d_5end ) {    # adj to L1P4a_5end
        &ChangePos( 769, 4900 );
      }
      elsif ( $HitName eq L1P4e_5end ) {    # adj to L1P4a_5end
        &ChangePos( 125, 4900 );
      }
      elsif ( $HitName eq L1PA10_5end ) {    # L1PA10 915 bp
        &ChangePos( 185, 3909 );
      }
      elsif ( $HitName eq L1PA13_5end ) {
        &ChangePos( 651, 4509 );
      }
      elsif ( $HitName eq L1PA14_5end ) {
        &ChangePos( 424, 4509 );
      }
      elsif ( $HitName eq "L1PA15-16_5end" ) {
        &ChangePos( 703, 3891 );
      }
      elsif ( $HitName eq "L1PA17_5end" ) {
        &ChangePos( 427, 5139 );
      }
      elsif ( $HitName eq L1PBa_5end ) {
        &ChangePos( 716, 3892 );
      }
      elsif ( $HitName eq L1PBa1_5end ) {
        &ChangePos( 466, 5020 );
      }
      elsif ( $HitName eq L1PBb_5end ) {
        &ChangePos( 57, 5146 );
      }
    }
    elsif ( $HitName eq L1M1_5end ) {
      &ChangePos( 1419, 3890 );
    }
    elsif ( $HitName =~ /L1M2/ ) {
      if ( $HitName eq L1M2_5end ) {
        &ChangePos( 702, 3945 );
      }
      elsif ( $HitName eq L1M2a_5end ) {
        &ChangePos( 1021, 4935 );
      }
      elsif ( $HitName eq L1M2a1_5end ) {
        &ChangePos( 969, 5274 );
      }
      elsif ( $HitName eq L1M2b_5end ) {
        &ChangePos( 1062, 5179 );
      }
      elsif ( $HitName eq L1M2c_5end ) {
        &ChangePos( 642, 4455 );
      }
    }
    elsif ( $HitName =~ /L1M3/ ) {
      if ( $HitName eq L1M3a_5end ) {
        &ChangePos( -112, 4780 );
      }
      elsif ( $HitName eq L1M3b_5end ) {
        &ChangePos( 204, 4516 );
      }
      elsif ( $HitName eq L1M3c_5end ) {
        &ChangePos( 64, 4516 );
      }
      elsif ( $HitName eq L1M3d_5end ) {
        &ChangePos( -176, 4516 );
      }
      elsif ( $HitName eq L1M3de_5end ) {
        &ChangePos( 586, 4516 );
      }
      elsif ( $HitName eq L1M3e_5end ) {
        &ChangePos( 960, 4917 );
      }
      elsif ( $HitName eq L1M3f_5end ) {
        &ChangePos( 182, 4065 );
      }
    }
    elsif ( $HitName eq L1M4_5end ) {
      &ChangePos( 498, 4831 );
    }
    elsif ( $HitName eq L1MB4_5end ) {
      &ChangePos( 601, 4812 );
    }
    elsif ( $HitName eq L1M4b_5end ) {
      &ChangePos( 860, 3630 );
    }
    elsif ( $HitName eq L1M4c_5end ) {
      &ChangePos( 236, 3884 );
    }
    elsif ( $HitName eq L1MCa_5end ) {    # L1MC1 3end 1088 bp
      &ChangePos( 175, 4074 );
    }
    elsif ( $HitName eq L1MCb_5end ) {
      &ChangePos( 418, 4848 );
    }
    elsif ( $HitName eq L1MCc_5end ) {
      &ChangePos( 795, 4887 );
    }
    elsif ( $HitName eq L1MDa_5end ) {    # L1MD1 3end 989 bp
      &ChangePos( 391, 3983 );
    }
    elsif ( $HitName eq L1MDb_5end ) {
      &ChangePos( 260, 4987 );
    }
    elsif ( $HitName eq L1MD2_5end ) {
      &ChangePos( 398, 5478 );
    }
    elsif ( $HitName =~ /L1ME[ab]_5end/ ) {
      &ChangePos( -66, 4981 );
    }
    elsif ( $HitName eq L1MEc_5end ) {
      &ChangePos( 73, 3873 );
    }
    elsif ( $HitName eq L1MEe_5end ) {
      &ChangePos( -1312, 3690 );
    }
    elsif ( $HitName eq L1MEd_5end ) {
      &ChangePos( -17, 4862 );
    }
    elsif ( $HitName eq L1MC4_5end ) {
      &ChangePos( 68, 3660 );
      $HitName = L1M5 if $Seq2Begin >= 2110;
    }
  }
}

sub preprocessalus {
  if ( $Seq2End - $Seq2Begin < 50 && $SW < 250 ) {
    $HitName = "Alu";
  }
  $LeftUnaligned += 169 if $HitName =~ /FLAM/;    # adjust to AluJ
  if ( $Seq2End < 153 ) {
    $HitName = "AluR_5" if $HitName =~ /AluS[xq]/;
    $HitName =~ s/(AluY\w)\d/$1/;
    if ( $HitName eq "7SLRNA" && $Seq2End < 80 ) {
      $HitName = "FLAM_A";
      $LeftUnaligned -= 19;    # rest subtracted before printing
    }
    if ( $HitName =~ /FLAM_C|AluJo/ && $Seq2End < 134 ) {
      $HitName = "AluH_5";
      if ( $HitName =~ /FLAM_A|AluH_5/ && $Seq2Begin > 37 ) {
        $HitName = "AluG_5";
      }
    }
    if ( $Seq2End < 125 && $HitName =~ /Alu/ ) {
      $HitName = "AluZ1_5" if $HitName =~ /AluYa/;
      if ( $Seq2End < 103 ) {
        $HitName = "AluI_5"  if $HitName =~ /AluJb|Alu[GH]_5/;
        $HitName = "AluQ_5"  if $HitName =~ /AluSp|AluR/;
        $HitName = "AluY"    if $HitName =~ /AluYd/ && $Seq2End < 88;
        $HitName = "AluZ2_5" if $HitName =~ /Alu[YZ][^d]/;
        if ( $Seq2End < 79 ) {
          $HitName = "AluX_5" if $HitName =~ /AluS[cg]|AluZ/;
          if ( $Seq2End < 64 ) {
            $HitName = "AluV_5" if $HitName =~ /Alu[QX]/;
            $HitName = "Alu_5" if $Seq2End < 57;
          }
        }
      }
    }
  }
  if ( $HitName =~ /F[R]?AM/ ) {    # adjust to AluJ
    $Seq2Begin += 136;
    $Seq2End   += 136;
  }
  if ( $HitName eq "7SLRNA" && $Seq2Begin > 238 ) {
    $HitName = "FAM";
    $Seq2Begin -= 5;
    $Seq2End   -= 5;
  }
  elsif ( $Seq2Begin > 64 ) {
    $HitName = "AluO_3" if $HitName =~ /AluS[xg]/;
    if ( $Seq2Begin > 127 ) {
      $HitName = "AluH_3" if $HitName =~ /FRAM|AluJo/;
      if ( $Seq2End < 227 ) {
        $HitName = "AluG_3" if $HitName =~ /FAM|AluH_3/;
        if ( $Seq2End < 213 ) {
          $HitName = "AluF_3" if $HitName =~ /AluJb|AluG_3/;
        }
      }
      if ( $Seq2Begin > 153 ) {
        $HitName = "AluP_3" if $HitName =~ /AluS[pq]/;
        if ( $Seq2Begin > 165 ) {
          $HitName = "AluZ_3" if $HitName =~ /AluYa/;
          if ( $Seq2Begin > 213 ) {
            $HitName = "AluI_3" if $HitName =~ /AluJb|AluH_3/;
            if ( $Seq2Begin > 219 ) {
              $HitName = "AluT_3" if $HitName =~ /AluY$|AluO/;
              if ( $Seq2Begin > 233 ) {
                $HitName = "AluN_3" if $HitName =~ /Alu[ITZ]/;
                if ( $Seq2Begin > 246 ) {
                  if (    $HitName =~ /AluN|AluYb/
                       || ( $HitName eq AluSc  && $Seq2Begin > 255 )
                       || ( $HitName eq AluP_3 && $Seq2Begin > 263 ) )
                  {
                    $HitName = "Alu_3";
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

sub preprocessdnatransp {
  if ( $HitName =~ /MER1[abAB]|Charlie3/ ) {
    if ( $HitName eq MER1A ) {
      if ( $Seq2Begin < 265 && $Seq2End >= 280 ) {
        $HitName = Charlie3a;
      }
      else {
        $HitName = Charlie3;
      }
      $Seq2Begin += 2173 if $Seq2Begin >= 265;
      $Seq2End   += 2173 if $Seq2End > 280;
    }
    elsif ( $HitName eq MER1B ) {
      if (    $Seq2Begin < 88 && $Seq2End >= 103
           || $Seq2Begin < 240 && $Seq2End >= 240 )
      {
        $HitName = Charlie3b;
      }
      else {
        $HitName = Charlie3;
      }
      $Seq2Begin += 40   if $Seq2Begin >= 88;
      $Seq2End   += 40   if $Seq2End > 103;
      $Seq2Begin += 2333 if $Seq2Begin >= 280;    # includes
      $Seq2End   += 2333 if $Seq2End > 280;       # previous addition
    }
  }
  elsif ( $HitName =~ /Charlie/ ) {
    if ( $HitName =~ /Charlie1/ ) {
      if ( $HitName eq Charlie1a ) {
        unless ( $Seq2Begin < 111 && $Seq2End > 123 ) {
          $HitName = Charlie1;
        }
        $Seq2Begin += 1306 if $Seq2Begin >= 111;
        $Seq2End   += 1306 if $Seq2End > 123;
      }
      elsif ( $HitName eq Charlie1b ) {
        unless ( $Seq2Begin < 167 && $Seq2End > 179 ) {
          $HitName = Charlie1;
        }
        $Seq2Begin += 2238 if $Seq2Begin >= 168;
        $Seq2End   += 2238 if $Seq2End > 179;
      }
    }
    elsif ( $HitName =~ /Charlie2/ ) {
      if ( $HitName eq Charlie2a ) {
        if ( $Seq2End < 633 || $Seq2Begin > 1757 ) {
          $HitName = Charlie2;
        }
      }
      elsif ( $HitName eq Charlie2b ) {
        if ( $Seq2End < 633 || $Seq2Begin > 1677 ) {
          $HitName = Charlie2;
        }
        $Seq2Begin += 80 if $Seq2Begin > 1677;
        $Seq2End   += 80 if $Seq2End > 1691;
      }
    }
    elsif ( $HitName eq Charlie4a ) {
      unless ( $Seq2Begin < 285 && $Seq2End > 298 ) {
        $HitName = Charlie4;
      }
      $Seq2Begin += 1453 if $Seq2Begin >= 285;
      $Seq2End   += 1453 if $Seq2End > 298;
    }
  }
  elsif ( $HitName eq 'MER3' ) {
    if ( $Seq2Begin < 48 || $Seq2Begin < 161 && $Seq2End > 153 ) {
      $HitName = Charlie5a;
    }
    else {
      $HitName = Charlie5;
    }
    $Seq2Begin -= 47 if $Seq2Begin <= 160;
    $Seq2End   -= 47 if $Seq2End < 179;
  }
  elsif ( $HitName eq 'MER33' ) {
    if ( $Seq2Begin < 63 && $Seq2End >= 71 ) {
      $HitName = Charlie5b;
    }
    else {
      $HitName = Charlie5;
    }
    $Seq2Begin += 2261 if $Seq2Begin >= 63;
    $Seq2End   += 2261 if $Seq2End > 71;
  }
  elsif ( $HitName =~ /MER102/ ) {
    if ( $Seq2Begin < 257 && $Seq2End >= 290 ) {
      $HitName =~ s/MER102/Charlie8/;
    }
    else {
      $HitName = Charlie8;
    }
    $Seq2Begin += 1087 if $Seq2Begin >= 257;
    $Seq2End   += 1087 if $Seq2End > 290;
  }
  elsif ( $HitName =~ /MER112/ ) {
    if ( $Seq2Begin < 120 && $Seq2End >= 134 ) {
      $HitName =~ s/MER112/Charlie9a/;
    }
    else {
      $HitName = Charlie9;
    }
    $Seq2Begin += 2398 if $Seq2Begin >= 120;
    $Seq2End   += 2398 if $Seq2End > 134;
  }
  elsif ( $HitName =~ /Tigger/ ) {
    if ( $HitName eq Tigger2a ) {
      unless ( $Seq2Begin < 55 && $Seq2End > 70 ) {
        $HitName = Tigger2;
      }
      $Seq2Begin += 2274 if $Seq2Begin >= 55;
      $Seq2End   += 2274 if $Seq2End > 70;
    }
    elsif ( $HitName =~ /Tigger3/ ) {
      if ( $HitName eq Tigger3a ) {
        unless ( $Seq2Begin < 69 && $Seq2End > 80 ) {
          $HitName = Tigger3;
        }
        $Seq2Begin += 2690 if $Seq2Begin >= 70;
        $Seq2End   += 2690 if $Seq2End > 80;
      }
      elsif ( $HitName eq Tigger3b ) {
        unless ( $Seq2Begin < 350 && $Seq2End > 360 ) {
          $HitName = Tigger3;
        }
        $Seq2Begin += 1797 if $Seq2Begin >= 341;
        $Seq2End   += 1797 if $Seq2End > 350;
      }
      elsif ( $HitName eq Tigger3c ) {
        unless ( $Seq2Begin < 137 && $Seq2End > 141 ) {
          $HitName = Tigger3;
        }
        $Seq2Begin += 2426 if $Seq2Begin >= 137;
        $Seq2End   += 2426 if $Seq2End > 141;
      }
      elsif ( $HitName eq Tigger3d ) {
        unless ( $Seq2Begin < 215 && $Seq2End > 86 ) {
          $HitName = Tigger3;
        }
        $Seq2Begin += 2708 if $Seq2Begin >= 215;
        $Seq2End   += 2708 if $Seq2End > 222;
      }
    }
    elsif ( $HitName =~ /Tigger4/ ) {
      if ( $HitName eq Tigger4a ) {
        unless (    $Seq2Begin < 90 && $Seq2End > 87
                 || $Seq2Begin < 146 && $Seq2End > 149 )
        {
          $HitName = Tigger4;
        }
        if ( $Seq2Begin > 90 && $Seq2End < 149 ) {
          if ( $RevComp eq "C" ) {
            $RevComp = '+';
          }
          else {
            $RevComp = "C";
          }
          my $tempvar = $Seq2Begin;
          $Seq2Begin = 145 - $Seq2End;
          $Seq2End   = 145 - $tempvar;
        }
        $Seq2Begin += 2495 if $Seq2Begin >= 147;
        $Seq2End   += 2495 if $Seq2End > 160;
      }
      elsif ( $HitName eq Tigger4b ) {
        unless ( $Seq2Begin < 133 && $Seq2End > 143 ) {
          $HitName = Tigger4;
        }
        $Seq2Begin += 2370 if $Seq2Begin >= 134;
        $Seq2End   += 2370 if $Seq2End > 143;
      }
    }
    elsif ( $HitName =~ /Tigger6/ ) {
      if ( $HitName eq 'Tigger6a' ) {
        unless ( $Seq2Begin < 426 && $Seq2End > 440 ) {
          $HitName = Tigger6;
        }
        $Seq2Begin += 514 if $Seq2Begin >= 426;
        $Seq2End   += 514 if $Seq2End > 440;
      }
      elsif ( $HitName eq 'Tigger6b'
              && ( $Seq2End < 440 || $Seq2Begin > 1002 ) )
      {
        $HitName = Tigger6;
      }
    }
  }
  elsif ( $HitName =~ /MER44/ ) {
    if ( $HitName eq MER44A ) {
      unless ( $Seq2Begin < 65 && $Seq2End > 85 ) {
        $HitName = Tigger7;
      }
      else {
        $HitName = Tigger7a;
      }
      $Seq2Begin += 2152 if $Seq2Begin >= 65;
      $Seq2End   += 2152 if $Seq2End > 85;
    }
    elsif ( $HitName eq MER44B ) {
      unless ( $Seq2Begin < 342 && $Seq2End > 362 ) {
        $HitName = Tigger7;
      }
      else {
        $HitName = Tigger7b;
      }
      $Seq2Begin += 1937 if $Seq2Begin >= 342;
      $Seq2End   += 1937 if $Seq2End > 362;
    }
    elsif ( $HitName eq MER44C ) {
      unless ( $Seq2Begin < 648 && $Seq2End > 668 ) {
        $HitName = Tigger7;
      }
      else {
        $HitName = Tigger7c;
      }
      $Seq2Begin += 1754 if $Seq2Begin >= 645;
      $Seq2End   += 1754 if $Seq2End > 669;
    }
    elsif ( $HitName eq MER44D ) {
      if ( $Seq2Begin >= 227 || $Seq2End <= 248 ) {
        $HitName = Tigger7;
      }
      else {
        $HitName = Tigger7d;
      }
      $Seq2Begin += 1882 if $Seq2Begin >= 227;
      $Seq2End   += 1882 if $Seq2End > 248;
    }
  }
  elsif ( $HitName =~ /MER45/ ) {
    if ( $HitName eq MER45A ) {
      if ( $Seq2Begin >= 106 || $Seq2End <= 123 ) {
        $HitName = MER45;
      }
      $Seq2Begin += 1403 if $Seq2Begin >= 106;
      $Seq2End   += 1403 if $Seq2End > 123;
    }
    elsif ( $HitName eq MER45B ) {
      if ( $Seq2Begin >= 857 || $Seq2End <= 199 ) {
        $HitName = MER45;
      }
      $Seq2Begin += 541 if $Seq2Begin >= 857;
      $Seq2End   += 541 if $Seq2End > 857;
    }
    elsif ( $HitName eq MER45C ) {
      if ( $Seq2Begin >= 771 || $Seq2End <= 179 ) {
        $HitName = MER45;
      }
      $Seq2Begin += 628 if $Seq2Begin >= 771;
      $Seq2End   += 628 if $Seq2End > 771;
    }
    elsif ( $HitName eq MER45R ) {
      if ( $Seq2Begin >= 1458 || $Seq2End <= 199 ) {
        $HitName = MER45;
      }
    }
  }
  elsif ( $HitName =~ /MER47/ ) {
    if ( $HitName eq MER47A ) {
      unless ( $Seq2Begin < 86 && $Seq2End > 103 ) {
        $HitName = Tigger5;
      }
      else {
        $HitName = Tigger5a;
      }
      $Seq2Begin += 1957 if $Seq2Begin >= 86;
      $Seq2End   += 1957 if $Seq2End > 103;
    }
    elsif ( $HitName eq MER47B ) {
      unless ( $Seq2Begin < 230 && $Seq2End > 243 ) {
        $HitName = Tigger5;
      }
      else {
        $HitName = Tigger5b;
      }
      $Seq2Begin += 1905 if $Seq2Begin >= 230;
      $Seq2End   += 1905 if $Seq2End > 243;
    }
    elsif ( $HitName eq MER47C ) {
      unless ( $Seq2Begin < 23 && $Seq2End > 60 ) {
        $HitName = Tigger5;
      }
      else {
        $HitName = Tigger5c;
      }
      $Seq2Begin += 2309 if $Seq2Begin >= 23;
      $Seq2End   += 2309 if $Seq2End > 60;
    }
  }
  elsif ( $HitName =~ /MER58|Cheshire/ ) {
    if ( $HitName eq MER58A ) {
      if ( $Seq2Begin >= 50 || $Seq2End <= 64 ) {
        $HitName = MER58;
        if ( $Seq2Begin < 146 && $Seq2End > 169 ) {
          $HitName = MER58B;
        }
      }
      else { $HitName = MER58Ba; }
      $Seq2Begin += 117  if $Seq2Begin >= 50;
      $Seq2End   += 117  if $Seq2End >= 64;
      $Seq2Begin += 2079 if $Seq2Begin >= 146 + 117;
      $Seq2End   += 2079 if $Seq2End >= 169 + 117;
    }
    elsif ( $HitName eq MER58B ) {
      unless ( $Seq2Begin < 273 && $Seq2End > 287 ) {
        $HitName = MER58;
      }
      elsif ( $Seq2Begin < 163 && $Seq2End > 67 ) {
        $HitName = MER58Bb;
      }
      $Seq2Begin += 2079 if $Seq2Begin >= 272;
      $Seq2End   += 2079 if $Seq2End >= 286;
    }
    elsif ( $HitName eq Cheshire ) {
      if ( $Seq2Begin > 2108 || $Seq2End < 287 ) {
        $HitName = MER58;
      }
      else {
        $HitName = MER58E;
      }
    }
    elsif ( $HitName eq MER58C ) {
      unless ( $Seq2Begin < 128 && $Seq2End > 128 ) {
        $HitName = MER58;
      }
      $Seq2Begin += 2205 if $Seq2Begin >= 135;
      $Seq2End   += 2205 if $Seq2End >= 153;
    }
    elsif ( $HitName eq MER58D ) {
      unless ( $Seq2Begin < 128 && $Seq2End > 128 ) {
        $HitName = MER58;
      }
      $Seq2Begin += 2034 if $Seq2Begin >= 135;
      $Seq2End   += 2034 if $Seq2End >= 153;
    }
  }
  elsif ( $HitName =~ /MER6[ABC]/ ) {
    if ( $HitName eq MER6A ) {
      unless ( $Seq2Begin < 334 && $Seq2End > 346 ) {
        $HitName = MER6;
      }
      $Seq2Begin += 260 if $Seq2Begin >= 334;
      $Seq2End   += 260 if $Seq2End >= 346;
    }
    elsif ( $HitName eq MER6B ) {
      unless (    $Seq2Begin < 123 && $Seq2End > 138
               || $Seq2Begin < 60 && $Seq2End > 72 )
      {
        $HitName = MER6;
      }
      $Seq2Begin += 655 if $Seq2Begin >= 126;
      $Seq2End   += 655 if $Seq2End >= 135;
      $Seq2Begin -= 66 if $Seq2Begin < 126;
      $Seq2End   -= 66 if $Seq2End < 135;
    }
    else {
      unless ( $Seq2Begin < 64 && $Seq2End >= 74 ) {
        $HitName = MER6;
      }
      $Seq2Begin += 653 if $Seq2Begin >= 64;
      $Seq2End   += 653 if $Seq2End >= 74;
    }
  }
  elsif ( $HitName =~ /MER91/ ) {
    if ( $HitName eq MER91A ) {
      unless (    $Seq2Begin < 37 && $Seq2End > 47
               || $Seq2Begin < 131 && $Seq2End > 141 )
      {
        $HitName = "MER91";
      }
    }
    elsif ( $HitName eq MER91B ) {
      unless (    $Seq2Begin < 37 && $Seq2End > 47
               || $Seq2Begin < 119 && $Seq2End > 129 )
      {
        $HitName = "MER91";
      }
    }
    elsif ( $HitName eq MER91C ) {
      unless ( $Seq2Begin < 65 && $Seq2End > 75 ) {
        $HitName = "MER91";
      }
    }
  }
  elsif ( $HitName =~ /MER63/ ) {
    if ( $HitName eq MER63A ) {
      unless ( $Seq2Begin < 158 && $Seq2End > 164 ) {
        $HitName = MER63;
      }
      $Seq2Begin += 852 if $Seq2Begin >= 158;
      $Seq2End   += 852 if $Seq2End > 163;
      $Seq2Begin += 626 if $Seq2Begin >= 45;
      $Seq2End   += 626 if $Seq2End > 54;
    }
    elsif ( $HitName eq MER63B ) {
      unless ( $Seq2Begin < 45 && $Seq2End > 164 ) {
        $HitName = MER63;
      }
      $Seq2Begin += 626 if $Seq2Begin >= 45;
      $Seq2End   += 626 if $Seq2End > 54;
    }
    elsif ( $HitName eq MER63C ) {
      unless ( $Seq2Begin < 288 && $Seq2End > 329 ) {
        $HitName = MER63;
      }
      $Seq2Begin += 130 if $Seq2Begin >= 288;
      $Seq2End   += 130 if $Seq2End > 328;
    }
    elsif ( $HitName eq MER63D ) {
      unless ( $Seq2Begin < 418 && $Seq2End > 330 ) {
        $HitName = MER63;
      }
    }
  }
  elsif ( $HitName =~ /MER69|Arthur1/ ) {
    if ( $HitName eq MER69A ) {
      unless ( $Seq2Begin < 71 && $Seq2End > 85 ) {
        $HitName = MER69;
      }
      $Seq2Begin += 3763 if $Seq2Begin >= 71;
      $Seq2End   += 3763 if $Seq2End > 85;
    }
    elsif ( $HitName eq MER69B ) {
      unless ( $Seq2Begin < 823 && $Seq2End > 840 ) {
        $HitName = MER69;
      }
      $Seq2Begin += 2714 if $Seq2Begin >= 823;
      $Seq2End   += 2714 if $Seq2End > 840;
    }
    else {
      $HitName = MER69;
    }
  }
  elsif ( $HitName =~ /MER70/ ) {
    if ( $Seq2Begin > 430 ) {
      $HitName = MER70;
    }
  }
  elsif ( $HitName eq 'MER75B' ) {
    unless ( $Seq2Begin < 82 && $Seq2End > 36 ) {
      $HitName = MER75;
    }
    $Seq2Begin += 261 if $Seq2Begin >= 82;
    $Seq2End   += 261 if $Seq2End >= 95;
  }
  elsif ( $HitName =~ /MER104|Kanga1/ ) {
    if ( $HitName eq 'MER104' ) {
      $Seq2Begin += 1894 if $Seq2Begin >= 76;
      $Seq2End   += 1894 if $Seq2End > 90;
      $HitName = MER104Z if $Seq2Begin < 76 && $Seq2End > 90;
    }
    elsif ( $HitName eq 'MER104A' ) {
      $Seq2Begin += 1001 if $Seq2Begin >= 147;
      $Seq2End   += 1001 if $Seq2End > 161;
      $Seq2Begin += 176  if $Seq2Begin >= 1360;
      $Seq2End   += 176  if $Seq2End > 1377;
      $HitName = MER104 unless $Seq2Begin < 147 && $Seq2End > 161;
    }
    elsif ( $HitName eq 'MER104B' )
    {    # has an 176 bp insertion compared to Kanga1
      $Seq2Begin += 997 if $Seq2Begin >= 146;
      $Seq2End   += 997 if $Seq2End > 155;
      $HitName = MER104 unless $Seq2Begin < 146 && $Seq2End > 155;
    }
    elsif ( $HitName eq 'MER104C' ) {
      $Seq2Begin += 1182 if $Seq2Begin >= 619;
      $Seq2End   += 1182 if $Seq2End > 637;
      $HitName = MER104 unless $Seq2Begin < 619 && $Seq2End > 637;
    }
    elsif ( $HitName eq 'HsTc2' ) {
      $Seq2Begin += 176 if $Seq2Begin >= 1360;
      $Seq2End   += 176 if $Seq2End > 1377;
      $HitName = MER104;
    }
    $LeftUnaligned = 1921 - $Seq2End if $HitName eq 'MER104';
  }
  elsif ( $HitName =~ /Ricksha/ ) {
    if (
            $HitName =~ /Ricksha(_[bc])?$/
         && $Seq2Begin > 182
         && $Seq2End < 383
         && (    $sortedHits[ $i - 1 ]->getSeq2Name() =~ /ERVL/
              || $sortedHits[ $i + 1 ]->getSeq2Name() =~ /ERVL/ )
        )
    {

      # this is likely the boundary of an ERVL-internal and LTR sequence
      # which is contained in the Ricksha consensus
      $HitName   = 'ERVL-int';
      $ClassName = 'LTR/ERVL';
      $Seq2Begin += 5414;
      $Seq2End   += 5414;
      $LeftUnaligned = 0;    # approximately
    }
    elsif ( $HitName eq Ricksha_a ) {
      unless ( $Seq2Begin < 134 && $Seq2End > 147 ) {
        $HitName = Ricksha;
      }
      $Seq2Begin += 2070 if $Seq2Begin >= 134;
      $Seq2End   += 2070 if $Seq2End >= 147;
    }
    elsif ( $HitName eq Ricksha_b ) {
      unless ( $Seq2Begin < 604 && $Seq2End > 618 ) {
        $HitName = Ricksha;
      }
      $Seq2Begin += 1600 if $Seq2Begin >= 604;
      $Seq2End   += 1600 if $Seq2End >= 618;
    }
    elsif ( $HitName eq Ricksha_c ) {
      unless ( $Seq2Begin < 1289 && $Seq2End > 1302 ) {
        $HitName = Ricksha;
      }
      $Seq2Begin += 1208 if $Seq2Begin >= 1289;
      $Seq2End   += 1208 if $Seq2End >= 1302;
    }
    elsif ( $HitName eq Ricksha_0 ) {
      unless ( $Seq2Begin < 110 && $Seq2End > 120 ) {
        $HitName = Ricksha;
      }
      $Seq2Begin += 1513 if $Seq2Begin >= 110;
      $Seq2End   += 1513 if $Seq2End >= 120;
    }

    #the inverted repetitive termini of Ricksha are tandem repeats of 15/16 bp
    if ( $Seq2End < 170 || $Seq2Begin > 3155 ) {
      if (    $pastHitName[ 0 ]
           && $pastHitName[ 0 ] =~ /Ricksha/
           && $RevComp ne $pastRevComp[ 0 ]
           && $pastEndAlign[ 0 ] - $BeginAlign > 20
           && $pastSeq1Name[ 0 ] eq $Seq1Name )
      {
        $RevComp = $pastRevComp[ 0 ];
        if ( $Seq2End < 170 ) {
          $Seq2End   = 3255 - $Seq2Begin;
          $Seq2Begin = 3170;
        }
        else {
          $Seq2Begin = 3255 - $Seq2End;
          $Seq2End   = 84;
        }
      }
      elsif (    $i < $#sortedHits
              && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /Ricksha/
              && $RevComp ne $sortedHits[ $i + 1 ]->getRevComp()
              && $EndAlign - $sortedHits[ $i + 1 ]->getSeq1Beg() > 20
              && $sortedHits[ $i + 1 ]->getSeq1Name() eq $Seq1Name )
      {
        $RevComp = $sortedHits[ $i + 1 ]->getRevComp();
        if ( $Seq2End < 170 ) {
          $Seq2End   = 3255 - $Seq2Begin;
          $Seq2Begin = 3170;
        }
        else {
          $Seq2Begin = 3255 - $Seq2End;
          $Seq2End   = 84;
        }
      }
    }
  }
}

sub preprocessltrs {

  # all MLT2s adjusted to MLT2B3 or 4
  if ( $Seq2Begin > 180 ) {
    if ( $HitName =~ /^MLT2A/ ) {
      &ChangePos( -108 ) if $Seq2Begin > 270;
    }
    elsif ( $HitName =~ /^MLT2B[12]$/ ) {
      &ChangePos( -47 ) if $Seq2Begin > 265;
    }
    elsif ( $HitName eq MLT2B5 ) {
      if ( $Seq2Begin > 415 ) {
        &ChangePos( 162 );
      }
      else {
        &ChangePos( 116 );
      }
    }
    elsif ( $HitName eq MLT2C1 ) {
      &ChangePos( -166 ) if $Seq2Begin > 220;
    }
    elsif ( $HitName eq MLT2C2 ) {
      &ChangePos( -95 ) if $Seq2Begin > 275;
    }
    elsif ( $HitName eq MLT2D ) {
      &ChangePos( -146 ) if $Seq2Begin > 225;
    }
    elsif ( $HitName eq MLT2E ) {
      &ChangePos( 65 ) if $Seq2Begin > 520;
    }
    elsif ( $HitName eq MLT2F ) {
      &ChangePos( 100 ) if $Seq2Begin > 550;
    }
  }
}

# Temporarily adjusts consensus sequence position info to allow
# merging of matches to different subfamilies. The position is usually
# later readjusted based on the "minned" hash.  Note that positive
# numbers fed to the subroutine are subtracted (longer subfamilies are
# adjusted with higher numbers, shorter with negatives)
sub ChangePos {
  $minned{$ID} = shift;
  $Seq2Begin -= $minned{$ID};
  $Seq2End   -= $minned{$ID};
  $LeftUnaligned += $_[ 0 ] if $_[ 0 ];
}

sub ReAdjustHitName {
  if ( $ClassName eq "SINE/Alu" && !$opt_mus ) {
    if ( $HitName =~ /Alu.*_[35]/ ) {
      if ( $HitName =~ /Alu[GH]_5/ ) {
        if (
             $RevComp eq '+'
             && (
                     $i == $#sortedHits
                  || $Seq1Name ne $sortedHits[ $i + 1 ]->getSeq1Name()
                  || (    $sortedHits[ $i + 1 ]->getSeq1Beg() - $EndAlign < 5
                       && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /SINE\/Alu/ )
             )
            )
        {
          $HitName = "AluJo/FLAM";
        }
        elsif (
                $RevComp eq 'C'
                && (
                        $i == 0
                     || $Seq1Name ne $pastSeq1Name[ 0 ]
                     || (    $BeginAlign - $pastEndAlign[ 0 ] < 5
                          && $pastClassName[ 0 ] eq "SINE/Alu" )
                )
            )
        {
          $HitName = "AluJo/FLAM";
        }
        else {
          $HitName = "FLAM"   if $HitName eq "AluG_5";
          $HitName = "FLAM_C" if $HitName eq "AluH_5";
        }
      }
      elsif ( $HitName eq "AluO_3" ) {
        $HitName = "AluSg/x";
      }
      elsif ( $HitName eq "AluR_5" ) {
        $HitName = "AluSq/x";
      }
      elsif ( $HitName =~ /Alu[FGH]_3/ ) {
        if (
             $RevComp eq "C"
             && (
                     $i == $#sortedHits
                  || $Seq1Name ne $sortedHits[ $i + 1 ]->getSeq1Name()
                  || (    $sortedHits[ $i + 1 ]->getSeq1Beg() - $EndAlign < 5
                       && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /SINE\/Alu/ )
             )
             || $RevComp eq '+'
             && (
                     $i == 0
                  || $Seq1Name ne $pastSeq1Name[ 0 ]
                  || (    $BeginAlign - $pastEndAlign[ 0 ] < 5
                       && $pastClassName[ 0 ] eq "SINE/Alu" )
             )
            )
        {
          $HitName = "AluJo/FRAM"   if $HitName eq "AluH_3";
          $HitName = "AluJo/F(R)AM" if $HitName eq "AluG_3";
          $HitName = "AluJ/F(R)AM"  if $HitName eq "AluF_3";
        }
        else {
          $HitName = "FRAM" if $HitName eq "AluH_3";
          $HitName = "FRAM/FAM" if $HitName =~ /Alu[FG]_3/;
        }
      }
      elsif ( $HitName eq "AluQ_5" ) {
        $HitName = "AluS";
      }
      elsif ( $HitName eq "AluP_3" ) {
        $HitName = "AluSp/q";
      }
      elsif ( $HitName eq "AluI_5" ) {
        $HitName = "AluJ/FLAM";
      }
      elsif ( $HitName eq "AluI_3" ) {
        $HitName = "AluJ/FRAM";
      }
      elsif ( $HitName =~ /Alu[VX]_5|AluT_3/ ) {
        if ( $PctSubst > 11 ) {
          $HitName = "AluS";    # generic AluS
        }
        elsif ( $PctSubst < 5 ) {
          $HitName = "AluY";    # rare AluYa5/8 and AluYb8 ignored
        }
        else {
          $HitName = "Alu";
        }
      }
      elsif ( $HitName =~ /AluZ1_5|AluZ_3/ ) {
        $HitName = "AluYa5/8";
      }
      elsif ( $HitName eq "AluZ2_5" ) {
        $HitName = "AluY";      #rare AluYa5/8 and AluYb8 ignored
      }
      elsif ( $HitName =~ /AluN?_[35]/ ) {
        if ( $PctSubst > 20 ) {
          $HitName = "AluJ/monomer";
        }
        elsif ( $PctSubst < 5 ) {
          $HitName = "AluY";
        }
        else {
          $HitName = "Alu";
        }
      }
      if ( $HitName =~ /AluY[ab]/ && $PctSubst >= 6 ) {
        $HitName = "Alu";
      }
    }
    if ( $HitName =~ /^F[LR]?AM/ ) {
      $LeftUnaligned -= 169 if $HitName =~ /^FLAM/;
      $Seq2Begin     -= 136 if $HitName =~ /F[R]?AM/;
      $Seq2Begin = 1 if $Seq2Begin < 1;
      $Seq2End -= 136 if $HitName =~ /F[R]?AM/;
    }
  }

  elsif ( $ClassName =~ /DNA/ ) {
    $HitName =~ s/f$//;

    #Change names back to internal deletion products if so necessary
    if ( $HitName =~ /Charlie/ ) {
      if ( $HitName =~ /Charlie1/ ) {
        if ( $HitName eq Charlie1a ) {
          &BeginandEnd( 1306, 1455 );
        }
        elsif ( $HitName eq Charlie1b ) {
          &BeginandEnd( 2238, 523 );
        }
        else {
          $LeftUnaligned = 2761 - $Seq2End;
        }
      }
      elsif ( $HitName eq Charlie2b ) {
        $Seq2End   -= 80 if $Seq2End > 1871;
        $Seq2Begin -= 80 if $Seq2Begin > 1857;
      }
      elsif ( $HitName =~ /Charlie3/ ) {
        if ( $HitName eq Charlie3a ) {
          $HitName = MER1A;
          &BeginandEnd( 2173, 527 );
        }
        elsif ( $HitName eq Charlie3b ) {
          $HitName = MER1B;
          &BeginandEnd( 2333, 337 );
          $Seq2Begin -= 40 if $Seq2Begin > 135;
          if ( $Seq2End > 135 ) {
            $Seq2End -= 40;
          }
          else {
            $LeftUnaligned = 337 - $Seq2End;
          }
        }
        else {
          $LeftUnaligned = 2710 - $Seq2End;
        }
      }
      elsif ( $HitName eq Charlie4a ) {
        &BeginandEnd( 1453, 508 );
      }
      elsif ( $HitName eq Charlie4 ) {
        $LeftUnaligned = 1961 - $Seq2End;
      }
      elsif ( $HitName =~ /Charlie5/ ) {
        if ( $HitName eq Charlie5a ) {
          $HitName = MER3;
          $Seq2Begin += 47 if $Seq2Begin <= 113;
          $Seq2End   += 47 if $Seq2End < 122;
          $LeftUnaligned = 209 - $Seq2End;
        }
        elsif ( $HitName eq Charlie5b ) {
          $HitName = MER33;
          &BeginandEnd( 2261, 324 );
        }
        else {

          $LeftUnaligned = 2612 - $Seq2End;
        }
      }
      elsif ( $HitName =~ /Charlie8/ ) {
        if ( $HitName eq Charlie8a ) {
          &BeginandEnd( 1087, 330 );
          $HitName = MER102a;
        }
        elsif ( $HitName eq Charlie8b ) {
          &BeginandEnd( 1087, 341 );
          $HitName = MER102b;
        }
        else {
          $LeftUnaligned = 2417 - $Seq2End;
        }
      }
      elsif ( $HitName =~ /Charlie9/ ) {
        if ( $HitName eq Charlie9a ) {
          &BeginandEnd( 2398, 260 );
          $HitName = MER112;
        }
        else {
          $LeftUnaligned = 2659 - $Seq2End;
        }
      }
    }
    elsif ( $HitName =~ /Tigger/ ) {
      if ( $HitName eq Tigger2a ) {
        &BeginandEnd( 2274, 434 );
      }
      elsif ( $HitName =~ /Tigger2/ ) {
        $LeftUnaligned = 2718 - $Seq2End;
      }
      elsif ( $HitName =~ /Tigger3/ ) {
        $HitName = 'Tigger3(Golem)' if $HitName eq 'Tigger3';
        if ( $HitName =~ /3a/ ) {
          &BeginandEnd( 2692, 348 );
          $HitName = "MER7A";
        }
        elsif ( $HitName =~ /3b/ ) {
          &BeginandEnd( 1797, 1231 );
        }
        elsif ( $HitName =~ /3c/ ) {
          &BeginandEnd( 2426, 602 );
          $HitName = "MER7C";
        }
        elsif ( $HitName =~ /3d/ ) {
          &BeginandEnd( 2708, 321 );
          $HitName = "MER7D";
        }
        else {
          $LeftUnaligned = 3029 - $Seq2End;
        }
      }
      elsif ( $HitName =~ /Tigger4/ ) {
        $HitName = 'Tigger4(Zombi)' if $HitName eq 'Tigger4';
        if ( $HitName =~ /4a/ ) {
          &BeginandEnd( 2495, 236 );
          $HitName = "MER46A";
        }
        elsif ( $HitName =~ /4b/ ) {
          &BeginandEnd( 2495, 361 );
          $HitName = "MER46B";
        }
        else {
          $LeftUnaligned = 2731 - $Seq2End;
        }
      }
      elsif ( $HitName =~ /Tigger7\w/ ) {
        if ( $HitName =~ /7a/ ) {
          &BeginandEnd( 2152, 339 );
          $HitName = "MER44A";
        }
        elsif ( $HitName =~ /7b/ ) {
          &BeginandEnd( 1937, 550 );
          $HitName = "MER44B";
        }
        elsif ( $HitName =~ /7c/ ) {
          &BeginandEnd( 1754, 733 );
          $HitName = "MER44C";
        }
        elsif ( $HitName =~ /7d/ ) {
          &BeginandEnd( 1882, 705 );
          $HitName = "MER44D";
        }
        else {
          $LeftUnaligned = 2487 - $Seq2End;
        }
      }
      elsif ( $HitName =~ /Tigger5/ ) {
        if ( $HitName eq Tigger5a ) {

          #		    $HitName = MER47A;
          &BeginandEnd( 1957, 366 );
        }
        elsif ( $HitName eq Tigger5b ) {

          #		    $HitName = MER47B;
          &BeginandEnd( 1905, 418 );
        }
        elsif ( $HitName eq Tigger5c ) {

          #                   $HitName = MER47C;
          &BeginandEnd( 2309, 97 );
        }
        else {
          $LeftUnaligned = 2323 - $Seq2End;
        }
      }
      elsif ( $HitName eq Tigger6a ) {
        $Seq2Begin -= 514 if $Seq2Begin >= 940;
        $Seq2End   -= 514 if $Seq2End >= 940;
        $LeftUnaligned = 1083 - $Seq2End;
      }
    }
    elsif ( $HitName =~ /MER45\w/ ) {
      if ( $HitName eq MER45A ) {
        &BeginandEnd( 1403, 178 );
      }
      elsif ( $HitName eq MER45B ) {
        $Seq2Begin -= 541 if $Seq2Begin >= 857;
        $Seq2End   -= 541 if $Seq2End >= 857;
        $LeftUnaligned = 1040 - $Seq2End;
      }
      elsif ( $HitName eq MER45C ) {
        $Seq2Begin -= 628 if $Seq2Begin >= 771;
        $Seq2End   -= 628 if $Seq2End >= 771;
        $LeftUnaligned = 953 - $Seq2End;
      }
      else {
        $LeftUnaligned = 1581 - $Seq2End;
      }
    }
    elsif ( $HitName =~ /MER58/ ) {
      if ( $HitName eq MER58Ba ) {
        &BeginandEnd( 2079, 224 );
        &BeginandEnd( 117,  224 );
        $HitName = MER58A;
      }
      elsif ( $HitName =~ /MER58B/ ) {
        &BeginandEnd( 2079, 341 );
        $HitName = MER58B;
      }
      elsif ( $HitName eq MER58C ) {
        &BeginandEnd( 2205, 215 );
      }
      elsif ( $HitName eq MER58D ) {
        &BeginandEnd( 2034, 386 );
      }
      elsif ( $HitName eq MER58E ) {
        $HitName       = Cheshire;
        $LeftUnaligned = 2420 - $Seq2End;
      }
    }
    elsif ( $HitName eq MER6A ) {
      $Seq2Begin -= 260 if $Seq2Begin >= 334;
      $Seq2End   -= 260 if $Seq2End >= 346;
      $LeftUnaligned = 605 - $Seq2End;
    }
    elsif ( $HitName eq MER6B ) {
      &BeginandEnd( 655, 210 );
      $Seq2Begin += 66 if $Seq2Begin < 126;
      if ( $Seq2End < 135 ) {
        $Seq2End += 66;
      }
      else {
        $LeftUnaligned = 210 - $Seq2End;
      }
    }
    elsif ( $HitName eq MER6C ) {
      &BeginandEnd( 653, 202 );
    }
    elsif ( $HitName =~ /MER63[ABC]/ ) {
      if ( $HitName =~ /3A/ ) {
        &BeginandEnd( 852, 210 );
        &BeginandEnd( 626, 210 );
      }
      elsif ( $HitName =~ /3B/ ) {
        &BeginandEnd( 626, 436 );
      }
      elsif ( $HitName =~ /3C/ ) {
        $Seq2Begin -= 130 if $Seq2Begin > 400;
        $Seq2End   -= 130 if $Seq2End > 400;
        $LeftUnaligned = 930 - $Seq2End;
      }
    }
    elsif ( $HitName =~ /MER69/ ) {
      &BeginandEnd( 2349, 177 )  if $HitName eq 'MER69A';
      &BeginandEnd( 1300, 1226 ) if $HitName eq 'MER69B';
      $HitName = 'Arthur1' if $HitName eq 'MER69';
    }
    elsif ( $HitName eq 'MER75B' ) {
      &BeginandEnd( 261, 243 );
    }
    elsif ( $HitName =~ /MER104/ ) {
      if ( $HitName =~ /Z$/ ) {
        $HitName = MER104;
        &BeginandEnd( 1894, 180 );
      }
      elsif ( $HitName =~ /A$/ ) {
        $Seq2Begin -= 176 if $Seq2Begin > 1400;
        $Seq2End   -= 176 if $Seq2End > 1400;
        &BeginandEnd( 1001, 744 );
        $HitName = Kanga1a;
      }
      elsif ( $HitName =~ /B$/ ) {
        &BeginandEnd( 997, 765 );
        $HitName = Kanga1b;
      }
      elsif ( $HitName =~ /C$/ ) {
        &BeginandEnd( 1182, 729 );
        $HitName = Kanga1c;
      }
      else {
        $Seq2Begin -= 176 if $Seq2Begin > 1400;
        $Seq2End   -= 176 if $Seq2End > 1400;
        $HitName = Kanga1;
      }
    }
    elsif ( $HitName =~ /Ricksha_/ ) {
      if ( $HitName eq Ricksha_0 ) {
        &BeginandEnd( 1513, 1733 );
      }
      elsif ( $HitName eq Ricksha_a ) {
        &BeginandEnd( 2070, 1181 );
      }
      elsif ( $HitName eq Ricksha_b ) {
        &BeginandEnd( 1600, 1255 );
      }
      elsif ( $HitName eq Ricksha_c ) {
        $Seq2Begin -= 1208 if $Seq2Begin > 1289;
        $Seq2End   -= 1208 if $Seq2End > 1302;
        $LeftUnaligned = 2048 - $Seq2End;
      }
    }
  }
  $LeftUnaligned = 0 if $LeftUnaligned < 0;

  # can be caused by minor errors in adjustments
  # negative leftunaligned throw lines out somehow
}

sub BeginandEnd {
  my ( $change, $length ) = @_;
  $Seq2Begin -= $change if $Seq2Begin >= $change;
  if ( $Seq2End >= $change ) {
    $Seq2End -= $change;
  }
  else {
    $LeftUnaligned = $length - $Seq2End;
  }
}

sub FuseOverlappingSeqs {
  my $cycle = shift;
  $fusedwithprev = $nextoverlap = 0;
  my $j         = 0;
  my $ignorediv = "";
  while (
    !$fusedwithprev
    &&

# if another element overlaps, previous element has already been fused with that
    $j < 5 && $j <= $#pastID
      )
  {

# can't simply use objects, since features may have been adjusted in this same cycle
    &NamePrevious( $j );
    unless ( $ClassName eq $lCN && $Seq1Name eq $lSN ) {    # && $QO >= -10) {
       # used to have requirement && $QO >= -10, but 'twopast' element may fully overlap
       # past element (with lower SW) or start at same spot but end later (sort works that way)
      last;
    }
    my $thislength = $Seq2End - $Seq2Begin + 1;
    my $lastlength = $lSE - $lSB + 1;
    if ( $ClassName =~ /Simple|Satellite/ && $QO >= -10 ) {
      if ( $EndAlign > $lEA ) {    # don't fuse (CA)n(TG)n(CA)n etc
        if ( $SW <= $lSW && $HitName ne $lHN ) {
          my $tempname    = quotemeta $lHN;
          my $nextoverlap = 0;
          if (    $cycle == 1
               && $i < $#sortedHits
               && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /$tempname/
               && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
               && $sortedHits[ $i + 1 ]->getSeq1Beg() < $EndAlign )
          {
            $nextoverlap = $EndAlign - $sortedHits[ $i + 1 ]->getSeq1Beg() + 1;
          }
          elsif (    $cycle == 2
                  && $i < $#sortedHits
                  && $sortedHits[ $i + 1 ]->getSeq2Name() =~ /$tempname/
                  && $Seq1Name eq $sortedHits[ $i + 1 ]->getSeq1Name()
                  && $sortedHits[ $i + 1 ]->getSeq1End() < $BeginAlign )
          {
            $nextoverlap =
                $BeginAlign - $sortedHits[ $i + 1 ]->getSeq1End() + 1;
          }
          if (
            $QO + $nextoverlap > 10
            &&

            # just to be sure it's not 0 in the following division
            $thislength / ( $QO + $nextoverlap ) < 2
              )
          {
            $SW         = $lSW;
            $PctSubst   = $lPS;
            $PctInsert  = $lPI;
            $PctDelete  = $lPD;
            $BeginAlign = $lBA if $cycle == 1;
            $EndAlign   = $lEA if $cycle == 2;
            $HitName    = $lHN;
            $Seq2Begin  = 1;
            my $matchlength = $EndAlign - $BeginAlign + 1;
            $Seq2End =
                $matchlength + ( $PctInsert - $PctDelete ) * $matchlength / 100;
            $Seq2End = sprintf( "%d", $Seq2End );
            $fusedwithprev = 1;
          }
        }
        elsif ( $HitName eq $lHN ) {
          $SW = $lSW if $lSW > $SW;
          $PctSubst =
              ( $PctSubst * $thislength + $lPS * $lastlength ) /
              ( $thislength + $lastlength );
          $PctInsert =
              ( $PctInsert * $thislength + $lPI * $lastlength ) /
              ( $thislength + $lastlength );
          $PctDelete =
              ( $PctDelete * $thislength + $lPD * $lastlength ) /
              ( $thislength + $lastlength );
          $BeginAlign = $lBA if $cycle == 1;
          $EndAlign   = $lEA if $cycle == 2;
          $Seq2Begin  = 1;
          my $matchlength = $EndAlign - $BeginAlign + 1;
          $Seq2End =
              $matchlength + ( $PctInsert - $PctDelete ) * $matchlength / 100;
          $Seq2End = sprintf( "%d", $Seq2End );
          $fusedwithprev = 1;
        }
      }
    }
    elsif ( $HitName eq 'SVA' )
    {    # due to placement in Alu file, can be of different 'cut-levels'
      if (
        $cycdir == 1 && $Seq2End < 880 && $lSE > 425 ||    # tandem repeat area
        $cycdir == 2 && $Seq2Begin > 425 && $lSB < 880
          )
      {    # rest taken care of elsewhere
        if ( $QO >= -10 ) {
          $SW = $lSW if $lSW > $SW;
          $PctSubst =
              ( $PctSubst * $thislength + $lPS * $lastlength ) /
              ( $thislength + $lastlength );
          $PctInsert =
              ( $PctInsert * $thislength + $lPI * $lastlength ) /
              ( $thislength + $lastlength );
          $PctDelete =
              ( $PctDelete * $thislength + $lPD * $lastlength ) /
              ( $thislength + $lastlength );
          $BeginAlign = $lBA if $cycle == 1;
          $EndAlign   = $lEA if $cycle == 2;
          $Seq2Begin  = $lSB if $lSB < $Seq2Begin;
          $Seq2End    = $lSE if $lSE > $Seq2End;
          $fusedwithprev = 1;
          last;
        }
        else {
          $id{$ID} = $lID;
          ++$matchedup{ $pastID[ $j ] };
        }
      }
    }
    elsif ( $LastField < $lLF ) {
      last
          ; # cut out before the last one was detected: is never going to overlap!
    }    # Low_complexity never overlaps:
    elsif (
         $QO > 33
      && $RevComp   eq $lRC
      && $LastField eq $lLF
      && (
        $HitName !~ /^L1.*_3end$/    # to be handled by adjustsub
        || $EndAlign - $lEA <= 30 && $lBA - $BeginAlign <= 30
      )
        )
    {                                # insignificant extensions
       #left out for cases like: young 3'end inserted in old one, alignment extended into old one;
      if ( $ClassName eq 'LINE/L1' && $HitName ne $lHN ) {
        if (
             $HitName =~ /HAL1_5end$/
          || $HitName !~ /_[35]end/
          && $lHN =~ /_[35]end/
          && $HitName !~ /_strong/
          ||                         # this takes care of most
             $HitName =~ /L1$|orf2/ && $lHN !~ /L1$|orf2/
          || $HitName =~ /_5end/ && $lHN =~ /_5end/ && $cycdir == 2
          || $HitName =~ /_5end/ && $lHN =~ /^L1[PM][1-5]$|^L1.+_3end$|_strong$/
          || $HitName =~ /L1[PM]$/     && $lHN =~ /L1\w\w/
          || $HitName =~ /L1[PM][1-6]/ && $lHN =~ /^L1.*_3end$/
          || $HitName =~ /L1M[56]/     && $lHN =~ /5end$/
            )
        {                            #wonder if that still happens

   #		    $cycdir == 1 && ($HitName =~ /L1[PM][1-6]/ && $lHN =~ /L1[PM][1-6]/ ||
   #				     $HitName =~ /L1[PM]$/ && $lHN =~ /L1[PM]$/)) {
          if (    $HitName =~ /_orf2/
               && $sortedHits[ $i - $j - 1 ]->getSeq2Name() =~ /_orf2/ )
          {

    # March 04 addition: especially at more sensitive settings two ORF2
    # region-fragments of LINEs may get covered by a single alignment
    # (usually with much indels and one region with high divergence) to a
    # "wrong" consensus. The correct consensus matches in two pieces, and
    # only one has a higher score than the false one note that $lHN may
    # have been adjusted to now have a 5' or 3' end name and cannot be used
    # The main problem is that the elements look much older than they are
    # occasionally blocking the "merging of IDs" of the fragments of the element
    # in which it had inserted
            ++$ignorediv;
          }
          $HitName = $lHN unless $lHN =~ /HAL1_5end$/;
        }
        elsif (
                $cycdir == 1
                && (    $HitName =~ /L1[PM][1-6]/ && $lHN =~ /L1[PM][1-6]/
                     || $HitName =~ /L1[PM]$/ && $lHN =~ /L1[PM]$/ )
            )
        {
          last;
        }
      }
      elsif ( $HitName =~ /^CR1-[BF]$/ && $cycdir == 1 ) {
        $HitName = $lHN;
      }

      &AdjustSubstLevel( $j, $ignorediv );

      # Adjusting the positions in the consensus sequence
      # and the bp left over in the consensus in the fused fragments
      # Alu stuff can be removed after Phil adjusts masklevel behavior
      if ( $ClassName !~ /Alu/ || $SW <= $lSW ) {
        ##if ($cycle == 1 && $RevComp ne C || $cycle ==2 && $RevComp eq C) {
        ###try difference (also for Seq2End)
        if (
          $lSB < $Seq2Begin

     #this doesn't work out easily as insertions can cause it to be out of range
     #		    && ($HitName eq $lHN ||
     #		     $RevComp ne C && $Seq2Begin - $lSB < $BeginAlign - $lBA + 500
     #		     && $Seq2Begin - $lSB > $BeginAlign - $lBA - 500 ||
     #		     $RevComp eq C && $Seq2Begin - $lSB < $lEA - $EndAlign + 500
     #		     && $Seq2Begin - $lSB > $lEA - $EndAlign - 500)
          || $ClassName =~ /Alu/
            )
        {
          $Seq2Begin = $lSB;
        }
        if (
             $ClassName ne 'LINE/L1' && $LeftUnaligned > $lLU
          || $ClassName eq 'LINE/L1' && $cycdir == 1 && $lSE > $Seq2End
          ||

# in case $lSE == $Seq2End, current call is a shorter match with higher SW score:
          $ClassName =~ /Alu/
            )
        {
          $LeftUnaligned = $lLU;
        }
        if ( $lSE > $Seq2End || $ClassName =~ /Alu/ ) {
          $Seq2End = $lSE;
        }
      }

      if ( $SW <= $lSW ) {
        $SW = $lSW; # no adding, confuses script while adjusting begin/end below
          #is this right? does it not change hitnames to less well defined hitname? CHECK
        $HitName = $lHN if $ClassName !~ /^LINE/ || $HitName =~ /^L1.*_3end$/;
      }
      if ( $HitName =~ /-int|ERV/ && $ltrscore{$lID} ) {

# was /-int|[HM]ERV/ improved annotation; more ERVs are adjusted for LTR assignments
        $HitName = $lHN;
      }
      if ( $cycle == 1 || $SW > $lSW && $BeginAlign > $lBA ) {
        $BeginAlign = $lBA;
      }
      if ( $cycle == 2 || $SW > $lSW && $EndAlign < $lEA ) {
        $EndAlign = $lEA;
      }
      $fusedwithprev = 1;
      if ( $minned{ $id{$ID} } && $Seq2Begin < $lSB ) {
        $minned{$lID} = $minned{ $id{$ID} };
      }

# only when HitName is adjusted to lasthitname, the 'age' of the element should get adjusted as well:
      $lineage{$lID} = $lineage{ $id{$ID} } unless $HitName eq $lHN;
      $id{$ID} = $lID;
      ++$matchedup{ $pastID[ $j ] };
      $length{$ID} = $EndAlign - $BeginAlign + 1;
    }
    elsif (    $QO > 33
            && $ClassName =~ /DNA/
            && $HitName   eq $lHN
            && $LastField eq $lLF )
    {
      $id{$ID} = $lID;    # due to palindromic nature (e.g. MER5, MER96)
           # I think these represent single insertions of recombined elements,
           # rather than insertions on top of each other
    }
    ++$j;
  }
}

sub AdjustNames {

# adjust fragment names based on flanking elements and merges LINE1 fragments
# note that to get here the fragments haven't been required to be in the same orientation
  $cycdir           = "";
  @sameori          = ();
  @distfine         = ();
  @ConsensusGap     = ();
  @ConsensusOverlap = ();

  $internal = "";
  if (
          $ClassName =~ /LTR/
       && ( $HitName !~ /LTR/ || $HitName =~ /int$/ )
       && ( $HitName =~ /int|ERV|PRIMA41|Harlequin|HUERS/i
         || $opt_mus && $HitName =~ /MMERGLN|MMURS|MMVL30|MULV|MURVY|ETn|^IAP/ )
      )
  {
    $internal = 1;
  }

  my $j = 0;
  if (    ( $cycle eq "1" && $RevComp eq "C" )
       || ( $cycle eq "2" && $RevComp eq '+' ) )
  {
    $cycdir = 1;
    while ( $j < 7 && $pastID[ $j ] ) {
      $ConsensusGap[ $j ]     = $pastSeq2Begin[ $j ] - $Seq2End;
      $ConsensusOverlap[ $j ] = -$ConsensusGap[ $j ];
      ++$j;
    }
  }
  elsif (    ( $cycle eq "1" && $RevComp eq '+' )
          || ( $cycle eq "2" && $RevComp eq "C" ) )
  {
    $cycdir = 2;
    while ( $j < 7 && $j <= $#pastClassName ) {
      $ConsensusGap[ $j ]     = $Seq2Begin - $pastSeq2End[ $j ];
      $ConsensusOverlap[ $j ] = -$ConsensusGap[ $j ];
      ++$j;
    }
  }

  my $k = 0;
  while (    $k < 7
          && $pastID[ $k ]
          && $ClassName eq $pastClassName[ $k ]
          && $Seq1Name  eq $pastSeq1Name[ $k ]
          && $ID - $pastID[ $k ] < 21
          && $pastID[ $k ] - $ID < 21 )
  {
    if (
         $pastLastField[ $k ] > $LastField
         && (    $cycle == 1 && $pastEndAlign[ $k ] > $EndAlign
              || $cycle == 2 && $pastBeginAlign[ $k ] < $BeginAlign )
        )
    {

    # insertion in a previous element; should not be adjusted to anything beyond
      last;
    }
    if (
      $cycle == 1 && $id{ $pastID[ $k ] } > $id{$ID}
      ||

      # should not happen, as it should be covered by previous (insert)
      $cycle == 2 && $id{ $pastID[ $k ] } < $id{$ID}
        )
    {

# happens when an element 3' of this one has been linked to one 5' to current
# as the 3' element preferred the 5' el over current, don't connect this one now
# if the above link is correct, no elements further 5' can be linked to current
      last;
    }

    if ( $RevComp eq $pastRevComp[ $k ] ) {
      $sameori[ $k ] = "complement" if $RevComp eq "C";
      $sameori[ $k ] = "forward"    if $RevComp eq '+';
    }
    if (
            $ConsensusOverlap[ $k ] <= 33 && $ConsensusGap[ $k ] <= 200
         || $internal
         && (    $ConsensusOverlap[ $k ] <= 111 && $ConsensusGap[ $k ] <= 1234
              || $HitName eq $pastHitName[ $k ]
              && $ConsensusOverlap[ $k ] <= 111
              && $ConsensusGap[ $k ] <= 5555 )
        )
    {
      $distfine[ $k ] = 1;
    }
    elsif ( $ClassName eq "LINE/L1" ) {
      my $divdif;
      if ( $PctSubst > $pastPctSubst[ $k ] ) {
        $divdif =
            ( $pastPctSubst[ $k ] / $PctSubst ) / 0.65 -
            ( $PctSubst - $pastPctSubst[ $k ] ) / 100;
      }
      elsif ( $pastPctSubst[ $k ] > 0 ) {
        $divdif =
            ( $PctSubst / $pastPctSubst[ $k ] ) / 0.65 -
            ( $pastPctSubst[ $k ] - $PctSubst ) / 100;
      }
      else {
        $divdif = 1.2;
      }
      $divdif = 1.2 if $divdif > 1.2;
      my $removed
          ; # factor decreasing with number of intervening elements; should prevent way distatnt link-ups
      $removed = 1 - ( $ID - $pastID[ $k ] - 1 ) / 30
          if $cycle ==
          1;    # -1 because previous ID should not be a penalty at all
      $removed = 1 - ( $pastID[ $k ] - $ID - 1 ) / 30 if $cycle == 2;

      my $Overlap = $ConsensusOverlap[ $k ];
      $Overlap -= $QueryOverlap[ $k ] if $QueryOverlap[ $k ] > 0;

      if (
        $Overlap <= ( 3.75 * $LeftUnaligned**0.48 - 47 ) * $removed**2 *
        $divdif             # painfully arbitrary
        && $divdif > 0.1    # I'm being generous here
        && $ConsensusGap[ $k ] <= $removed * $divdif * $LeftUnaligned / 1.4
          )
      {

# consensus gap should be allowed to be larger the more 5' you get, since these regions are getting rarer
        $distfine[ $k ] = 1;
      }
    }
    ++$k;
  }

  # adjust Alu subfamily names
  if ( $HitName =~ /Alu$|Alu.*_[35]/
       || ( $HitName =~ /AluJ[bo]/ && ( $Seq2Begin > 103 || $Seq2End < 213 ) ) )
  {
    if (
            $sameori[ 0 ]
         && $ConsensusOverlap[ 0 ] <= 25
         && (    $ConsensusGap[ 0 ] <= 10
              || $ConsensusGap[ 0 ] <= 100 && $QueryGap[ 0 ] <= 25 )
        )
    {
      &ChangeAluNames( $pastHitName[ 0 ] );
    }
    elsif (    $sameori[ 1 ]
            && $ConsensusOverlap[ 1 ] <= 25
            && $ConsensusGap[ 1 ] <= 10 )
    {
      &ChangeAluNames( $pastHitName[ 1 ] );
    }
    elsif (    $sameori[ 2 ]
            && $ConsensusOverlap[ 2 ] <= 25
            && $ConsensusGap[ 2 ] <= 10 )
    {
      &ChangeAluNames( $pastHitName[ 2 ] );
    }
  }

  if ( $ClassName =~ /LTR/ ) {

# all that trouble about pTR5 is bull; it's a transcript with a large internal deletion of an ERV9
# pTR5 has been deleted from retrovirus.lib and LTR12 and LTR17 consensi moved to humsines.lib Apr 10 '04
# since it is quite diverged from other LTR12 and HERV9 consensi kind of surprising that it is transcribed
#	if ($HitName eq 'LTR12' && $pastHitName[0] eq 'pTR5' && $LastField < 5
#	    && $RevComp eq $pastRevComp[0] && $QueryGap[0] < 10) {
#	    $HitName = 'pTR5';
#	    $LastField = $pastLastField[0]; # otherwise will be seen as inserted element
#	    $SW = $pastSW[0] if $pastSW[0] > $SW; # divergence doesn't matter too much?
#	    $BeginAlign = $pastBeginAlign[0] if $BeginAlign > $pastBeginAlign[0];
#	    if ($EndAlign < $pastEndAlign[0]) {	# takes care of overlaps too
#		$EndAlign = $pastEndAlign[0];   # these overlaps are artifacts
#                $LeftOver = $pastLeftOver[0];
#	    }
#	    if ($RevComp eq '+') {
#		$Seq2Begin = $pastSeq2Begin[0];
#	    } else {
#		$Seq2Begin += 1519;
#	    }
#	    $Seq2End += 1780;
#	    $length{$ID} = $EndAlign - $BeginAlign + 1;
#	} else {
    $anothercounter = 0;

    # adjust LTR elements' internal names to names of LTRs
    $ltrtaken = $increasethruskip = 0;
    $ltrpassed = 0;
LTRLOOP:
    while (    !$ltrtaken
            && $anothercounter < 6
            && $pastSeq1Name[ $anothercounter ]
            && $Seq1Name eq $pastSeq1Name[ $anothercounter ]
            && $pastClassName[ $anothercounter ] =~ $ClassName )
    {

      # measures to prevent distant fragments to 'attach' to each other
      if ( $cycle == 1 ) {
        for ( $j = $ID - 1 ; $j > $pastID[ $anothercounter ] ; --$j ) {
          if ( $id{$j} && $class{$j} !~ /^simple|low/i ) {

# if candidate fragments of same element are interrupted by much older "insert", don't link
# there is a problem when the inserted element is not in the repeat library but distantly matches an existing entry
            if (
                 &CheckDifinDiv( $PctSubst, $div{$j} )
              && $EndAlign - $BeginAlign > 50

         # too short fragments sometimes have erratically low  divergence levels
              || $ID < $numberoffragments     && $id{$j} == $id{ $ID + 1 }
              || $ID + 1 < $numberoffragments && $id{$j} == $id{ $ID + 2 }
              || $ID + 2 < $numberoffragments && $id{$j} == $id{ $ID + 3 }
                )
            {
              last LTRLOOP;
            }
            elsif (
                  &CheckDifinDiv( $div{ $pastID[ $anothercounter ] }, $div{$j} )
                  && $pastEndAlign[ $anothercounter ] -
                  $pastBeginAlign[ $anothercounter ] > 50 )
            {
              ++$anothercounter;
              next LTRLOOP;
            }
          }
        }
      }
      elsif ( $cycle == 2 ) {
        for ( $j = $ID + 1 ; $j < $pastID[ $anothercounter ] ; ++$j ) {
          if ( $id{$j} && $class{$j} !~ /^simple|low/i ) {
            if (    &CheckDifinDiv( $PctSubst, $div{$j} )
                 && $EndAlign - $BeginAlign > 50
                 || $ID > 1 && $id{$j} == $id{ $ID - 1 }
                 || $ID > 2 && $id{$j} == $id{ $ID - 2 }
                 || $ID > 3 && $id{$j} == $id{ $ID - 3 } )
            {
              last LTRLOOP;
            }
            elsif (
                  &CheckDifinDiv( $div{ $pastID[ $anothercounter ] }, $div{$j} )
                  && $pastEndAlign[ $anothercounter ] -
                  $pastBeginAlign[ $anothercounter ] > 50 )
            {
              ++$anothercounter;
              next LTRLOOP;
            }
          }
        }
      }
      &AdjustSubFam( $anothercounter );
      ++$anothercounter;
    }
    ++$matchedup{$ltrpassed}
        if $ltrpassed;    # for if nothing with better matches showed up
  }

  elsif ( $ClassName eq "LINE/L1" ) {

    #adjust subfamily names based on better characterized neighboring fragments
    $l1taken = $l1passed = $increasethruskip = $maybeHitName = $maybeID = 0;
    $anothercounter = 0;
LINELOOP:
    while (    !$l1taken
            && $anothercounter < 7
            && $anothercounter <= $#pastID
            && $Seq1Name eq $pastSeq1Name[ $anothercounter ]
            && $pastClassName[ $anothercounter ] =~ $ClassName )
    {
      if ( $cycle == 1 ) {
        for ( $j = $ID - 1 ; $j > $pastID[ $anothercounter ] ; --$j ) {
          if ( $id{$j} && $class{$j} !~ /^simple|low/i ) {
            if (    &CheckDifinDiv( $PctSubst, $div{$j} )
                 && $EndAlign - $BeginAlign > 50
                 || $ID < $numberoffragments     && $id{$j} == $id{ $ID + 1 }
                 || $ID + 1 < $numberoffragments && $id{$j} == $id{ $ID + 2 }
                 || $ID + 2 < $numberoffragments && $id{$j} == $id{ $ID + 3 } )
            {
              last LINELOOP;
            }
            elsif (
                  &CheckDifinDiv( $div{ $pastID[ $anothercounter ] }, $div{$j} )
                  && $pastEndAlign[ $anothercounter ] -
                  $pastBeginAlign[ $anothercounter ] > 50 )
            {
              ++$anothercounter;
              next LINELOOP;
            }
          }
        }
      }
      elsif ( $cycle == 2 ) {
        for ( $j = $ID + 1 ; $j < $pastID[ $anothercounter ] ; ++$j ) {
          if ( $id{$j} && $class{$j} !~ /^simple|low/i ) {
            if (    &CheckDifinDiv( $PctSubst, $div{$j} )
                 && $EndAlign - $BeginAlign > 50
                 || $ID > 1 && $id{$j} == $id{ $ID - 1 }
                 || $ID > 2 && $id{$j} == $id{ $ID - 2 }
                 || $ID > 3 && $id{$j} == $id{ $ID - 3 } )
            {
              last LINELOOP;
            }
            elsif (
                  &CheckDifinDiv( $div{ $pastID[ $anothercounter ] }, $div{$j} )
                  && $pastEndAlign[ $anothercounter ] -
                  $pastBeginAlign[ $anothercounter ] > 50 )
            {
              ++$anothercounter;
              next LINELOOP;
            }
          }
        }
      }
      &AdjustSubFam( $anothercounter );
      ++$anothercounter;
    }
    if ( $l1passed ) {    # for if nothing with a better match showed up
      $HitName = $maybeHitName;
      if ( $minned{ $id{$ID} }
          && ( !$minned{$maybeID} || $minned{ $id{$ID} } > $minned{$maybeID} ) )
      {
        $minned{$maybeID} = $minned{ $id{$ID} };
      }
      $id{$ID} = $maybeID;
      ++$matchedup{$l1passed};
    }
  }

  elsif ( $ClassName =~ /DNA/ ) {
    my $j = 0;
    while (    $pastHitName[ $j ]
            && $j < 4
            && $HitName ne $pastHitName[ $j ]
            && $id{$ID} != $id{ $pastID[ $j ] } )
    {
      if (
           $pastHitName[ $j ] =~ /$HitName(_)?[abcdABCDE]/
           && (    $ConsensusGap[ $j ] <= 500
                || $BeginAlign - $pastEndAlign[ $j ] < 500
                && $pastEndAlign[ $j ] - $BeginAlign < 500 )
           && $ConsensusOverlap[ $j ] <= 75
          )
      {
        $HitName = $pastHitName[ $j ];
        $id{$ID} = $id{ $pastID[ $j ] };
      }
      ++$j;
    }
  }

# chicken: CR1 is almost only repeat around, so CR1 3' ends usually follow each other: make strict requirements
  elsif ( $HitName =~ /CR1-[BFX]/ && $cycdir == 1 ) {
    my $j = 0;
    while (
         $pastHitName[ $j ]
      && $j < 4
      && $QueryGap[ $j ] < ( 500 + $LeftUnaligned / 4 )
      &&    # loop mostly for interrupting simple repeats
      $HitName ne $pastHitName[ $j ] && $id{$ID} != $id{ $pastID[ $j ] }
        )
    {
      if (
           $ConsensusOverlap[ $j ] < 35
           && (    $pastHitName[ $j ] =~ /CR1-[BX]/ && $HitName =~ /CR1-[BX]/
                || $pastHitName[ $j ] =~ /CR1-F/ && $HitName =~ /CR1-F/ )
           && ( $sameori[ $j ] || $QueryGap[ $j ] < 10 )
          )
      {     # the latter for "-><-" cases
        $HitName = $pastHitName[ $j ];
        $id{$ID} = $id{ $pastID[ $j ] };
      }
      ++$j;
    }
  }

# fuse non-LINE1 sequences with small gaps with respect to consensus
# why limit to last one; excludes any elements with inserts in both fragments now
  $shortHitName = $HitName;
  $shortHitName   =~ s/(^\w{5}).*/$1/
      if $HitName =~ /^MER\d{2}|^LTR\d{2}|^L1M|^Alu/;
  $shortHitName   =~ s/(^\w{4}).*/$1/
      if $HitName =~ /^MER\d[A-Z_a-z]|^LTR\d[A-Z_a-z]|ORR1/;
  $shortHitName =~ s/^(MT2?)[A-F]$/$1/ if $opt_mus;
  $shortHitName = quotemeta $shortHitName;

  if (
          $ClassName ne "LINE/L1"
       && $sameori[ 0 ]
       && $ConsensusGap[ 0 ] <= 100
       && $LastField eq $pastLastField[ 0 ]
       && $QueryGap[ 0 ] <= 25
       && !$fusedwithprev
       && $pastHitName[ 0 ] =~ /$shortHitName/
       && (    $ConsensusOverlap[ 0 ] <= 20
            || $QueryGap[ 0 ] < 0
            && $ConsensusOverlap[ 0 ] - $QueryOverlap[ 0 ] <= 20 )
       && ( $ClassName ne "SINE/Alu" || $cycdir == 1 )
      )
  {

    if (    $ClassName ne "SINE/Alu" && $SW < $pastSW[ 0 ]
         || $ClassName eq "SINE/Alu" && $HitName eq $pastHitName[ 0 ] )
    {
      $SW       = $pastSW[ 0 ];
      $PctSubst = $length{$ID} * $PctSubst + $length{ $pastID[ 0 ] } *
          $pastPctSubst[ 0 ];
      $PctInsert = $length{$ID} * $PctInsert + $length{ $pastID[ 0 ] } *
          $pastPctInsert[ 0 ];
      $PctDelete = $length{$ID} * $PctDelete + $length{ $pastID[ 0 ] } *
          $pastPctDelete[ 0 ];
      if ( $QueryGap[ 0 ] - $ConsensusGap[ 0 ] > 0 ) {
        $PctInsert += ( $QueryGap[ 0 ] - $ConsensusGap[ 0 ] );
      }
      else { $PctDelete -= ( $QueryGap[ 0 ] - $ConsensusGap[ 0 ] ); }
      $PctSubst  /= $length{$ID} + $length{ $pastID[ 0 ] };
      $PctInsert /= $length{$ID} + $length{ $pastID[ 0 ] };
      $PctDelete /= $length{$ID} + $length{ $pastID[ 0 ] };
      $HitName = $pastHitName[ 0 ];
      if ( $cycle == 1 ) {
        $BeginAlign = $pastBeginAlign[ 0 ];
      }
      elsif ( $cycle == 2 ) {
        $EndAlign = $pastEndAlign[ 0 ];
        $LeftOver = $pastLeftOver[ 0 ];
      }
      if ( $cycdir == 1 ) {
        $Seq2End       = $pastSeq2End[ 0 ];
        $LeftUnaligned = $pastLeftUnaligned[ 0 ];
      }
      elsif ( $cycdir == 2 ) {
        $Seq2Begin = $pastSeq2Begin[ 0 ];
      }
      ++$matchedup{ $pastID[ 0 ] };
    }
  }
}

sub CheckDifinDiv {
  my $this = shift;
  my $that = shift;
  $that > 2 * $this && $that > $this + 10;
}

sub AdjustSubFam {
  my $number = shift;
  &NamePrevious( $number );

 #    if ($matchedup{$pastID[$number]}) {
 #	$id{$ID} = $pastID[$number]; # keeps it the same if the linked ID has changed
 #    } elsif ($sameori) {
  if (
       $sameori
       && ( !$matchedup{ $pastID[ $number ] }
            || $BeginAlign == $lBA )
      )
  {    # for those that are fused in sub Fuse..
    if ( $ClassName =~ /^LTR/ ) {
      my $lastinternal;
      if (    $lHN =~ /int|ERV|PRIMA41|Harlequin|HUERS/i && $lHN !~ /LTR$/
           || $opt_mus && $lHN =~ /MMERGLN|MMURS|MMVL30|MULV|MURVY|ETn|IAP$/ )
      {
        $lastinternal = 1;
      }
      if ( $internal ) {
        if (
             $ClassName !~ /MaLR/ && $lHN !~ /pTR5/
             || (    $HitName =~ /^THE1/ && $lHN =~ /THE1|MST[AB]/
                  || $HitName =~ /^MST/    && $lHN =~ /THE1[BC]|MST|MLT1[AB]/
                  || $HitName =~ /^MLT1?-/ && $lHN =~ /MST[CD]|MLT1/
                  || $HitName =~ /^MLT1F/  && $lHN =~ /MLT1[DEFGHIJKL]/
                  || $HitName =~ /^ORR1/   && $lHN =~ /^ORR1|^MT/
                  || $HitName =~ /^MT/     && $lHN =~ /^MT|^ORR1/ )
            )
        {
          ###		     $HitName =~ /ERVL/ && $lHN =~ /^MT2/)) {  # ERVL is not labeled MaLR
          if ( !$lastinternal ) {
            if ( $id{$ID} < $lID + 4 ) {
              if (    $cycdir eq "2" && $Seq2Begin <= 33 && $lLU <= 33
                   || $cycdir eq "1" && $LeftUnaligned <= 33 && $lSB <= 33 )
              {
                $id{$ID} = $lID if $cycle == 1;
                unless (    $cycle == 2
                         && $ltrscore{ $id{$ID} }
                         && $ltrscore{ $id{$ID} } > $lSW )
                {
                  ### only the names  of internal sequences with -int are adjusted to the LTRs
                  ### 'HERVx' names remain what they are; change?
                  if ( $HitName =~ /int/i ) {
                    $HitName = $lHN . "-int";
                  }
                  elsif ( $lHN =~ /^ML?T2/ )
                  {    # catches both MT2 and MLT2 for MERVL and (H)ERVL
                    ( $HitName .= "-" . "$lHN" ) =~
                        s/ERVL([-\w]+)?-ML?T2/ERVL-/;  #  removes previous label
                  }
                  $ltrscore{ $id{$ID} } = $lSW;
                }
                $id{$ID}   = $lID;
                $ltrtaken  = 1;
                $ltrpassed = 0;
                ++$matchedup{ $pastID[ $number ] };
              }
              elsif (
                   !$ltrpassed
                   && ( $cycdir eq "2" && $Seq2Begin <= 333 && $lLU <= 150
                     || $cycdir eq "1" && $LeftUnaligned <= 333 && $lSB <= 150 )
                  )
              {
                $id{$ID} = $lID if $cycle == 1;
                unless (    $cycle == 2
                         && $ltrscore{ $id{$ID} }
                         && $ltrscore{ $id{$ID} } > $lSW )
                {
                  if ( $HitName =~ /int/i ) {
                    $HitName = $lHN . "-int";
                  }
                  elsif ( $lHN =~ /^ML?T2/ ) {
                    ( $HitName .= "-" . "$lHN" ) =~
                        s/ERVL([-\w]+)?-ML?T2/ERVL-/;  #  removes previous label
                  }
                  $ltrscore{ $id{$ID} } = $lSW;
                }
                $id{$ID} = $lID;
                if (    $cycdir eq "2" && $Seq2Begin > 33
                     || $cycdir eq "1" && $LeftUnaligned > 33 )
                {
                  $ltrpassed =
                      $pastID[ $number ];    # keep looking for better match
                }
                else {
                  $ltrtaken  = 1;
                  $ltrpassed = 0;
                  ++$matchedup{ $pastID[ $number ] };
                }
              }
            }
          }

          # elsif $lHN is internal and:
          elsif (
                     $cycle == 1 && ( $distfine || $BeginAlign == $lBA )
                  || $cycle == 2
                  && (
                       $id{$ID} == $curid{ $pastID[ $number ] }
                       || $ltrscore{$lID} && ( !$ltrscore{ $id{$ID} }
                                    || $ltrscore{ $id{$ID} } < $ltrscore{$lID} )
                       || $HitName eq $lHN && $distfine
                  )
              )
          {

# latter: odd cases where link not made in first cycle due to too many (now fused) intervening seqs
            $HitName  = $lHN;
            $id{$ID}  = $lID;
            $ltrtaken = 1;
            ++$matchedup{ $pastID[ $number ] };
          }
          elsif ( !$ltrscore{ $id{$ID} } && !$ltrscore{$lID} ) {
            $HitName = $lHN if $SW > 2 * $lSW;
            $id{$ID} = $lID;
            $ltrtaken = 1;
            ++$matchedup{ $pastID[ $number ] };
          }
        }
      }

      #elsif it is not an internal sequence
      elsif (
              $ClassName !~ /MaLR/
              || (    $HitName =~ /THE1/ && $lHN =~ /THE1|MST[AB-]/
                   || $HitName =~ /MST/   && $lHN =~ /THE1[BC-]|MST|MLT1[A-]/
                   || $HitName =~ /MLT1A/ && $lHN =~ /MST[CD-]|MLT1[ABC-]/
                   || $HitName =~ /MLT1[B-H]/ && $lHN =~ /MLT1/
                   || $HitName =~ /^ORR1/     && $lHN =~ /^ORR1|^MT/
                   || $HitName =~ /^MT/       && $lHN =~ /^MT|^ORR1/ )
          )
      {
        if ( $lastinternal ) {
          if ( $cycle == 2 && $id{$ID} == $curid{ $pastID[ $number ] } ) {

            # connected in first cycle; shouldn't disconnect
            $id{$ID} = $lID;
            $ltrtaken = 1;
            ++$matchedup{ $pastID[ $number ] };
          }
          elsif (
               $cycle == 1
            && $ltrscore{$lID}
            && (    $ClassName =~ /MaLR/ && $SW < $ltrscore{$lID} / 1.5
                 || $SW < $ltrscore{$lID} / 2 )
            &&

# $ltrscore{$lID} is the $SW of opposite LTR;
# 1.5 or 2 times lower score suggests small piece and much better guess at other site
            (
                 $RevComp eq "+" && $Seq2Begin <= 33     && $lLU <= 33
              || $RevComp eq "C" && $LeftUnaligned <= 33 && $lSB <= 33
            )
              )
          {
            if ( $HitName =~ /MLT2/ ) {
              ( $HitName = $lHN ) =~ s/[HM]ERVL-/MLT2/i;
            }
            elsif ( $lHN =~ /-int$/ ) {
              ( $HitName = $lHN ) =~ s/-int//i;
            }
            $id{$ID} = $lID;
            $ltrtaken = 1;
            ++$matchedup{ $pastID[ $number ] };
          }
        }    # elsif last is LTR too:
        elsif (
          (
               $ClassName =~ /MaLR/
            || $HitName =~ /MLT2/ && $lHN =~ /MLT2/
            || $HitName eq $lHN
          )
          && $LastField == 5
          && $lLF == 5         # lower (3) means: cut out and complete
          && $CG <= 220 - ( $number + 1 ) * 20
          && $CO <= 50
          && $sameori          # $CG and $CO will be 0 if !$sameori

# don't adjust LTRs that are complete at connecting end (would happen when broken longer LTR follows):
          && (    $cycdir == 1 && $LeftUnaligned >= 10 && $lSB > 10
               || $cycdir == 2 && $Seq2Begin > 10 && $lLU >= 10 )
          || $id{$ID} == $curid{ $pastID[ $number ] }
            )
        {
          if ( $ClassName =~ /MaLR/ && $SW < $lSW || 2 * $SW < $lSW ) {
            $HitName = $lHN;
          }
          $id{$ID}  = $lID;
          $ltrtaken = 1;       #just causes adjustsubfam cycle to stop
          ++$matchedup{ $pastID[ $number ] };
        }
      }
    }
    elsif ( $ClassName eq "LINE/L1" && $cycdir == 1 ) {
      my $endsmatch = "";
      if ( $HitName =~ /^L1.*_3end$/ ) {
        if (
             $QO > 33
             && (
                  $opt_primate && ( $HitName =~ /L1PA/ && $lHN =~ /^L1PA/
                     || $HitName =~ /L1PA1[4567]/ && $lHN =~ /^L1PB/
                     || $HitName =~ /L1PB/ && $lHN =~ /L1PA1[4567]|L1MA[1-4]$/ )
                  || $opt_mus && ( $HitName =~ /L1Md/ && $lHN =~ /L1Md|L1_Mus/
                       || $HitName =~ /L1_Mus/ && $lHN =~ /L1Md|L1_Mus|Lx[_2]/
                       || $HitName =~ /L1_Rn/  && $lHN =~ /L1_R[na]t?/
                       || $HitName =~ /L1_Rat/ && $lHN =~ /L1_R[na]t?|Lx[_2]/
                       || $HitName =~ /Lx[_2]/ && $lHN =~ /L1_Mus|L1_Rat|Lx[_2]/
                       || $HitName =~ /Lx[3-9]/ && $lHN =~ /Lx[3-9]/ )
                  || $HitName =~ /L1M[AB]/  && $lHN =~ /L1M[AB]/
                  || $HitName =~ /L1M[CDE]/ && $lHN =~ /L1M[CDE]/
                  || $HitName =~ /L1MB[5-8]|L1ME[1-3]/
                  && $lHN     =~ /L1MB[5-8]|L1ME[1-3]/
             )
            )
        {
          $endsmatch =
              1;    # other cases may represent 'hybrids' after integration
        }
        elsif (
          $opt_primate
          && (
               $HitName =~ /L1P[HA][2-6s]/ && $lHN =~ /^L1P[HA][2-9s]/
            || $HitName =~ /L1PA[7-9]/     && $lHN =~ /^L1PA[4-9]|^L1PA1[0-2]/
            || $HitName =~ /L1PA1[0-3]/    && $lHN =~ /^L1PA[7891]/
            ||      # save as long as there is no L1PA1
            $HitName =~ /L1PA1[4-67]/ && $lHN =~ /^L1PA1/ ||    # ibid
            $HitName =~ /L1PB/ && $lHN =~ /^L1PB/
            || $HitName =~ /L1MA[1-3]$/    && $lHN =~ /^L1MA[1-4]A?$/
            || $HitName =~ /L1MA4A?|L1PB3/ && $lHN =~ /^L1MA[1-6]A?$|L1PB3/
          )
          || $opt_mus && (    $HitName =~ /^(L1\w+?)\d*_3end/ && $lHN =~ /^$1/
                           || $HitName =~ /(Lx[\d_])/ && $lHN =~ /^$1/ )
          ||    # pretty restrictive
             $HitName =~ /L1MA[5-7]A?/ && $lHN =~ /^L1MA[4-9]A?/
          || $HitName =~ /L1MA[7-9]/   && $lHN =~ /^L1MA[5-9]|L1MA10/
          || $HitName eq 'L1MB1' && $lHN =~ /L1MA9|L1MA10|^L1MB[1-4]/
          || $HitName =~ /L1MA10|L1MA9/
          && $lHN     =~ /L1MA[89]|L1MA10|^L1M[BE][1-3]/
          || $HitName =~ /L1MB[2-4]/ && $lHN =~ /^L1MB[1-6]/
          || $HitName =~ /L1MB[5-8]/ && $lHN =~ /^L1MB[3-8]|^L1ME[1-3]/
          || $HitName =~ /L1MC|L1MD3/ && $lHN =~ /^L1MC|L1MD3/
          || $HitName =~ /L1MD/ && $lHN =~ /^L1MD/
          || $HitName =~ /L1ME/ && $lHN =~ /^L1ME/
            )
        {
          $endsmatch = 1;
        }
      }

      # new scheme to ease the problem of linking broken L1 fragments
      # this only works on the primate and mammalian-wide L1 subs nomenclature
      if (
        (
          $distfine
          ||    #nearby fragments with a proper distance in query and consensus
          $QO > 33 && $endsmatch && $LastField == $lLF
        )
        &&

        # overlapping, close 3'ends left untouched in fuse sub
        (
             $HitName =~ /$lHN(_)?/
          || $endsmatch && ( $opt_mus && $Seq2End < 6600 || $Seq2End <= 6015 )
          ||

    # $endsmatch just  determined before this loop; works on 3' ends only, thus:
          $HitName !~ /_3end$/ && &matchL1frags( $lHN )
        )
          )
      {
        if (    $CG <= 200 && $CO <= 33
             || $QO > 33 && $endsmatch
             || $QO > 0 && $CO - $QO <= 33 && $QO - $CO <= 33 )
        {
          $HitName = $lHN;
          if ( $minned{ $id{$ID} } && $Seq2Begin < $lSB ) {
            $minned{$lID} = $minned{ $id{$ID} };
          }
          $id{$ID}  = $lID;
          $l1taken  = 1;
          $l1passed = 0;
          ++$matchedup{ $pastID[ $number ] };
          if ( $QO >= 0 && $LastField == $lLF ) {

# fix Feb 15 2002: added "&& $LastField == $lLF"  Alignments are not merged if the lastfields are not identical
            if ( $SW < $lSW || $lEA - $lBA > 200 ) {
              $SW = $lSW;
            }
            &AdjustSubstLevel( $number );
            $BeginAlign = $lBA if $BeginAlign > $lBA;
            $EndAlign   = $lEA if $EndAlign < $lEA;
            $Seq2Begin  = $lSB if $lSB < $Seq2Begin;
            if ( $LeftUnaligned >= $lLU ) {

              # if ($lSE > $Seq2Begin + 50) {
              $Seq2End = $lSE if $lSE > $Seq2End;
              $LeftUnaligned = $lLU;
            }
          }
        }
        elsif ( !$l1passed ) {

# gets here if $HitName eq $lHN && $ConsensusOverlap[$k] <= 111 && $ConsensusGap[$k] <= 5555 && !$l1passed
          $maybeHitName = $lHN;
          $maybeID      = $lID;
          $l1passed     = $pastID[ $number ];
        }
      }
      elsif (    $LastField == $lLF
              && $QO > 33
              && !$endsmatch
              && $Seq2End > 5825 )
      {    # with $Seq2End > 5825 most 3'ends retain full name
        ++$shrink5end{ $pastID[ $number ] };

        # to adjust lenght immediately I need to change all $BeginAlign to
        # $BeginAlign{$ID} etc.; solves other problems as well. However, in
        # some cases the previous match extends both beyond both current ends;
        # will be left with some unaccounted for masked seq if you'd just shrink
        if ( $cycle == 1 && $lEA > $EndAlign ) {
          $EndAlign = $lEA;
        }
        elsif ( $cycle == 2 && $lBA < $BeginAlign ) {
          $BeginAlign = $lBA;
        }
        $Seq2Begin = $lSB if $lSB < $Seq2Begin;
      }
    }

    #associate 5'ends and bodies of L1 lacking 3' ends to 5' ends
    elsif (    $HitName =~ /^L1$|^L1.*orf2|^L1.*5end$/
            && $lHN =~ /^L1.*5end$/
            && $cycdir == 2
            && $distfine )
    {
      if (    $HitName =~ /^L1$/ && $lHN =~ /^L1$|L1P|L1M1/
           || $HitName =~ /orf2$/      && $lHN =~ /L1M/
           || $HitName =~ /^L1P/       && $lHN =~ /L1P/
           || $HitName =~ /^L1M1/      && $lHN =~ /L1M[123]/
           || $HitName =~ /^L1M[23]/   && $lHN =~ /L1M[1234]/
           || $HitName =~ /^L1M[4CDE]/ && $lHN =~ /L1M[4CDE]/ )
      {
        if (    $CG <= 200 && $CO <= 33
             || $QO > 0 && $QO - $CO <= 33 && $CO - $QO <= 33 )
        {
          $HitName = $lHN;
          if ( $minned{ $id{$ID} } && $Seq2Begin < $lSB ) {
            $minned{$lID} = $minned{ $id{$ID} };
          }
          $id{$ID}  = $lID;
          $l1taken  = 1;
          $l1passed = 0;
          ++$matchedup{ $pastID[ $number ] };
          if ( $QO >= 0 ) {
            if ( $SW < $lSW ) {
              $SW = $lSW;
              &AdjustSubstLevel( $number );
            }
            if ( $cycle == 1 ) {
              $BeginAlign = $lBA;
            }
            else {
              $EndAlign = $lEA;
            }
            $Seq2Begin = $lSB;    # always $cycdir 2
          }
        }
        elsif ( !$l1passed ) {
          $maybeHitName = $lHN;
          $maybeID      = $lID;
          $l1passed     = $pastID[ $number ];
        }
      }
    }
  }
}

sub PrintReady {
  if ( $RevComp eq '+' ) {
    $Seq2BeginPrint     = $Seq2Begin;
    $LeftUnalignedPrint = "(" . $LeftUnaligned . ")";
  }
  else {
    $Seq2BeginPrint     = "(" . $LeftUnaligned . ")";
    $LeftUnalignedPrint = $Seq2Begin;
  }
}

sub MoveToPast {
  unshift @pastSW,            $SW;
  unshift @pastPctSubst,      $PctSubst;
  unshift @pastPctInsert,     $PctInsert;
  unshift @pastPctDelete,     $PctDelete;
  unshift @pastSeq1Name,      $Seq1Name;
  unshift @pastBeginAlign,    $BeginAlign;
  unshift @pastEndAlign,      $EndAlign;
  unshift @pastLeftOver,      $LeftOver;
  unshift @pastRevComp,       $RevComp;
  unshift @pastHitName,       $HitName;
  unshift @pastClassName,     $ClassName;
  unshift @pastSeq2Begin,     $Seq2Begin;
  unshift @pastSeq2End,       $Seq2End;
  unshift @pastLeftUnaligned, $LeftUnaligned;
  unshift @pastLastField,     $LastField;
  unshift @pastID,            $ID;
  if ( $pastSW[ 100 ] ) {    # to relieve memory of large arrays
    splice @pastSW,            30;    # unlikely to ever look more than 30 back
    splice @pastPctSubst,      30;
    splice @pastPctInsert,     30;
    splice @pastPctDelete,     30;
    splice @pastSeq1Name,      30;
    splice @pastBeginAlign,    30;
    splice @pastEndAlign,      30;
    splice @pastLeftOver,      30;
    splice @pastRevComp,       30;
    splice @pastHitName,       30;
    splice @pastClassName,     30;
    splice @pastSeq2Begin,     30;
    splice @pastSeq2End,       30;
    splice @pastLeftUnaligned, 30;
    splice @pastLastField,     30;
    splice @pastID,            30;
  }
}

sub NamePrevious {
  my $j = shift;
  $distfine = $sameori = $CG = $CO = 0;
  $lSW = $pastSW[ $j ];
  $lPS = $pastPctSubst[ $j ];
  $lPI = $pastPctInsert[ $j ];
  $lPD = $pastPctDelete[ $j ];
  $lSN = $pastSeq1Name[ $j ];
  $lBA = $pastBeginAlign[ $j ];
  $lEA = $pastEndAlign[ $j ];
  $lRC = $pastRevComp[ $j ];
  $lHN = $pastHitName[ $j ];
  $lCN = $pastClassName[ $j ];
  $lSB = $pastSeq2Begin[ $j ];
  $lSE = $pastSeq2End[ $j ];
  $lLU = $pastLeftUnaligned[ $j ];
  $lLF = $pastLastField[ $j ];
  $lID = $id{ $pastID[ $j ] };
  $QO  = $QueryOverlap[ $j ];
  if ( $sameori[ $j ] ) {
    $distfine = $distfine[ $j ];
    $sameori  = $sameori[ $j ];
    $CG       = $ConsensusGap[ $j ];
    $CO       = $ConsensusOverlap[ $j ];
  }
}

sub AdjustSubstLevel {
  my $j = shift;
  my ( $id, $id2 );
  my $qo        = $QO;
  my $ignorediv = shift;    #only present for falsely extended L1 ORF2 fragments
  if ( $ignorediv ) {
    $PctSubst  = $lPS;
    $PctInsert = $lPI;
    $PctDelete = $lPD;      # for annotation
    $div{$ID}  = $lPS;      # this is what the subroutin CheckDifinDiv checks on
  }
  else {

#this construction should subtract the length of shared inserts in overlapping elements
    foreach $id ( @{ $inserts{$ID} } ) {
      foreach $id2 ( @{ $inserts{ $pastID[ $j ] } } ) {
        $qo -= $length{$id} if $id2 == $id && $length{$id};
      }
    }
    if ( $PctSubst <= $lPS ) {
      $PctSubst =
          $length{$ID} * $PctSubst + ( $length{ $pastID[ $j ] } - $qo ) * $lPS;
      $PctInsert =
          $length{$ID} * $PctInsert + ( $length{ $pastID[ $j ] } - $qo ) * $lPI;
      $PctDelete =
          $length{$ID} * $PctDelete + ( $length{ $pastID[ $j ] } - $qo ) * $lPD;
    }
    else {
      $PctSubst =
          $length{ $pastID[ $j ] } * $lPS + ( $length{$ID} - $qo ) * $PctSubst;
      $PctInsert =
          $length{ $pastID[ $j ] } * $lPI + ( $length{$ID} - $qo ) * $PctInsert;
      $PctDelete =
          $length{ $pastID[ $j ] } * $lPD + ( $length{$ID} - $qo ) * $PctDelete;
    }
    $PctSubst  /= ( $length{$ID} + $length{ $pastID[ $j ] } - $qo );
    $PctInsert /= ( $length{$ID} + $length{ $pastID[ $j ] } - $qo );
    $PctDelete /= ( $length{$ID} + $length{ $pastID[ $j ] } - $qo );
  }
}

sub ChangeAluNames {
  my ( $lastorpast ) = @_;
  if (    ( $HitName eq "Alu" && $lastorpast =~ /Alu\w/ )
       || ( $HitName eq "AluR_5" && $lastorpast =~ /AluS[xq]/ )
       || ( $HitName =~ /Alu[GH]_5/ && $lastorpast =~ /AluJo|FLAM/ )
       || ( $HitName eq "AluZ1_5" && $lastorpast =~ /AluYa[58]/ )
       || ( $HitName eq "AluI_5"  && $lastorpast =~ /AluJ/ )
       || ( $HitName eq "AluQ_5"  && $lastorpast =~ /AluS[xqp]/ )
       || ( $HitName eq "AluZ2_5" && $lastorpast =~ /AluY/ )
       || ( $HitName eq "AluX_5"  && $lastorpast =~ /AluS[cg]|AluY/ )
       || ( $HitName eq "AluV_5"  && $lastorpast =~ /Alu[SY]/ )
       || ( $HitName eq "Alu_5"   && $lastorpast =~ /Alu[JSY]|FLAM/ ) )
  {
    $HitName = $lastorpast;
  }
  elsif ( $HitName =~ /Alu[QR]_5/ ) {
    $HitName = "AluSx" if $lastorpast eq "AluO_3";
    $HitName = "AluSq" if $lastorpast eq "AluP_3";
  }
  elsif ( $HitName =~ /Alu[GH]_5/ ) {
    $HitName = "AluJo" if $lastorpast =~ /Alu[GH]_3/;
    $HitName = "AluJ" if $lastorpast eq "AluF_3";
  }
  elsif ( $HitName eq "AluX_5" ) {
    $HitName = "AluSg" if $lastorpast eq "AluO_3";
  }
  elsif ( $HitName eq "AluG_5" ) {
    $HitName = "AluJo/FLAM" if $lastorpast =~ /Alu[HI]_5/;
  }
  elsif (    ( $HitName eq "AluO_3" && $lastorpast =~ /AluS[xg]/ )
          || ( $HitName eq "AluH_3" && $lastorpast =~ /AluJo|FRAM/ )
          || ( $HitName eq "AluG_3" && $lastorpast =~ /AluJo|FR?AM/ )
          || ( $HitName eq "AluF_3" && $lastorpast =~ /AluJ|FR?AM/ )
          || ( $HitName eq "AluP_3" && $lastorpast =~ /AluS[pq]/ )
          || ( $HitName eq "AluZ_3" && $lastorpast =~ /AluYa/ )
          || ( $HitName eq "AluI_3" && $lastorpast =~ /AluJ|FR?AM/ )
          || ( $HitName eq "AluT_3" && $lastorpast =~ /AluY$|AluS[xg]/ )
          || ( $HitName eq "AluN_3" && $lastorpast =~ /Alu[JSY][abgox]?|FR?AM/ )
          || ( $HitName eq "Alu_3"  && $lastorpast =~ /Alu[JSY]|FR?AM/ ) )
  {
    $HitName = $lastorpast;
  }
  elsif ( $HitName eq "AluO_3" ) {
    $HitName = "AluSx" if $lastorpast =~ /Alu[RQ]_5/;
    $HitName = "AluSg" if $lastorpast eq "AluX_5";
  }
  elsif ( $HitName =~ /Alu[FGH]_3/ ) {
    $HitName = "AluJo" if $lastorpast =~ /Alu[GH]_5/;
  }
  elsif ( $HitName eq "AluP_3" ) {
    $HitName = "AluSq"   if $lastorpast eq "AluR_5";
    $HitName = "AluSg/q" if $lastorpast eq "AluSg";
  }
  if (    ( $lastorpast =~ /AluJb?$/ && $HitName =~ /Alu[GH]_[35]|AluJo/ )
       || ( $lastorpast =~ /Alu[GH]_[35]|AluJo?$/ && $HitName eq "AluJb" ) )
  {
    $HitName = "AluJ";
  }
}

sub matchL1frags {
  my $matchit = shift;
  $matchit =~ s/\#.*//;
  unless ( $HitName =~ /_[35]end$/ && $matchit =~ /_orf2$/ ) {
    my ( $ord, $fam, $gen, $spe, $lord, $lfam, $lgen, $lspe );
    if ( $HitName =~ /L1([PM][A-F])(\d*)([a-z]*)/ ) {
      $fam = $1;
      $gen = $2;
      $spe = $3;
    }
    elsif ( $HitName =~ /L1([PM])(\d)/ ) {
      $ord = $1;
      $fam = $2;
    }
    if ( $matchit =~ /L1([PM][A-F])(\d*)([a-z]*)/ ) {
      $lfam = $1;
      $lgen = $2;
      $lspe = $3;
    }
    elsif ( $matchit =~ /L1([PM])(\d)/ ) {
      $lord = $1;
      $lfam = $2;
    }
    if (
      $HitName =~ /$matchit(_)?/
      ||

#the (_)? takes care that L1P4_orf2 etc will merge with L1P4 etc (which is a renamed 3' end)
      $opt_mus && (
           $HitName =~ /L1_Mm(_orf2)?$/ && $matchit =~ /L1Md|L1_Mus|Lx[_2]/
        || $HitName =~ /L1_Rn(_orf2)?$/ && $matchit =~ /L1_R[na]t?|Lx[_2]/
        ||

        # Changed names to include _orf2 apr 14 2004
        # the ()? thing is only for a bit of backward compatibility
           $HitName =~ /L1_Mur1/ && $matchit =~ /Lx[_234]/
        || $HitName =~ /L1_Mur2/ && $matchit =~ /Lx[2-6]/
        || $HitName =~ /L1_Mur3/ && $matchit =~ /Lx[5-8]/
        || $HitName =~ /L1_Rod/  && $matchit =~ /Lx[8-9]/
      )
      ||

      # this gives an error when $lgen was not defined CHECK!
         $fam
      && $lfam
      && $fam eq $lfam
      && ( !$gen || $lgen > $gen - 3 && $lgen < $gen + 3 )
      && (    $HitName =~ /_5end$/
           || !$gen
           || $lgen > $gen - 2 && $lgen < $gen + 2 )
      ||

      # more lenience given to matching 5' ends
         $ord
      && $lord
      && $ord eq $lord
      && ( !$fam || $lfam > $fam - 2 && $lfam < $fam + 2 )
      || $HitName =~ /^L1P\d/
      && (    $HitName =~ /^L1P1/ && $matchit =~ /L1H|PA[2-7]/
           || $HitName =~ /^L1P2/ && $matchit =~ /PA[2-8]/
           || $HitName =~ /^L1P3/ && $matchit =~ /PA[6-9]|PA1[0-3]/
           || $HitName =~ /^L1P4/ && $matchit =~ /PA1[0-7]|PB[23]/
           || $HitName =~ /^L1P5/ && $matchit =~ /PB/ )
      || $HitName =~ /^L1M\d/ && ( $HitName =~ /^L1M1/ && $matchit =~ /MA[1-5]/
                  || $HitName =~ /^L1M2/ && $matchit =~ /MA[4-9]/
                  || $HitName =~ /^L1M3/ && $matchit =~ /MA[89]|MA10|MB[1-5]/
                  || $HitName =~ /^L1M4/ && $matchit =~ /MB[4-8]|ME1|M[CD][345]/
                  || $HitName =~ /^L1M5/ && $matchit =~ /ME[1-4]|M[CD][345]/ )
      || $HitName =~ /^Lx/ && $matchit =~ /^Lx/
        )
    {
      return 1;
    }
    else {
      return 0;
    }
  }
  else {
    return 0;
  }
}

# discarded lines from matchL1 sub
#                 $HitName =~ /^(L1\w+)[a-g]?_5end/ && $lHN =~ /^$1\w/ ||
#                 $HitName =~ /L1P.*5end$/ && $lHN =~ /^L1[HP]\w/ ||
#                 $HitName =~ /L1M[CDE].*5end$/ && $lHN =~ /^L1M[CDE]|^L1M[456]$/ ||
#                 $HitName =~ /orf2$/ && $lHN =~ /orf2$/ ||
#                 $Seq2End < 5430 && ($HitName eq L1M && $lHN =~ /^L1M[ABCDE123456]?/ ||
#                                     $HitName eq L1P && $lHN =~ /^L1[HP][ABS12345]?/) ||
#                 ($Seq2End < 5825 || $Seq2End + $SW < 6165) # latter won't work if fragment attached to longer piece
#                 && ($HitName =~ /L1M[456]/ && $lHN =~ /^L1M[BCDE3456]/ ||
#                     $HitName =~ /L1M[123]/ && $lHN =~ /^L1M[AB1234]/ ||
#                     $HitName =~ /L1M1/ && $lHN =~ /^L1PB|^L1PA1[56]/ ||
#                     $HitName =~ /L1P[45]/ && $lHN =~ /^L1P[AB345]/ ||
#                     $HitName =~ /L1P[123]/ && $lHN =~ /^L1[PH][AS1234]/)))) {
# need to make generic L1MC3/4/5, L1MD3 if Seq2End < 6800 or so

sub Adjustwidths {
  $PctSubst  = sprintf "%4.1f", $PctSubst;
  $PctInsert = sprintf "%4.1f", $PctInsert;
  $PctDelete = sprintf "%4.1f", $PctDelete;
  $widthSW       = length $SW       if $widthSW < length $SW;
  $widthSeq1Name = length $Seq1Name if $widthSeq1Name < length $Seq1Name;
  $widthBeginAlign = length $BeginAlign
      if $widthBeginAlign < length $BeginAlign;
  $widthEndAlign = length $EndAlign if $widthEndAlign < length $EndAlign;
  $widthLeftOver = length $LeftOver if $widthLeftOver < length $LeftOver;
  $widthHitName  = length $HitName  if $widthHitName < length $HitName;

  if ( $HitName =~ /Tigger[34]$|Tigger[34]_/ && $widthHitName < 14 ) {
    $widthHitName = 14;
  }
  $widthclass = length $ClassName if $widthclass < length $ClassName;
  if (    $ClassName eq "Simple_repeat"
       && $HitName =~ /rich|purine|pyrimidin/
       && $widthclass < 14 )
  {
    $widthclass = 14;
  }
  $widthSeq2Begin = length $Seq2BeginPrint
      if $widthSeq2Begin < length $Seq2BeginPrint;
  $widthSeq2End = length $Seq2End if $widthSeq2End < length $Seq2End;
  $widthLeftUnaligned = length $LeftUnalignedPrint
      if $widthLeftUnaligned < length $LeftUnalignedPrint;
  ++$widthID if $widthID < length $id{$ID};
}

#########################################
# formats

format OUTFULL =
@##### @#.# @#.# @#.# @<<<<<<<<<<<<<<<< @######## @######## @>>>>>>> @< @<<<<<<<<<<<<<< @<<<<<<<<<<<<<< @>>>>>> @>>>>>> @>>>>>> @<<<< @>>
$SW, $PctSubst, $PctInsert, $PctDelete, $Seq1Name, $BeginAlign, $EndAlign, $LeftOverPrint, $RevComp, $HitName, $ClassName, $Seq2BeginPrint, $Seq2End, $LeftUnalignedPrint, $printid, $Overlapped
.

format OUTRAW =
@##### @#.# @#.# @#.# @<<<<<<<<<<<<<<<<<<< @######## @######## @>>>>>>> @< @<<<<<<<<<<<<<< @<<<<<<<<<<<<<< @>>>>>> @>>>>>> @>>>>>> @<<
$SW, $PctSubst, $PctInsert, $PctDelete, $Seq1Name, $BeginAlign, $EndAlign, $LeftOverPrint, $RevComp, $HitName, $ClassName, $Seq2BeginPrint, $Seq2End, $LeftUnalignedPrint, $Overlapped
.

format OUTPOLY =
@##### @#.# @#.# @#.# @<<<<<<<<<<<<<<<<<<< @######## @######## @>>>>>>> @< @<<<<<<<<<<<<<< @<<<<<<<<<<<<<< @>>>>>> @>>>>>> @>>>>>> @<<
$SW, $PctSubst, $PctInsert, $PctDelete, $Seq1Name, $BeginAlign, $EndAlign, $LeftOverPrint, $RevComp, $HitName, $ClassName, $Seq2BeginPrint, $Seq2End, $LeftUnalignedPrint, $Overlapped
.

format humanPERCENTTABLE =
==================================================
file name: @<<<<<<<<<<<<<<<<<<<<<<<
$filename
sequences:       @######
$seq_cnt
total length: @######### bp  @<<<<<<<<<<<<<<<<<<<<<<<
$totalSeqLen, $nonNSeqLen
GC level:        @##.## %
$frac_GC
bases masked: @######### bp (@##.## %)
$maskedlength, $maskedpercent*100
==================================================
               number of      length   percentage
               elements*    occupied  of sequence
--------------------------------------------------
SINEs:           @#####    @######## bp   @##.## %
$sinecnt, $sinelength, $sinelength*100/$totseqlen
      ALUs       @#####    @######## bp   @##.## %
$count{"SINE/Alu"}, $totlength{"SINE/Alu"}, $totlength{"SINE/Alu"}*100/$totseqlen
      MIRs       @#####    @######## bp   @##.## %
$count{"SINE/MIR"}, $totlength{"SINE/MIR"}, $totlength{"SINE/MIR"}*100/$totseqlen

LINEs:           @#####    @######## bp   @##.## %
$linecnt, $linelength, $linelength*100/$totseqlen
      LINE1      @#####    @######## bp   @##.## %
$count{"LINE/L1"}, $totlength{"LINE/L1"}, $totlength{"LINE/L1"}*100/$totseqlen
      LINE2      @#####    @######## bp   @##.## %
$count{"LINE/L2"}, $totlength{"LINE/L2"}, $totlength{"LINE/L2"}*100/$totseqlen
      L3/CR1     @#####    @######## bp   @##.## %
$count{"LINE/CR1"}, $totlength{"LINE/CR1"}, $totlength{"LINE/CR1"}*100/$totseqlen

LTR elements:    @#####    @######## bp   @##.## %
$ltrcnt, $ltrlength, $ltrlength*100/$totseqlen
      MaLRs      @#####    @######## bp   @##.## %
$count{"LTR/MaLR"}, $totlength{"LTR/MaLR"}, $totlength{"LTR/MaLR"}*100/$totseqlen
      ERVL       @#####    @######## bp   @##.## %
$count{"LTR/ERVL"}, $totlength{"LTR/ERVL"}, $totlength{"LTR/ERVL"}*100/$totseqlen
      ERV_classI @#####    @######## bp   @##.## %
$count{"LTR/ERV1"}, $totlength{"LTR/ERV1"}, $totlength{"LTR/ERV1"}*100/$totseqlen
      ERV_classII @####    @######## bp   @##.## %
$count{"LTR/ERVK"}, $totlength{"LTR/ERVK"}, $totlength{"LTR/ERVK"}*100/$totseqlen

DNA elements:    @#####    @######## bp   @##.## %
$dnacnt, $dnalength, $dnalength*100/$totseqlen
      MER1_type  @#####    @######## bp   @##.## %
$count{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}*100/$totseqlen
      MER2_type  @#####    @######## bp   @##.## %
$count{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}*100/$totseqlen

Unclassified:    @#####    @######## bp   @##.## %
$othercnt, $otherlength, $otherlength*100/$totseqlen

Total interspersed repeats:@######## bp   @##.## %
$totallength, $totallength*100/$totseqlen


Small RNA:       @#####    @######## bp   @##.## %
$rnacnt, $rnalength, $rnalength*100/$totseqlen

Satellites:      @#####    @######## bp   @##.## %
$satelcnt, $satellength, $satellength*100/$totseqlen
Simple repeats:  @#####    @######## bp   @##.## %
$simplecnt, $simplelength, $simplelength*100/$totseqlen
Low complexity:  @#####    @######## bp   @##.## %
$lowcompcnt, $lowcomplength, $lowcomplength*100/$totseqlen
==================================================

* most repeats fragmented by insertions or deletions
  have been counted as one element
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$exclnote

The query species was assumed to be @<<<<<<<<<<<<<<
$opt_species
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$versionmode
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$engine
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$dbversion
.

format genPERCENTTABLE =
=====================================================
file name: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$filename
sequences:      @#######
$seq_cnt
total length: @######### bp  @<<<<<<<<<<<<<<<<<<<<<<<
$totalSeqLen, $nonNSeqLen
GC level:        @##.## %
$frac_GC
bases masked: @######### bp (@##.## %)
$maskedlength, $maskedpercent*100
=====================================================
                   number of      length   percentage
                   elements     occupied  of sequence
-----------------------------------------------------
Retroelements       @#####    @######## bp   @##.## %
$linecnt+$sinecnt+$ltrcnt,$linelength+$sinelength+$ltrlength, ($linelength+$sinelength+$ltrlength)*100/$totseqlen
   SINEs:           @#####    @######## bp   @##.## %
$sinecnt, $sinelength, $sinelength*100/$totseqlen
   LINEs:           @#####    @######## bp   @##.## %
$linecnt, $linelength, $linelength*100/$totseqlen
    Penelope        @#####    @######## bp   @##.## %
$count{"LINE/Penelope"}, $totlength{"LINE/Penelope"}, $totlength{"LINE/Penelope"}*100/$totseqlen
     CRE/SLACS      @#####    @######## bp   @##.## %
$count{"LINE/CRE"}, $totlength{"LINE/CRE"}, $totlength{"LINE/CRE"}*100/$totseqlen
      L2/CR1/Rex    @#####    @######## bp   @##.## %
$lineCR1cnt, $lineCR1length, $lineCR1length*100/$totseqlen
      R1/LOA/Jockey @#####    @######## bp   @##.## %
$lineIcnt, $lineIlength, $lineIlength*100/$totseqlen
      R2/R4/NeSL    @#####    @######## bp   @##.## %
$lineR2cnt, $lineR2length, $lineR2length*100/$totseqlen
      RTE/Bov-B     @#####    @######## bp   @##.## %
$lineRTEcnt, $lineRTElength, $lineRTElength*100/$totseqlen
      L1/CIN4       @#####    @######## bp   @##.## %
$count{"LINE/L1"}, $totlength{"LINE/L1"}, $totlength{"LINE/L1"}*100/$totseqlen
   LTR elements:    @#####    @######## bp   @##.## %
$ltrcnt, $ltrlength, $ltrlength*100/$totseqlen
     BEL/Pao        @#####    @######## bp   @##.## %
$ltrBELcnt, $ltrBELlength, $ltrBELlength*100/$totseqlen
     Ty1/Copia      @#####    @######## bp   @##.## %
$count{"LTR/Copia"}, $totlength{"LTR/Copia"}, $totlength{"LTR/Copia"}*100/$totseqlen
     Gypsy/DIRS1    @#####    @######## bp   @##.## %
$ltrGYPcnt, $ltrGYPlength, $ltrGYPlength*100/$totseqlen
       Retroviral   @#####    @######## bp   @##.## %
$ltrERVcnt, $ltrERVlength, $ltrERVlength*100/$totseqlen

DNA transposons     @#####    @######## bp   @##.## %
$dnacnt, $dnalength, $dnalength*100/$totseqlen
   hobo-Activator   @#####    @######## bp   @##.## %
$dnaHATcnt, $dnaHATlength, $dnaHATlength*100/$totseqlen
   Tc1-IS630-Pogo   @#####    @######## bp   @##.## %
$dnaTC1cnt, $dnaTC1length, $dnaTC1length*100/$totseqlen
   En-Spm           @#####    @######## bp   @##.## %
$count{"DNA/En-Spm"}, $totlength{"DNA/En-Spm"}, $totlength{"DNA/En-Spm"}*100/$totseqlen
   MuDR-IS905       @#####    @######## bp   @##.## %
$count{"DNA/MuDR"}, $totlength{"DNA/MuDR"}, $totlength{"DNA/MuDR"}*100/$totseqlen
   PiggyBac         @#####    @######## bp   @##.## %
$dnaPIGcnt, $dnaPIGlength, $dnaPIGlength*100/$totseqlen
   Tourist/Harbinger@#####    @######## bp   @##.## %
$dnaHcnt, $dnaHlength, $dnaHlength*100/$totseqlen
   Other (Mirage,   @#####    @######## bp   @##.## %
$dnaPcnt, $dnaPlength, $dnaPlength*100/$totseqlen
    P-element, Transib)

Rolling-circles     @#####    @######## bp   @##.## %
$count{"RC/Helicop"}, $totlength{"RC/Helicop"}, $totlength{"RC/Helicop"}*100/$totseqlen

Unclassified:       @#####    @######## bp   @##.## %
$othercnt, $otherlength, $otherlength*100/$totseqlen

Total interspersed repeats:   @######## bp   @##.## %
$totallength, $totallength*100/$totseqlen


Small RNA:          @#####    @######## bp   @##.## %
$rnacnt, $rnalength, $rnalength*100/$totseqlen

Satellites:         @#####    @######## bp   @##.## %
$satelcnt, $satellength, $satellength*100/$totseqlen
Simple repeats:     @#####    @######## bp   @##.## %
$simplecnt, $simplelength, $simplelength*100/$totseqlen
Low complexity:     @#####    @######## bp   @##.## %
$lowcompcnt, $lowcomplength, $lowcomplength*100/$totseqlen
==================================================

* most repeats fragmented by insertions or deletions
  have been counted as one element
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$exclnote

@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$queryorigin
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$versionmode
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$engine
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$dbversion
.

format mousePERCENTTABLE =
==================================================
file name: @<<<<<<<<<<<<<<<<<<<<<<<
$filename
sequences:       @#####
$seq_cnt
total length: @######### bp  @<<<<<<<<<<<<<<<<<<<<<<<
$totalSeqLen, $nonNSeqLen
GC level:        @##.## %
$frac_GC
bases masked: @######### bp (@##.## %)
$maskedlength, $maskedpercent*100
==================================================
               number of      length   percentage
               elements*     occupied  of sequence
--------------------------------------------------
SINEs:            @#####    @######## bp   @##.## %
$sinecnt, $sinelength, $sinelength*100/$totseqlen
      Alu/B1      @#####    @######## bp   @##.## %
$count{"SINE/Alu"}, $totlength{"SINE/Alu"}, $totlength{"SINE/Alu"}*100/$totseqlen
      B2-B4       @#####    @######## bp   @##.## %
$count{"SINE/B2"}+$count{"SINE/B4"}, $totlength{"SINE/B2"}+$totlength{"SINE/B4"}, ($totlength{"SINE/B2"}+$totlength{"SINE/B4"})*100/$totseqlen
      IDs         @#####    @######## bp   @##.## %
$count{"SINE/ID"}, $totlength{"SINE/ID"}, $totlength{"SINE/ID"}*100/$totseqlen
      MIRs        @#####    @######## bp   @##.## %
$count{"SINE/MIR"}, $totlength{"SINE/MIR"}, $totlength{"SINE/MIR"}*100/$totseqlen

LINEs:            @#####    @######## bp   @##.## %
$linecnt, $linelength, $linelength*100/$totseqlen
      LINE1       @#####    @######## bp   @##.## %
$count{"LINE/L1"}, $totlength{"LINE/L1"}, $totlength{"LINE/L1"}*100/$totseqlen
      LINE2       @#####    @######## bp   @##.## %
$count{"LINE/L2"}, $totlength{"LINE/L2"}, $totlength{"LINE/L2"}*100/$totseqlen
      L3/CR1      @#####    @######## bp   @##.## %
$count{"LINE/CR1"}, $totlength{"LINE/CR1"}, $totlength{"LINE/CR1"}*100/$totseqlen

LTR elements:     @#####    @######## bp   @##.## %
$ltrcnt, $ltrlength, $ltrlength*100/$totseqlen
      MaLRs       @#####    @######## bp   @##.## %
$count{"LTR/MaLR"}, $totlength{"LTR/MaLR"}, $totlength{"LTR/MaLR"}*100/$totseqlen
      ERVL        @#####    @######## bp   @##.## %
$count{"LTR/ERVL"}, $totlength{"LTR/ERVL"}, $totlength{"LTR/ERVL"}*100/$totseqlen
      ERV_classI  @#####    @######## bp   @##.## %
$count{"LTR/ERV1"}, $totlength{"LTR/ERV1"}, $totlength{"LTR/ERV1"}*100/$totseqlen
      ERV_classII @#####    @######## bp   @##.## %
$count{"LTR/ERVK"}, $totlength{"LTR/ERVK"}, $totlength{"LTR/ERVK"}*100/$totseqlen

DNA elements:     @#####    @######## bp   @##.## %
$dnacnt, $dnalength, $dnalength*100/$totseqlen
      MER1_type   @#####    @######## bp   @##.## %
$count{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}*100/$totseqlen
      MER2_type   @#####    @######## bp   @##.## %
$count{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}*100/$totseqlen

Unclassified:     @#####    @######## bp   @##.## %
$othercnt, $otherlength, $otherlength*100/$totseqlen

Total interspersed repeats: @######## bp   @##.## %
$totallength, $totallength*100/$totseqlen


Small RNA:        @#####    @######## bp   @##.## %
$rnacnt, $rnalength, $rnalength*100/$totseqlen

Satellites:       @#####    @######## bp   @##.## %
$satelcnt, $satellength, $satellength*100/$totseqlen
Simple repeats:   @#####    @######## bp   @##.## %
$simplecnt, $simplelength, $simplelength*100/$totseqlen
Low complexity:   @#####    @######## bp   @##.## %
$lowcompcnt, $lowcomplength, $lowcomplength*100/$totseqlen
==================================================

* most repeats fragmented by insertions or deletions
  have been counted as one element
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$exclnote

The query species was assumed to be @<<<<<<<<<<<<<<
$opt_species
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$versionmode
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$engine
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$dbversion
.

format cowPERCENTTABLE =
==================================================
file name: @<<<<<<<<<<<<<<<<<<<<<<<
$filename
sequences:       @#####
$seq_cnt
total length: @######### bp  @<<<<<<<<<<<<<<<<<<<<<<<
$totalSeqLen, $nonNSeqLen
GC level:        @##.## %
$frac_GC
bases masked: @######### bp (@##.## %)
$maskedlength, $maskedpercent*100
==================================================
               number of      length   percentage
               elements*    occupied  of sequence
--------------------------------------------------
SINEs:            @#####    @######## bp   @##.## %
$sinecnt, $sinelength, $sinelength*100/$totseqlen
      Alu/B1      @#####    @######## bp   @##.## %
$count{"SINE/Alu"}, $totlength{"SINE/Alu"}, $totlength{"SINE/Alu"}*100/$totseqlen
      MIRs        @#####    @######## bp   @##.## %
$count{"SINE/MIR"}, $totlength{"SINE/MIR"}, $totlength{"SINE/MIR"}*100/$totseqlen

LINEs:            @#####    @######## bp   @##.## %
$linecnt, $linelength, $linelength*100/$totseqlen
      LINE1       @#####    @######## bp   @##.## %
$count{"LINE/L1"}, $totlength{"LINE/L1"}, $totlength{"LINE/L1"}*100/$totseqlen
      BovB/Art2   @#####    @######## bp   @##.## %
$count{"LINE/BovB"}, $totlength{"LINE/BovB"}, $totlength{"LINE/BovB"}*100/$totseqlen
      LINE2       @#####    @######## bp   @##.## %
$count{"LINE/L2"}, $totlength{"LINE/L2"}, $totlength{"LINE/L2"}*100/$totseqlen
      L3/CR1      @#####    @######## bp   @##.## %
$count{"LINE/CR1"}, $totlength{"LINE/CR1"}, $totlength{"LINE/CR1"}*100/$totseqlen

LTR elements:     @#####    @######## bp   @##.## %
$ltrcnt, $ltrlength, $ltrlength*100/$totseqlen
      MaLRs       @#####    @######## bp   @##.## %
$count{"LTR/MaLR"}, $totlength{"LTR/MaLR"}, $totlength{"LTR/MaLR"}*100/$totseqlen
      ERVL        @#####    @######## bp   @##.## %
$count{"LTR/ERVL"}, $totlength{"LTR/ERVL"}, $totlength{"LTR/ERVL"}*100/$totseqlen
      ERV_classI  @#####    @######## bp   @##.## %
$count{"LTR/ERV1"}, $totlength{"LTR/ERV1"}, $totlength{"LTR/ERV1"}*100/$totseqlen
      ERV_classII @#####    @######## bp   @##.## %
$count{"LTR/ERVK"}, $totlength{"LTR/ERVK"}, $totlength{"LTR/ERVK"}*100/$totseqlen

DNA elements:     @#####    @######## bp   @##.## %
$dnacnt, $dnalength, $dnalength*100/$totseqlen
      MER1_type   @#####    @######## bp   @##.## %
$count{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}, $totlength{"DNA/MER1_type"}*100/$totseqlen
      MER2_type   @#####    @######## bp   @##.## %
$count{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}, $totlength{"DNA/MER2_type"}*100/$totseqlen

Unclassified:     @#####    @######## bp   @##.## %
$othercnt, $otherlength, $otherlength*100/$totseqlen

Total interspersed repeats: @######## bp   @##.## %
$totallength, $totallength*100/$totseqlen


Small RNA:        @#####    @######## bp   @##.## %
$rnacnt, $rnalength, $rnalength*100/$totseqlen

Satellites:       @#####    @######## bp   @##.## %
$satelcnt, $satellength, $satellength*100/$totseqlen
Simple repeats:   @#####    @######## bp   @##.## %
$simplecnt, $simplelength, $simplelength*100/$totseqlen
Low complexity:   @#####    @######## bp   @##.## %
$lowcompcnt, $lowcomplength, $lowcomplength*100/$totseqlen
==================================================

* most repeats fragmented by insertions or deletions
  have been counted as one element
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$exclnote

The query species was assumed to be @<<<<<<<<<<<<<<
$opt_species
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$versionmode
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$engine
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$dbversion
.

package ExtractObjects;

use strict;

sub new {
  my $class = shift;

  my $this = {};
  bless $this, $class;

  # initialize
  my @parse_line;    # list of selected lines from this file
  $this->{'HIT_LIST'} = [];

  #either accepts an array (each cycle)
  if ( $#main::imout >= 0 ) {    #initially @imout is set to (), $#imout is -1
    @parse_line = @main::imout;
    for ( @parse_line ) {
      my $hit = new Hit( $_ );
      push( @{ $this->{'HIT_LIST'} }, $hit );
    }

    # or a .cat file
  }
  else {
    my ( $file ) = @_;
    open( XMATCH, $file ) || die "cannot open $file\n";
    while ( <XMATCH> ) {
      push( @main::catfile, $_ ) if $main::opt_a;
      if ( /^[^\#].+\(\d+\)/ ) {    # only occurs in parse lines
        my $hit = new Hit( $_ );
        push( @{ $this->{'HIT_LIST'} }, $hit );
      }
    }
    close XMATCH;
  }
  return $this;

}    # end parse_cross_match

# when $ref = $objref->getHits(); is called, a reference is returned
# to a list of parsed lines from the cross_match output,
# where $objref was created by $objref = new Xmatch($file);
sub getHits {
  my $this = shift;
  return $this->{'HIT_LIST'};
}

######################################################################

package Hit;

sub new {
  my $class     = shift;    # @_ = (HIT, $parseLine)
  my $parseLine = shift;

  my $this = {};
  bless $this, $class;

  # create a reference for each parsed line, the line
  # is parsed into a list of refs to hashes (LoH)
  $this->addParsedLine( $parseLine );

  return $this;
}

sub addParsedLine {
  my ( $this, $line ) = @_;

  #
  # parse the line passed, the returned refs will correspond to
  # the start and end of a hit, its name and orientation (rel to
  # the first sequence in crossmatch.  the next elements ([4] - [end])
  # will contain the simscore (%match) and start and ending points)
  #

  $this->{'HIT_DATA'} = $line;    # sometimes want the "unparsed" data line

  $line =~ s/^\s+//;
  my @tokens = split( /\s+/, $line );
  $this->{'SW'}        = $tokens[ 0 ];    # smith-waterman score
  $this->{'SUBS'}      = $tokens[ 1 ];    # % substitution (seq1 vs seq2)
  $this->{'INS'}       = $tokens[ 2 ];    # % insertions     ""
  $this->{'DEL'}       = $tokens[ 3 ];    # % deletions      ""
  $this->{'SEQ1NAME'}  = $tokens[ 4 ];    # name of seq1
  $this->{'SEQ1BEG'}   = $tokens[ 5 ];    # beginning of alignment
  $this->{'SEQ1END'}   = $tokens[ 6 ];    # end of alignment
  $this->{'LEFTOVER1'} = $tokens[ 7 ];

  $this->{'MATCH'} = 100 - $this->{'SUBS'};

  if ( $tokens[ 8 ] eq "C" ) {            # the C for complemented seqs
    $this->{'SEQ2NAME'} = $tokens[ 9 ];     # name of seq2
    $this->{'REVCOMP'}  = "C";              # to be added it to the array
    $this->{'LEFTOVER'} = $tokens[ 10 ];    # 3' unaligned portion
    $this->{'SEQ2END'}  = $tokens[ 11 ];    # end of seq2 alignment
    $this->{'SEQ2BEG'}  = $tokens[ 12 ];    # beginning of seq2 alignment
    if ( defined $tokens[ 13 ] ) {
      if ( $tokens[ 13 ] eq '*' ) {
        if ( defined $tokens[ 14 ] ) {
          $this->{'LASTFIELD'} = $tokens[ 14 ];
          $this->{'LINEID'}    = $tokens[ 15 ];
        }
        else {
          $this->{'LASTFIELD'} = 1;         # -nocut option
        }
      }
      else {
        $this->{'LASTFIELD'} = $tokens[ 13 ];
        $this->{'LINEID'}    = $tokens[ 14 ];
      }
    }
    else {
      $this->{'LASTFIELD'} = 1;             # -nocut option
    }
  }
  elsif ( $tokens[ 8 ] eq '+' ) {           # for cycles 1-4
    $this->{'SEQ2NAME'} = $tokens[ 9 ];
    $this->{'REVCOMP'}  = '+';
    $this->{'SEQ2BEG'}  = $tokens[ 10 ];
    $this->{'SEQ2END'}  = $tokens[ 11 ];    #
    $this->{'LEFTOVER'} = $tokens[ 12 ];
    if ( $tokens[ 13 ] eq '*' ) {
      $this->{'LASTFIELD'} = $tokens[ 14 ];
      $this->{'LINEID'}    = $tokens[ 15 ];
    }
    else {
      $this->{'LASTFIELD'} = $tokens[ 13 ];
      $this->{'LINEID'}    = $tokens[ 14 ];
    }
  }
  else {                                    # cross_match output
    $this->{'REVCOMP'}  = '+';
    $this->{'SEQ2NAME'} = $tokens[ 8 ];
    $this->{'SEQ2BEG'}  = $tokens[ 9 ];
    $this->{'SEQ2END'}  = $tokens[ 10 ];
    $this->{'LEFTOVER'} = $tokens[ 11 ];
    if ( defined $tokens[ 12 ] ) {
      if ( $tokens[ 12 ] eq '*' ) {
        if ( defined $tokens[ 13 ] ) {
          $this->{'LASTFIELD'} = $tokens[ 13 ];
        }
        else {
          $this->{'LASTFIELD'} = 1;
        }
      }
      else {
        $this->{'LASTFIELD'} = $tokens[ 12 ];
      }
    }
    else {
      $this->{'LASTFIELD'} = 1;
    }
  }

  # we will return an array with the beginning and end positions
  # of the hit, its name, and its orientation
  $this->{'LEFTOVER'} =~ tr/[()]//d;    # remove flanking "()"
  $this->{'SEQ2LEN'} =
      $this->{'SEQ2END'} + $this->{'LEFTOVER'};    # for "dotplots"
}

# the following methods are used to get the data

# smith-waterman score
sub getSW {
  my $this = shift;
  return $this->{'SW'};
}

sub getScore {
  my $this = shift;
  return $this->{SW};
}

# % substitution (seq1 vs seq2)
sub getPctSubst {
  my $this = shift;
  return $this->{'SUBS'};
}

# leftover sequence of query
sub getLeftOver {
  my $this = shift;
  return $this->{'LEFTOVER1'};
}

# percent match
sub getPctMatch {
  my $this = shift;
  return $this->{'MATCH'};
}

# % insertions (seq1 vs seq2)
sub getPctInsert {
  my $this = shift;
  return $this->{'INS'};
}

# % deletions (seq1 vs seq2)
sub getPctDelete {
  my $this = shift;
  return $this->{'DEL'};
}

# name of sequence 1
sub getSeq1Name {
  my $this = shift;
  return $this->{'SEQ1NAME'};
}

# beginning of alignment
sub getSeq1Beg {
  my $this = shift;
  return $this->{'SEQ1BEG'};
}

# end of alignment
sub getSeq1End {
  my $this = shift;
  return $this->{'SEQ1END'};
}

#len of seq1
sub getSeq1Len {
  my $this = shift;
  return $this->{'SEQ1LEN'};
}

# name of hit (tokens[9])
sub getSeq2Name {
  my $this = shift;
  return $this->{'SEQ2NAME'};
}

# returns the orientation of the hit
sub getRevComp {
  my $this = shift;
  return $this->{'REVCOMP'};
}

# returns beginning of seq 2 alignment
sub getSeq2Beg {
  my $this = shift;
  return $this->{'SEQ2BEG'};
}

# returns end of seq 2 alignment
sub getSeq2End {
  my $this = shift;
  return $this->{'SEQ2END'};
}

# returns length of 3' unaligned portion
sub get3PrimeUnaligned {
  my $this = shift;
  return $this->{'LEFTOVER'};
}

# returns the length of Seq2
sub getSeq2Len {
  my $this = shift;
  return $this->{'SEQ2LEN'};
}

#returns level of condensation of DNA
sub getLastField {
  my $this = shift;
  return $this->{'LASTFIELD'};
}

#returns line ID number
sub getID {
  my $this = shift;
  return $this->{'LINEID'};
}

package main;
