#!/usr/bin/env perl
# evigene/scripts/genoasm/asmlink2refchr.pl

=item about 2303

  evigene/scripts/genoasm/asmlink2refchr.pl
  
  chromosome level scaffolding for chr assembly, using ref chr assembly
  based on chromonomer, with alignments to ref chrs from blastn asm x refchr
  
  includes asm contaminant screen, given contaminant.seq data
  uses gene align table, to keep contigs w/ valid genes
  uses dna cover depth table to classify duplicate contigs as valid or not (from gnodes analyses)
  
  without contam.seq, or gnodes.covtab, or gene aligns, 
    a. links asm contigs to ref chrs, placing all alignable contigs to closest ref chr locus
    b. retains all duplicate region contigs, 
  ie. contigs should be pre-screened or screened here w/ dna depth, contam, genes, to separate
     valid/invalid redundancy
  
=item updates 2303

  add to evg/scripts/genoasm/ gnodes collection
  
  rename: dapblastaln6linkmap, or asmblastaln6linkmap_2303upd.pl 
     >> asm2chrlinkmap.pl scaffold_asm2refchr.pl  asmscaffold2refchr asm2refchr refchrmap ??
  
=item dev about
  
  from dapblastaln6linkmap.pl
  
  work path=     daphmag/gasm20set/dmag20reasm/dmaglinkmap/
  assembly data= daphmag/gasm20set/dmag20reasm/geneval/genome/
              == daphmag/gasm20set/chraln/genome_dmagreasm
  
  see daphmag/gasm20set/dmag20reasm/dmaglinkmap/dmag5nrlink.info

=item 2201 UPD: BUG mis-orient scafs, 
  see large arath22vlr tigs: Chr3 two 10+Mb per Chr, one is wrong dir : blastn/btall  orient is ok :-
  
  bug must be in this sub, translates btall to chromer linkmap format:
    my($nlksam,$linkmap,$samtab)= btall2lksamtab($btall); # make lksamtab,linkmap,sam, SKIPSCAF used
  
  slateeg/chrs/daphplx/gasm20set/gnodes20f/aweed22asm/chrlinkmaps/dmaglinkmap6s/
grep  Chr3 lgdat6v_at22vlr_flyd6ph_asm/l6vat22vlr_flyd6ph_asm-arath22vlrncbi_chr_all.btall
at22vlr_flyd6phs000009	Chr3	26260000	14305064	14305906	14413141	26150454	
  438-14300156/438-14300156	19-14288136:+
at22vlr_flyd6phs000041	Chr3	19758439	10772850	10777567	10858112	26150454	
  1-10773405/1-15459,15958-10773405	
  12749936-12765384,15401478-26150434:-  << proper -orient

>> lksamtab has wrong locs for scaf x chr
>>  sam flag 16 = reverse, BUT parts of s041 are not reversed to match ***
 grep Chr3 lgdat6v_at22vlr_flyd6ph_asm/l6vat22vlr_flyd6ph_asm-arath22vlrncbi_chr_all.lksamtab | grep at22vlr_flyd6phs000041     
Chr3	bcnw_Chr3_12749936_at22vlr_flyd6phs000041	229.49885	12749936	1-251/12749936-12750186	link.41
bcnw_Chr3_12749936_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	1	99	251M	*	0	Xl:i:41
Chr3	bcnw_Chr3_16463198_at22vlr_flyd6phs000041	296.33756	16463198	1077678-1077928/16463198-16463448	link.41
bcnw_Chr3_16463198_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	1077678	99	251M	*	0	Xl:i:41
Chr3	bcnw_Chr3_17540412_at22vlr_flyd6phs000041	315.72742	17540412	2154892-2155142/17540412-17540662	link.41
...
Chr3	bcnw_Chr3_25080910_at22vlr_flyd6phs000041	451.45638	25080910	9695390-9695640/25080910-25081160	link.41
bcnw_Chr3_25080910_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	9695390	99	251M	*	0	Xl:i:41
Chr3	bcnw_Chr3_26158124_at22vlr_flyd6phs000041	470.84623	26158124	10772604-10772854/26158124-26158374	link.41
bcnw_Chr3_26158124_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	10772604	99	251M	*	X

>> all.sam from lksamtab
grep Chr3 lgdat6v_at22vlr_flyd6ph_asm/l6vat22vlr_flyd6ph_asm-arath22vlrncbi_chr_all.sam | grep at22vlr_flyd6phs000041     
bcnw_Chr3_12749936_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	1	99	251M	*	0	Xl:i:41
bcnw_Chr3_16463198_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	1077678	99	251M	*	0	Xl:i:41
bcnw_Chr3_17540412_at22vlr_flyd6phs000041	16	at22vlr_flyd6phs000041	2154892	99	251M	*	0	Xl:i:41

>> arath22vlrncbi_chr_all.linkmap
>> Chr3_1274993..25080910 should be reverse order to linkmap CM col 229..451
Chr3	bcnw_Chr3_12749936_at22vlr_flyd6phs000041	229.49885
Chr3	bcnw_Chr3_16463198_at22vlr_flyd6phs000041	296.33756
Chr3	bcnw_Chr3_17540412_at22vlr_flyd6phs000041	315.72742
Chr3	bcnw_Chr3_18617626_at22vlr_flyd6phs000041	335.11727
Chr3	bcnw_Chr3_19694840_at22vlr_flyd6phs000041	354.50712
Chr3	bcnw_Chr3_20772054_at22vlr_flyd6phs000041	373.89697
Chr3	bcnw_Chr3_21849268_at22vlr_flyd6phs000041	393.28682
Chr3	bcnw_Chr3_22926482_at22vlr_flyd6phs000041	412.67668
Chr3	bcnw_Chr3_24003696_at22vlr_flyd6phs000041	432.06653
Chr3	bcnw_Chr3_25080910_at22vlr_flyd6phs000041	451.45638


----
.. more Chr3 btall
.. small centromere sattelite repeats
at22vlr_flyd6phs000052	Chr3	653800	355855	355873	355764	26150454	1-355764/1-355764	14291420-14646890:+
at22vlr_flyd6phs000115	Chr3	663500	364324	365635	365460	26150454	1-365460/1-365460	14623811-14988929:-
at22vlr_flyd6phs000173	Chr3	256900	140314	140487	148017	26150454	7585-148017/7585-148017	15033744-15174046:+
at22vlr_flyd6phs000337	Chr3	210500	114514	114529	114491	26150454	1-114491/1-114491	15170077-15284503:+
at22vlr_flyd6phs000339	Chr3	62395	33929	33931	33918	26150454	1-33918/1-33918	15473730-15507634:-
at22vlr_flyd6phs000648	Chr3	87255	47487	47490	47462	26150454	1-47462/1-47462	15487359-15534810:+
at22vlr_flyd6phs000925	Chr3	63217	34300	34302	34298	26150454	1-34298/1-34298	15587879-15622166:-
  
  
=item UPD2201 : blastn for highly repetv ie centromer repeats
=item UPD2303 : blastn for highly repetv >> FIXME word_size=200 ONLY FOR hi-ident asm x ref

  UPD2303 this needs to be option, simple switch for hiident vs mid/low ident asm x ref
    eg 
  
  add blast opts
  -word_size 200  # blastn def ws=11 tested 15 30, too low
  -subject_besthit  # should work for this use for best 1 location on subject chrs, cuts down excess dupl hits
  -perc_identity 95 instead of 90 ?

  from arath22vlr asm
  cmd="blastn -task megablast -evalue 1e-14 -subject_besthit -word_size 200 -perc_identity 95  -outfmt 7  -num_threads $NCPU  -db genome/bldb/arath22vlrncbi_chr -query genome/at22vlr_flyd5ph_nocpmt.fa -out l6vat22vlr_flyd5ph_nocpmt-arath22vlrncbi_chr.blastn7test"

=item lgmap5u_ 2020.Oct.26

  chralign data in dmaglinkmap/lkmapbaln/
  lkmap=/Users/gilbertd/Desktop/genoworkb/genomesoft/linkmaps/chromonomer-1.12

  db=dmag15nwblg2r_chrs;  # make sure chr IDs match
  pt=dmag20sk4abyss_lsc; pt=dmag20ug3dabyss; pt=dmag14bgi2vtop5k ; etc ...
  
  gunzip -c genome_dmagreasm/$pt.fa.gz | \
  $nbin/blastn -task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 3 \
    -db genome_dmagreasm/bldb/$db  -outfmt 7  -out $pt-$db.blastn -num_threads 3
  
  $evigene/scripts/makeblastscore3.pl -debug -needlen  -tall -spans=2 -pMINLOW=0.98 \
    -sizes genome_dmagreasm/$pt.facount,genome_dmagreasm/$db.facountx \
    -out $pt-$db.btall $pt-$db.blastn  
  
  btall2lksamtab.pl < $pt-$db.btall >  $pt-$db.lksamtab

  grep  link $pt-$db.lksamtab | sort -k1,1 -k4,4n | cut -f1-3 > $pt-$db.linkmap
  grep -v link $pt-$db.lksamtab > $pt-$db.sam  

  mkdir lgmap5u_$pt

  $lkmap/chromonomer --disable_splitting \
    --map lgdata_$pt/dmag15nwb2r.linkmap  --alns lgdata_$pt/dmag15nwb2r.sam  --agp genome/$pt.agp \
    --out_path lgmap5u_$pt >& lgmap5u.$pt.log
   
=item UPD lgmap6v_ 2020.Nov18

  lgmap6v_ == basic chr asm from best ug/sk asm
  AFTER removing bacteria contam, see daphmag/gasm20set/dmag20reasm/contamug/
  see best table stats in daphmag/gasm20set/dmag20reasm/geneval/alignsum2bone1a.info
  
  indir=daphmag/gasm20set/dmag20reasm/dmaglinkmap/
  dv=l6v
  outdir=lkmapdata$dv; mkdir $outdir;
  cd $outdir; # link data dirs: genome_dmagreasm ..

  db=dmag15nwblg2r_all
  # ^^ change ref seq, vv these are all derived from same dmag15nwb2fullasm.fa.gz
  # .. dmag15nwblgsyn2r_chrr.fa == dmag15nwblg2r_chrs.fa but for IDs,
  # .. dmag15nwblg2r_all.fa adds in scaf/ctg not in chr.fa
  # chraln/genome_dmagreasm/dmag15nwblgsyn2r_chrr.fa.gz@ -> 
  #   ../../dmaglinkmap/lgsyn2r_dmag15nwb2fullasm/CHRR_integrated.fa.gz
  # chraln/genome_dmagreasm/dmag15nwblg2r_chrs.fa.gz@ -> 
  #   ../../dmaglinkmap/lgsyn2r_dmag15nwb2fullasm/dmag15nwblg2r_chrs.fa.gz
  # chraln/genome_dmagreasm/dmag15nwblg2r_all.fa.gz@ -> 
  #   ../../dmag20newasm/asmnew/dmag15nwblg2r_all.fa.gz

 contenders
   orig asm: dmag20bgi(lg/orig), dmag15nwb(lg/orig), dmag19sk,
  new skasm: dmag20sk3baby, dmag20sk4abys_all,  dmag20skspad9k?/poorish
  new ugasm: dmag20ug4lg8i, dmag20ugspad8h?, dmag20ugXmaca

  for pt in dmag14bgi2vtop5k dmag20ugspad4d dmag20sk4abys dmag20ug6maca13ck ; do 
    spt=genome_dmagreasm/$pt-decontam;
    idpt=$pt; # FIXME
  

  gunzip -c $spt.fa.gz | \
  $nbin/blastn -task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 3 \
    -db genome_dmagreasm/bldb/$db  -outfmt 7  -out $dv$pt-$db.blastn -num_threads 3
  
  $evigene/scripts/makeblastscore3.pl -debug -needlen  -tall -spans=2 -pMINLOW=0.98 \
    -sizes $spt.facount,genome_dmagreasm/$db.facount \
    -out $dv$pt-$db.btall $dv$pt-$db.blastn  
  
  btall2lksamtab.pl < $dv$pt-$db.btall >  $dv$pt-$db.lksamtab

  grep  link $dv$pt-$db.lksamtab | sort -k1,1 -k4,4n | cut -f1-3 > $dv$pt-$db.linkmap
  grep -v link $dv$pt-$db.lksamtab > $dv$pt-$db.sam  

  mkdir ../lgmap6v_$pt

  $lkmap/scripts/fasta2agp.py --fasta $spt.fa.gz >  $spt.agp
   ^^this fails now, python bad, replace w/
  $evigene/scripts/genoasm/chrfasta2agp.pl -in $spt.fa -agp $spt.agp

  $lkmap/chromonomer --disable_splitting \
    --map $dv$pt-$db.linkmap  --alns $dv$pt-$db.sam  --agp $spt.agp \
    --out_path ../lgmap6v_$pt >& lgmap.$dv$pt.log

  $evigene/scripts/genoasm/chragp2fasta.pl -debug -idpre $ptid \
    -contigs $spt.fa.gz -agp ../lgmap6v_$pt/CHRR_genome.agp -out ../lgmap6v_$pt/${idpt}_chrs.fa

  $evigene/scripts/genoasm/chragp2fasta.pl -debug -idpre 0  -unplaced \
    -contigs $spt.fa.gz -agp ../lgmap6v_$pt/CHRR_unplaced_scaffolds.agp  -out ../lgmap6v_$pt/${idpt}_unscaf.fa

=item  usage

  export PATH=$nbin:$PATH
  pt=dmag14bgi2vtop5k; idp=dmagbgi6v;
  pt=dmag20sk4abyss; idp=dmagsk4aby6v; # asmname=dmag20sk4abyss_lsc; contamname=dmag20sk4abyss
     env asm=${pt}_lsc contam=contam/$pt-contamb_daphgene.tab ...
     
  env  asm=$pt idpre=$idp \
    ref=dmag15nwblg2r_all refchrs=genome/dmag15nwblg2r_all.chrlist \
    contam=contam/$pt-contamb_daphgene.tab ncpu=4 \
    lkmapbin=$lkmap evigene=$evigene \
    ../dapblastaln6linkmap.pl \
    > lgmap6v.$pt.log

  option: refchrs=genome/dmag15nwblg2r_all.chrlist to keep out ref.scafs
  
   where fasta = genome/$asm.fa.gz, genome/$ref.fa.gz ..
  ENV or PATH?: lkmapbin=pathto/chrmer evigene=$evigene ncbibin/blastn ..
  
=cut

use FindBin;
use lib ("$FindBin::Bin","$FindBin::Bin/.."); # assume evigene/scripts/ layout: main, prot/, rnaseq/, ...
use strict;
use Getopt::Long;

use constant VERSION => '2023.03.30';  
use constant UPD2303 => 1;
use constant NOGENE => 'nogene';
use constant { pMINALN => 25, bMINALN => 1000, }; # decontam

our $EGAPP='asmlink2refchr';  # tr2dgc ?
our $EGLOG='asm2chr';
our $EVIGENES=$ENV{EVIGENES} || $FindBin::Bin; $EVIGENES =~ s,scripts/.*,scripts,;

# UPD2303: drop lkmapbin, expect on PATH
#x my $lkmap=$ENV{lkmapbin}|| "~/bio/apps/linkmaps/chromonomer-1.12"; # FIXME path
# was "/Users/gilbertd/Desktop/genoworkb/genomesoft/linkmaps/chromonomer-1.12";
# my $evigene=$ENV{evigene}||"~/bio/apps/evigene"; # use EVIGENES

# $nbin/blastn ? expect blastn on PATH, also chromonomer ?
my $NCPU = $ENV{ncpu} || 1; #only blast?
my $dv=$ENV{vers}||"l7v"; #UPD2303 was l6v
my $debug=$ENV{debug} || 1; 
my %SKIPSCAF=();
my $REUSE=($ENV{doupdate})?0:1; # reuse step results
my $pMINLOW=$ENV{pminlow}||0.99999; # was 0.98, blast2btall, dont want near-dup aligns here

my $REFCHR_LIST= $ENV{chrlist}||$ENV{refchrs}||""; # rename chrlist
my $ASMDROP_LIST=""; # adds to %SKIPSCAF

my $BL_PIDENT_HI=$ENV{bl_pident_hi}|| 95; #was bl_pident 
my $BL_PIDENT_LO=$ENV{bl_pident_lo}|| 80;
my $BL_WORDSIZE=$ENV{bl_wordsize}|| 200;  # high for highly repetitive crap, def:11

#UPD2303: want -subject_besthit for all? seems to mean only one align-span per ref-chr, but many chrs ok?
my $REF_IDENTITY= $ENV{refident}||""; # ident level of asm x refchr, want GetOpts -refident, could test w/ quick blastn ?
my $blopt_refchrs_hiident="-task megablast -evalue 1e-14 -perc_identity $BL_PIDENT_HI -word_size $BL_WORDSIZE  -subject_besthit ";
my $blopt_refchrs_loident="-task megablast -evalue 1e-9 -perc_identity $BL_PIDENT_LO  -subject_besthit";
my $blopt_refchrs_nonident="-task dc-megablast -evalue 1e-9 -perc_identity $BL_PIDENT_LO  -subject_besthit";

## maybe add wordsize
my $blopt_contam="-task megablast -evalue 1e-9 -perc_identity 80 -culling_limit 3 -soft_masking true -dust yes";

my $ASMchrvers=$ENV{asmvers}||"";
my $idprefix= $ENV{idpre} || ""; 
my $refprefix= $ENV{refpre} || "refchr_"; 
# for blast2contam if no contamtab .....
my $contamtab= $ENV{contamtab}||$ENV{contam}||"";
my $contamfa= $ENV{contamfa}||$ENV{contamdb}||""; 
my $genealigntab= $ENV{genealign}||""; 
  # UPD2303: $genealigntab expected is gmap.align.tab (evg out), need other formats? gnodes.sumgenetab?

my($refchrs, $asm, $ingenexf, $ingenealign, $inrefblast, $output, $logfile);

my @ARGSAVE=@ARGV;
my %opts= (
  "asm|assembly|contigs=s", \$asm, # require
  "chrasm|refchr|chromosomes=s", \$refchrs, # require 
  "genexcopy=s", \$ingenexf, # opt
  "genealigntab=s", \$genealigntab, # opt
  "contamtab=s", \$contamtab, # opt
  "contamdb|contamfa=s", \$contamfa, # opt
  "asmversion=s", \$ASMchrvers, # opt

  "arefblast|arefbtall=s", \$inrefblast, # opt
 
  # "refids=s", \$refids, # opt 
  # "ALIGNER=s", \$ALIGNER, # opt 
  # "outname|output=s", \$output, # opt
  "idprefix=s", \$idprefix, # opt
  "refprefix=s", \$refprefix, # opt
  "refidentity=s", \$REF_IDENTITY, # opt
  "chrlist=s", \$REFCHR_LIST, # opt
  "asmdroplist=s", \$ASMDROP_LIST, # opt
 
  "reuse!", \$REUSE, # $ENV{doupdate} == noREUSE
  "logfile:s", \$logfile, # option
  "PIDENT_LO=i", \$BL_PIDENT_LO,  
  "PIDENT_HI=i", \$BL_PIDENT_HI,  
  "NCPU=i", \$NCPU, # "MAXMEM=i", \$MAXMEM,  
  "debug!", \$debug, 
);

my $optok= GetOptions(%opts);
my $optlist= ($debug) ? "All opts: ".join(", ",sort keys %opts) : "";

die "EvidentialGene $EGAPP, VERSION ",VERSION,"
  chromosome level scaffolding for chr assembly, using ref chr assembly
  based on chromonomer, with alignments to ref chrs from blastn asm x refchr
  
usage: $EGAPP -assembly myasm.fa -refchr myrefchr.fa  
options: 
  -contamdb contam.fa 
  -genexcopy gnodes_genedna.genexcopy
  -genealign genealign.tab or gnodes_genedna.sumgenetab ??
  -arefblast asm-refchr.blastn or .btall input
  
requires apps: 
  chromonomer [url]
  ncbi blastn 
     
" unless($optok and $asm and $refchrs);

#-----------------------------------

sub MAINstub {}

my($REFchrs,$REFfasta)= asmfasta( $refchrs || "none"); # dmag15nwblg2r_all
my($ASMname,$ASMfasta)= asmfasta( $asm);

$idprefix= substr($ASMname,0,8) unless($idprefix);
$idprefix.="_" unless($idprefix=~/_/);
$ASMchrvers= "$refprefix$dv" unless($ASMchrvers); # l6v or dmag15nwb_l6v refprefix?

my $blopt_refchrs= 
  ($REF_IDENTITY =~ m/hi|same|equal|^9[56789]/i) ? $blopt_refchrs_hiident 
  :  ($REF_IDENTITY =~ m/dist|dif/i)? $blopt_refchrs_nonident 
  :  $blopt_refchrs_loident; # default, use opt

# opt to input this: $refblout="$aname-$refna.blastn";
#  .. or this:  $refbtall="$aname-${refna}_chrs.btall"; 
#    (my $btall=$blout) =~ s/\.blast\w+//; $btall.=  ($is_refchrs) ? "_chrs.btall" : "_all.btall";

my($nblast,$refblout,$nbtall,$refbtall)=(0) x 9;
if($inrefblast and -s $inrefblast) {
  if($inrefblast =~ /btall/){ $refbtall=$inrefblast; $nbtall=1; } else { $refblout=$inrefblast; $nblast=1; }
}

unless($REUSE and $refbtall) {
  unless($REUSE and $refblout) {
  ($nblast,$refblout)= blast2refchrs( $ASMname, $ASMfasta, $REFfasta); # out to $dv$pt-$db.blastn
  die "FAIL: blast2refchrs( $ASMname, $ASMfasta, $REFfasta)" unless($nblast>0);
  }
  
  ($nbtall,$refbtall)= blasto2btall($refblout,$ASMfasta, $REFfasta, $REFCHR_LIST); # fa > facount needef for btall
  die "FAIL: blasto2btall($refblout,$ASMfasta, $REFfasta, $REFCHR_LIST)" unless($nbtall>0);
}

# FIXME : use orig $ASMfasta, AND contam.table w/ BACT contam ids + Dmag Gene aligns
#   add gene alings with REFfasta align as keep score, bact contam as drop score
#?? add input $ASMname-contam.blastn + $ASMname-refgenes.align.tab 
#   and classify asmscafs by contam vs refdna+refgenes
#>> Insert step here: remove bact-contam minus ok(refalign,genealign) from ASMfasta
# set SKIPSCAF{$sc}, asmok == ASMfast if no contam
# CHANGE decontam() to use blout not btall

if($ASMDROP_LIST and -s $ASMDROP_LIST) {
  my ($ok,$inh)= openRead($ASMDROP_LIST); 
  while(<$inh>){ next if(/^\W/); my ($sid)=split; $SKIPSCAF{$sid}=1; } close($inh);
}

if( $contamfa and not ($contamtab and -s $contamtab)) {
  my($nconbl,$ctabnew,$conblout)= blast2contam($ASMname,$ASMfasta,$contamtab,$contamfa,$genealigntab);
  $contamtab= $ctabnew if($nconbl);
}

my($nok,$ncon,$asmok,$asmcon)= decontam( $contamtab, $refblout, $ASMfasta, $REFfasta); # NOT now  $refbtall, 
die "FAIL: decontam( $contamtab, $refblout, $ASMfasta, $REFfasta)" unless($nok>0);

# inserthere fix: asmok has added refchr align annot (even if no contam?)
# replaces asmok w/ annotated asmok
my($nan)= addannots($asmok, $refblout, $ASMfasta, $REFfasta);

my($nlksam,$linkmap,$samtab)= btall2lksamtab($refbtall); # make lksamtab,linkmap,sam, SKIPSCAF used
die "FAIL: btall2lksamtab($refbtall)" unless($nlksam>0);

my($nchrs, $chrdir) = runchromer($linkmap,$samtab,$ASMname,$asmok);
die "FAIL: runchromer($linkmap,$samtab,$ASMname,$asmok)" unless($nchrs>0);

my($nfa,$chrfa,$unplfa) = makechrfasta($idprefix,$chrdir,$asmok); # $idpre,$chrdir,$asmfasta
die "FAIL: makechrfasta($idprefix,$chrdir,$asmok)" unless($nfa>0);

#------- end MAIN

# FIXME: REFCHR_LIST now used as filter in btall2lksamtab() before runchromer() to block ref-scafs
# but if want most asm tied to ref-chr, need this filter at blast2refchrs, or else blasto2btall
#  to reduce aligns to non-chr ref-scafs.
# OR just supply REFchrs=ref-chr.fasta, no unplaced ref-scafs
# value of REF-scafs is for decontam(), to keep asm-scafs w/ ref align and contam align
# ie, want both, diff uses

sub asmfasta { 
  my($aname)=@_; my($afa);
  if($aname =~ m/\.fa/) { $afa=$aname; $aname=~s/\.fa.*$//; $aname =~s,^.*/,,; }
  else { $afa="genome/$aname.fa"; $afa.=".gz" unless(-f $afa); }
  unless(-f $afa) { die "# MISSING fasta of $aname : $afa\n"; } # fixme need help, getOpts
  return($aname,$afa);
}

sub runcmd { my($c)=@_; warn "#cmd=$c\n" if($debug);  `$c`; } # or system($c) or `$c` ?
sub returndbg { warn "#ret=@_\n" if($debug); return @_; }
sub openRead { my($f)=@_; my ($ok,$inh); 
  if($f=~m/.gz$/){ $ok=open($inh,"gunzip -c $f|"); } else { $ok=open($inh,$f); }
  return($ok,$inh); }
sub fasize {  
  my ($fa,$otab)=@_; my ($ns,$sw,$id,$len)=(0) x 9;
  my($ok,$hin)= openRead($fa); return($ns,$sw) unless($ok);
  rename($otab,"$otab.old") if(-f $otab); open(OUT,">$otab");
  while(<$hin>) { 
    if(/^>(\S+)/){ print OUT "$id\t$len\n" if($id); $id=$1; $sw+=$len; $len=0; $ns++; }
    else { $len += (length($_) - 1); } 
  }
  print OUT "$id\t$len\n" if($id);
  close($hin); close(OUT);
  return ($ns,$sw); 
}

=item blast2contam

  ($ncon,$contamtab,$blout)= blast2contam($aname,$asmfa,$contamtab,$contamfa,$genealigntab) 

  from daphmag/gasm20set/dmag20reasm/contamug/contamugbact.info
  
  env asm=dmag15nwb2asm.fa  pident=80 datad=`pwd` qsub -q debug run_contamblast.sh
  
  gunzip -c ${pt}_dmag20ug4contambact80i.blastn.gz | perl -ne ..  > ${pt}-contambacb.tab
   
  perl -ne xxx   ../geneval/$pt-dmag14t1cds.align.tab $pt-contambacb.tab    > $pt-contamb_daphgene.tab

=cut

sub blast2contam {
  my($aname,$asmfa,$contamtab,$contamfa,$genealigntab)=@_; #? $contamtab also
  my $MINW=500; my $pMINA=0.33; #? global opts
  my $GMINCOV=20; my $GMINALN=120;
  
  (my $refdb=$contamfa) =~ s/\.fa.*//;
  my($refdir,$refna) = $refdb =~ m,^(.+)/(\w[^\/]+),;
  #? refna = "contamdb";
  warn "#blast2contam: MISSING refgenes.align.tab\n" unless(-s $genealigntab);
  
  # env asm=dmag15nwb2asm.fa  pident=80 datad=`pwd` qsub -q debug run_contamblast.sh
  my $blopt= $blopt_contam; # "-task megablast -evalue 1e-9 -perc_identity 80 -culling_limit 3 -soft_masking true -dust yes";

  my $blout="$aname-$refna.blastn"; # drop $dv
  unless($contamtab){ ($contamtab=$blout) =~ s/.blastn/.contab/; }
  if( -s $contamtab ) { return(1,$contamtab,$blout) if($REUSE); }
  
  unless( -s "$refdb.nsq") {
    my $CAT=($contamfa =~ /.gz/) ? "gunzip -c": "cat";    
    runcmd("$CAT $contamfa | makeblastdb -dbtype nucl -title $refna -out $refdb -logfile /dev/null");
  }
  
  my $CAT=($asmfa =~ /.gz/) ? "gunzip -c": "cat";    
  runcmd("$CAT $asmfa | blastn $blopt -num_threads $NCPU -db $refdb  -outfmt 7 -out $blout");
  unless(-s $blout){ return(0,$contamtab,$blout); }

  local(*OUT);
  
  # FIXME: load in genes.align.tab if avail, add OUT col: $ng.gene,$gspanb-$gspane
  # UPD2303: $genealigntab is gmap.align.tab (evg out), need other formats?
  our($ngene,%genes)=(0);
  if($genealigntab) {
    my($ok,$inh)= openRead($genealigntab);
    while(<$inh>){ next if(/^\W|^Genome/); my @v=split;
      my($sc,$sbe,$so,$tid,$tlen,$cov,$pid,$nex)= @v[0,1,2,3,6,7,8,11]; 
      my $ok=($cov >= $GMINCOV or $tlen*$cov/100 >= $GMINALN); 
      if($ok){ $ngene++; $genes{$sc} .= "$sbe;"; } #? only need $sbe list below
      # if($ok){ $ngene++; $genes{$sc} .="$sbe,$tid,$tlen,$cov;"; } #? only need $sbe list below
    } close($inh);
    
    for my $sc (sort keys %genes) {
      my($gsb,$gse,$ngn)=(0,0,0); 
      for my $sbe (split";",$genes{$sc}) {
        my($sb,$se)=split"-",$sbe; $ngn++;
        $gsb=$sb if($sb<$gsb or $gsb==0); $gse=$se if($se>$gse); 
        }
      $genes{$sc}= "$ngn.gene,$gsb-$gse"; # condensed info for contamtab
    }
  }
  
  our($tsw,$ttal,$tn)= (0) x 9;
  sub puth { 
    my($sid,$sw,$trd,$tal,$tsb,$tse)=@_;
    our($ngene,%genes); our($tsw,$ttal,$tn);
    return unless($sid and $tal and $trd);
    my $tsp=$tse-$tsb; $tal=$tsp if($tsp<$tal); 
    my $pal=($sw>1)?int(100*$tal/$sw):0; 
    
    if($sw>=$MINW and $tal>= $pMINA* $sw) {  
      my $genes= ($ngene == 0) ? "na" : ($genes{$sid} || NOGENE);
      print OUT join("\t",$sid,$sw,$trd,"$pal%,$tal/$tsb-$tse",$genes)."\n";
      $tsw+=$sw; $ttal+=$tal; $tn++; 
    } 
  } 

  my($sid, $sw,$trd,$tal,$tsb,$tse)= (0) x 9;
  open(IN,$blout); open(OUT,">$contamtab");
  while(<IN>) {
    if(/^# Query: (\S+)/){ puth($sid,$sw,$trd,$tal,$tsb,$tse) if($trd and $tal); 
      $sid=$1; ($sw)=m/(?:length|len)=(\d+)/; unless($sw){ $sw=($sid =~ /LG/)?999999:1999; }  
      $trd=$tal=0; $tsb=$tse=0; 
    } elsif(/^\w/){  my @v=split;
      my($sc,$rd,$pi,$al)=@v; my($sb,$se)=@v[6,7]; my $aok=0; 
      if($trd){ if($rd eq $trd){ $aok=1; } } else { $trd=$rd; $aok=1; } 
      if($aok){ $tal+=$al; $tsb=$sb if($sb<$tsb or $tsb==0); $tse=$se if($se>$tse); } 
    } 
  } 
  puth($sid,$sw,$trd,$tal,$tsb,$tse) if($trd and $tal); 
  
  my($mb,$mba)=map{ int($_/100_000)/10; } ($tsw,$ttal); 
  print OUT "# contam n=$tn, mb=$mb, mbal=$mba for MINW=$MINW, pMINA=$pMINA\n";  
  warn "#blast2contam n=$tn, mb=$mb, mbal=$mba for MINW=$MINW, pMINA=$pMINA\n";  
  close(IN); close(OUT);  
  
  returndbg(1,$contamtab,$blout);
}


=item decontam

  -- add: ($ncont,$contamtab)= blast2contam($asmfa,$contamfa);
  -- but, want also to add genes.align.tab 
input this sort of table: bact-contam, contamspan, daphgene-spans
and add blastout/btall align to ref
dmag20ug6maca13ck-contamb_daphgene.tab
dmag20ug6maca13v_ctg91883	3127	CP037867.1	99%,3117/10-3127	18.gene,10-3003
dmag20ug6maca13v_ctg112271	547	CP011774.1	99%,544/3-547	nogene
dmag20ug6maca13v_ctg114801	524	CP011774.1	99%,523/1-524	2.gene,10-174
dmag20ug6maca13v_ctg118415	2305	CP011774.1	99%,2304/1-2305	nogene

=cut

sub decontam {
  my($contamtab,$asmrefblast,$asmfa,$reffa)=@_;
  # my($asmfa,$contamtab,$asmrefblast,$reffa)=@_;
  my $asmrefbtall="nonesuch"; # no longer use: 
  
  unless($contamtab and -s $contamtab){
    warn( "decontam: no contam.table \n") if($debug);
    return(1,0,$asmfa);  
  }
  
  my(%contam,%contamids); 
  my ($nyes,$nno,$nmaybe)=(0) x 9; 
  open(IN,$contamtab);
  while(<IN>) { next if(/^\W/); my @v=split;
    my($sc,$sw,$bacid,$bacaln,$genes)=@v;
    # $genes="" if($genes eq NOGENE); # was bug "nogenes" vs "nogene", OR $genes="" unless($genes=~/\d+.gene/); ???
    $genes=0 unless($genes =~ m/^\d/); # 20.gene,4621-7417 now
    my($pbaln,$baln,$bb,$be)= split /[,\/\-]/, $bacaln;
    my $cclass="na";
    if ($pbaln >= pMINALN or $baln >= bMINALN) {
      if($genes>0){ $nmaybe++; $cclass="maybe"; } # check span overlaps?
      else { $nyes++; $cclass= "yes"; }
    } else{ $nno++; $cclass="no"; }
    $contam{$sc}{cla}= $cclass; 
    $contam{$sc}{val}= "$bacid $bacaln $genes";
    $contamids{$sc}= $cclass if($cclass ne "no");
  } close(IN);  
  
  my($asmcon,$asmok)=("","");
  my($ncon,$nok,$mbcon,$mbok,$iscon)=(0) x 9;
  $asmok=$asmfa; # for 0 yes
  if($nyes or $nmaybe) {
    if( -s $asmrefblast ) {
      my($nbt,$conbtall)= blasto2btall_decon($asmrefblast,$asmfa,$reffa,\%contamids);
      if($nbt){
      open(IN,$conbtall);
      while(<IN>) { next if(/^\W/); my @v=split;
        my($sc,$refid,$bits,$idaln,$aln,$sclen,$reflen,@spans)=@v;
        next unless(exists $contam{$sc}); # or $contamids{$sc}
        #  change for reflen < sclen? 
        my $alen= ($reflen<$sclen and $reflen>0)? $reflen : $sclen;
        my $paln= ($alen>0)? int(100*$aln/$alen) : 0;
        
        $contam{$sc}{val} .= " refchr:$paln%,$aln,$refid"; # add this if any hit
        if($aln >= bMINALN or $paln >= pMINALN) {
          my $oc= $contam{$sc}{cla}; 
          if($oc eq "yes"){ $contam{$sc}{cla}="maybe"; $nyes--; $nmaybe++; }
          # $contam{$sc}{val} .= " refchr:$paln%,$aln,$refid"; # add this if any
        }
      } close(IN);
      }
    }
    
    # set global SKIPSCAF{$sc}, asmok == ASMfast if no contam
    #UPD2303 off: %SKIPSCAF=(); #? dont reset in case others set this?
    map{ $SKIPSCAF{$_}= ($contam{$_}{cla} eq 'yes')?1:0 } sort keys %contam;
    
    # here: separate asmfa into contam/nocon/?maybe subsets, with header flags
    ($asmcon=$asmfa)=~s/\.fa[\w\.]*$//; $asmcon.="-contam.fa"; # save old?
    ($asmok=$asmfa) =~s/\.fa[\w\.]*$//; $asmok .="-clean.fa";
    my($outcon,$outok,$outh);
    my($ok,$inh)= openRead($asmfa);
    open($outcon,">$asmcon"); open($outok,">$asmok"); $outh=$outok;
    while(<$inh>) {
      if(/^>(\S+)/) { my $sc=$1; my $val="";
        my $oc= $contam{$sc}{cla}||"no"; $iscon=0;
        if($oc eq "yes") { $val="contam:".$contam{$sc}{val}; 
          $outh=$outcon; $ncon++; $iscon=1; }
        elsif($oc eq "maybe") { $val="maybecon:".$contam{$sc}{val}; $outh=$outok; $nok++; }
        else { $val="clean"; $outh=$outok; $nok++;} # default all if($ok eq "no") 
        $val=~s/\s+/:/g; s/$/ valid=$val;/;
      } else {
        if($iscon){ $mbcon += length($_)-1; } else { $mbok += length($_)-1; }
      }
      print $outh $_;
    } close($inh);
    close($outcon); close($outok);
    ($mbok,$mbcon)= map{ int($_/100_000)/10 } ($mbok,$mbcon);
  }
  
  warn "#decontam: $asmfa TO nok=$nok,$mbok.M,$asmok; ncon=$ncon,$mbcon.M,$asmcon \n" if($debug);
  return($nok,$ncon,$asmok,$asmcon); #? %contam or return idlist ?
}


=item runchromer

  mkdir ../lgmap6v_$pt
  $lkmap/scripts/fasta2agp.py --fasta $spt.fa.gz >  $spt.agp
  $lkmap/chromonomer --disable_splitting \
    --map $dv$pt-$db.linkmap  --alns $dv$pt-$db.sam  --agp $spt.agp \
    --out_path ../lgmap6v_$pt >& lgmap.$dv$pt.log

=cut

sub runchromer {
  my($linkmap,$alignsam,$asmname,$asmfasta)=@_;
  
  #  --scaffold_wl <path>: only process scaffolds in this file.
  #   ^^ use this opt to keep only ref chr, skip ref contigs ?
  my $cmeropts=" --disable_splitting ";
  #NO: if($REFCHR_LIST) { $cmeropts .= " --scaffold_wl $REFCHR_LIST"; }
  # scaffold_wl is for asmfasta not ref
  
  #my $chrdir="lgmap6v_$asmname";
  my $chrdir='lgmap'.$dv.'_'.$asmname; 

  (my $asmpath=$asmfasta) =~ s/\.fa.*//;
  mkdir( $chrdir);
  unless( $REUSE and -s "$asmpath.agp" ) {
  #old.bad: runcmd("$lkmap/scripts/fasta2agp.py --fasta $asmfasta >  $asmpath.agp");
  runcmd("$EVIGENES/genoasm/chrfasta2agp.pl -in $asmfasta -agp $asmpath.agp");
  }
  #UPD2303: drop $lkmap/chromr, use PATH
  runcmd("chromonomer $cmeropts --map $linkmap --alns $alignsam --agp $asmpath.agp --out_path $chrdir");
  
  # cleanup logs:  
  #  find $chrdir/ -name '[dC]*.log' | gnutar -cf $chrdir/dclogs.tar -T -; 
  #  find $chrdir/ -name '[dC]*.log' -delete
  
  returndbg(1, $chrdir);
}


=item makechrfasta
  $evigene/scripts/genoasm/chragp2fasta.pl -debug -idpre $ptid \
    -contigs $spt.fa.gz -agp ../lgmap6v_$pt/CHRR_genome.agp -out ../lgmap6v_$pt/${idpt}_chrs.fa

  $evigene/scripts/genoasm/chragp2fasta.pl -debug -idpre 0  -unplaced \
    -contigs $spt.fa.gz -agp ../lgmap6v_$pt/CHRR_unplaced_scaffolds.agp  -out ../lgmap6v_$pt/${idpt}_unscaf.fa
  
  UPD: add chrscaf.fa output, ie orig scafs that are in CHRR_genome.agp

=cut

sub makechrfasta {
  my($idpre,$chrdir,$asmfasta)= @_;
  
  # ugh: 
    #cmd=$evigene/scripts/genoasm/chragp2fasta.pl -debug -idpre lgmap6v_dmag14bgi2vtop5k -contigs  -agp genome/dmag14bgi2vtop5k-clean.fa/CHRR_genome.agp -out genome/dmag14bgi2vtop5k-clean.fa/lgmap6v_dmag14bgi2vtop5k_chrs.fa
    #ret=1 genome/dmag14bgi2vtop5k-clean.fa/lgmap6v_dmag14bgi2vtop5k_chrs.fa genome/dmag14bgi2vtop5k-clean.fa/lgmap6v_dmag14bgi2vtop5k_unscaf.fa
 
  # chragp2fasta needs opt to place header info: eg: asmvers=$vers$ASMname
  my $cfopts="-debug";
     $cfopts .=" -addhead vers=$ASMchrvers" if($ASMchrvers);
  
  runcmd("$EVIGENES/genoasm/chragp2fasta.pl $cfopts -idpre $idpre -contigs $asmfasta -agp $chrdir/CHRR_genome.agp -out $chrdir/${idpre}chrs.fa");
  runcmd("$EVIGENES/genoasm/chragp2fasta.pl $cfopts -unplaced -idpre 0 -contigs $asmfasta -agp $chrdir/CHRR_unplaced_scaffolds.agp -out $chrdir/${idpre}unscaf.fa");
  #UPD: add chrscaf.fa output, ie orig scafs in CHRR_genome.agp, with -unplaced == scaf.fa output instead of chr.fa
  runcmd("$EVIGENES/genoasm/chragp2fasta.pl $cfopts -unplaced -idpre 0 -contigs $asmfasta -agp $chrdir/CHRR_genome.agp -out $chrdir/${idpre}chrscaf.fa");

  returndbg(1, "$chrdir/${idpre}chrs.fa","$chrdir/${idpre}unscaf.fa","$chrdir/${idpre}chrscaf.fa");
}

=item blast2refchrs
  gunzip -c $spt.fa.gz | \
  $nbin/blastn -task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 3 \
    -db genome_dmagreasm/bldb/$db  -outfmt 7  -out $dv$pt-$db.blastn -num_threads 3
=cut

sub blast2refchrs {
  my($aname,$asmfa,$reffa)=@_;
  
  (my $refdb=$reffa) =~ s/\.fa.*//;
  my($refdir,$refna) = $refdb =~ m,^(.+)/(\w[^\/]+),;
  
  my $blout="$aname-$refna.blastn"; # drop $dv
  # FIXME: dont -cull?, want many dup hits, filter 2 ways: a. ref-chr only for chromer, b. best spans for decontam
  # or else wider -culling_limit 5..10 ?
  #o my $blopt="-task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 3 -outfmt 7 ";
  #o2: my $blopt="-task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 6 -outfmt 7 ";
  #above: $blopt_refchrs="-task megablast -evalue 1e-14 -perc_identity $BL_PIDENT -word_size $BL_WORDSIZE  -subject_besthit -outfmt 7 ";
  
  my $blopt=$blopt_refchrs; # UPD2303, remove -outfmt, opt for hi/lo/non-ident 
    # "-task megablast -evalue 1e-14 -perc_identity $BL_PIDENT -word_size $BL_WORDSIZE  -subject_besthit -outfmt 7 ";

  if( $REUSE and -s $blout ) { return(1,$blout); } # dang: returndbg(x) doesnt actually return from this sub..
  
  unless( -s "$refdir/bldb/$refna.nsq") {
    my $CAT=($reffa =~ /.gz/) ? "gunzip -c": "cat";    
    runcmd("$CAT $reffa | makeblastdb -dbtype nucl -title $refna -out $refdir/bldb/$refna -logfile /dev/null");
  }
  
  my $CAT=($asmfa =~ /.gz/) ? "gunzip -c": "cat";    
  runcmd("$CAT $asmfa | blastn $blopt -num_threads $NCPU -db $refdir/bldb/$refna  -outfmt 7 -out $blout");
  returndbg(1,$blout);
}

# inserthere fix: asmok has added refchr align annot (even if no contam?)
#  ($asmok)= addannots($asmok) # my($nbtalla,$btallall)= blasto2btall($blout,$ASMfasta, $REFfasta,"all"); # fa > facount needef for btall
sub addannots {
  my($asmok,$refblout,$ASMfasta, $REFfasta)= @_;
  
  my($nbtalla,$btallall)= blasto2btall($refblout, $ASMfasta, $REFfasta,"all");
  return 0 unless($nbtalla);
  my($nani,$nano,%annot)=(0,0);
  open(IN,$btallall); 
  while(<IN>){ next if(/^\W/);  my @v=split;
    my($td,$rd,$bs,$ida,$aln,$tw,$rw,$tspan,$rspan)=@v; next if($annot{$td});
    my $mw=($tw>$rw)?$rw:$tw; my $pal=($mw>0)?int(0.5+100*$aln/$mw):0;
    $annot{$td}= "refaln=$pal%,$aln,$rd"; $nani++; # rspan? drop pal% ?
  } close(IN);
    
  my $asmnew= $asmok.".anntmp";
  my $ok= open(IN,$asmok); return unless($ok);
  open(OUT,">$asmnew") or return 0;
  while(<IN>){ if(/^>(\S+)/){ if(my $an=$annot{$1}) { s/$/ $an;/; $nano++; } } print OUT $_; }
  close(IN); close(OUT);
  rename($asmok,"$asmok.old"); # or delete
  rename($asmnew,$asmok);
  returndbg(1,$nano,$asmok);
}

=item blasto2btall
  $evigene/scripts/makeblastscore3.pl -debug -needlen  -tall -spans=2 -pMINLOW=0.98 \
    -sizes $spt.facount,genome_dmagreasm/$db.facount \
    -out $dv$pt-$db.btall $dv$pt-$db.blastn  
=cut

sub blasto2btall {
  my($blout,$asmfa,$reffa,$reflistOrAll)= @_;
  
  my $is_refchrs=($reflistOrAll and $reflistOrAll ne 'all' and -s $reflistOrAll)?1:0; 
  
  my $btopt="-debug -needlen  -tall -spans=2 -pMINLOW=$pMINLOW";
  (my $btall=$blout) =~ s/\.blast\w+//; $btall.=  ($is_refchrs) ? "_chrs.btall" : "_all.btall";
  return(1,$btall) if($REUSE and -s $btall);
  
  # FIXME: want ref-chr.facount here, subset of reffa, to limit chrmer to ref-chr only
  # REFCHR_LIST=genome/dmag15nwblg2r_all.chrlist == facount for only chrs
  my($asmc,$refc)= map{ (my $na=$_) =~ s/\.fa.*$/.facount/; $na; } ($asmfa,$reffa);
  $refc= $reflistOrAll if($is_refchrs);  # assume: chrid size table
  unless(-f $asmc) { fasize($asmfa,$asmc); }
  unless(-f $refc) { fasize($reffa,$refc); }
  
  runcmd("$EVIGENES/makeblastscore.pl $btopt -sizes $asmc,$refc -out $btall $blout");
  returndbg(1,$btall);
}

sub blasto2btall_decon {
  my($blout,$asmfa,$reffa,$contamscafs)= @_;
  
  my $btopt="-debug -needlen  -tall -spans=2 -pMINLOW=$pMINLOW";
  (my $btall=$blout) =~ s/\.blast\w+//; $btall.="_decon.btall";
  return(1,$btall) if($REUSE and -s $btall);
  
  my($asmc,$refc)= map{ (my $na=$_) =~ s/\.fa.*$/.facount/; $na; } ($asmfa,$reffa);
  unless(-f $asmc) { fasize($asmfa,$asmc); }
  unless(-f $refc) { fasize($reffa,$refc); }
  if(ref $contamscafs) {
    (my $asmdec=$asmc) =~ s/\.\w+$//; $asmdec.="-contam.facount";
    open(F,$asmc); open(O,">$asmdec");
    while(<F>){ my($sc,$slen)=split; if($contamscafs->{$sc}) { print O $_; } } 
    close(F); close(O);
    $asmc=$asmdec;
  }
  runcmd("$EVIGENES/makeblastscore.pl $btopt -sizes $asmc,$refc -out $btall $blout");
  returndbg(1,$btall);
}

sub btall2lksamtab {
  my($btall)=@_;
  
  my $TAG=$ENV{tag}||"bcnw"; my $CB2CM=$ENV{cb2cm}|| 0.000018;
  my $MAXN=$ENV{maxn}||10; my $MINA=$ENV{mina}||150;
  
  (my $outf=$btall) =~ s/\.\w+$/.lksamtab/;
  if(-s $outf){ 
    (my $outlkmap=$outf) =~ s/.lksamtab/.linkmap/;
    (my $outsam=$outf) =~ s/.lksamtab/.sam/;
    return(1,$outlkmap,$outsam,$outf) if($REUSE); # warn for $nskip, $nlo ?
  }
  
  sub splitaln_bad { 
    my($pw,$spx,$dcx)=@_; my($tw,$ib,$ie,@sx,@dx); 
    my($sb,$se)=split"-",$spx; my($db,$de)=split"-",$dcx; 
    $tw=1+$se-$sb; for(my $i=0; $i<$tw; $i += 4 + $pw) { 
    $ib=$sb+$i; $ie=$ib+$pw; push @sx, "$ib-$ie"; 
    $ib=$db+$i; $ie=$ib+$pw; push @dx, "$ib-$ie"; } 
    return(\@sx,\@dx); 
    }
    
  sub splitaln { # UPD2202
    my($pw,$spx,$dcx,$dor)=@_; my($tw,$ib,$ie,@sx,@dx); 
    my($sb,$se)=split"-",$spx; my($db,$de)=split"-",$dcx; 
    $tw=1+$se-$sb; 
    if($dor eq "-" or $dor < 0) {
      for(my $i=0; $i<$tw; $i += 4 + $pw) { 
      $ib=$sb+$i; $ie=$ib+$pw; push @sx, "$ib-$ie"; 
      $ie=$de-$i; $ib=$ie-$pw; push @dx, "$ib-$ie"; 
      if($ib < 1) { pop @dx; pop @sx; last; }
      } 
    
    } else {
      for(my $i=0; $i<$tw; $i += 4 + $pw) { 
      $ib=$sb+$i; $ie=$ib+$pw; push @sx, "$ib-$ie"; 
      $ib=$db+$i; $ie=$ib+$pw; push @dx, "$ib-$ie"; 
      } 
    }
    return(\@sx,\@dx); 
    }
 
 
  my($nrefchr,%refchr)=(0);
  if($REFCHR_LIST) { 
    open(R,$REFCHR_LIST); 
    while(<R>){ next if(/^\W/); my($id)=split; $refchr{$id}=1; } close(R);
    $nrefchr= scalar(keys %refchr);
  }
 
  # FIXME: filter out near-dup aligns, caused conflict/drop in chromer .. eg: scf121796 has 2nd near ident align
  # .. change btall criterion?  -pMINLOW=0.98 >> 0.9999 maybe
  # dmag20ug6bmac25v_scf121796	dmag15nwb_DC03	1731	1084	1140	1133	9415166	1-1133/1-1133	6658735-6659871:-
  # dmag20ug6bmac25v_scf121796	dmag15nwb_DC04	1698	1077	1140	1133	9111258	1-1133/1-1133	2052369-2053506:-
  my %didaln;
  
  my ($nout,$nskip,$nlo,$ndup,$li)=(0) x 9;
  open(IN,$btall) or die "reading $btall";
  open(OUT,">$outf");
  while(<IN>){

    next if(/^Query|^\W/); 
    my($sc,$dc,$bs,$ida,$aln,$sw,$dw,$ssp,$dsp)= split;
    if($nrefchr and not $refchr{$dc}) { $nskip++; next; }
    if($SKIPSCAF{$sc}){ $nskip++; next; } # bad scaf list from decontam ?
    
    $li++; 
    if($aln < $MINA){ $nlo++; next; } 
    if($didaln{$sc}) { $ndup++; next; }#?
    
=item UPD2202: BUG in dsp,dcx,dor 
  .. wrong orient/place of dcx segments for -dor    
  .. need to revcompl @dcx 
  splitaln() needs rev ****
  
=cut

    my($spf,$spx)=split"/",$ssp; my($dcx,$dor)=split":",$dsp; 
    my @spx=split",",$spx; my $nspx=@spx; my @dcx=split",",$dcx;

    if(@spx < 2) { my $pw= ($aln>899) ? 250 : 99; 
      my($spxx,$dcxx)= splitaln($pw,$spx,$dcx,$dor); @spx=@$spxx; @dcx=@$dcxx; }
    elsif(@spx < 5) { my(@spxi,@dcxi);
      for(my $i=0; $i<$nspx; $i++) {
        my($sib,$sie)=split"-",$spx[$i]; my $sw=$sie-$sib;
        if($sw < 400) { push @spxi,$spx[$i]; push @dcxi,$dcx[$i]; }
        else { my($spxx,$dcxx)= splitaln(($sw>899) ? 250 : 200, $spx[$i],$dcx[$i],$dor); 
          push @spxi,@$spxx; push @dcxi,@$dcxx; }
        } 
        if(@spxi > @spx){ @spx=@spxi; @dcx=@dcxi; } 
      }
    
    $nspx=@spx;   $didaln{$sc}= $dc if($nspx>0); # dup filter
    my $k=($nspx >= 2*$MAXN)?int($nspx/$MAXN):1;  
    for(my $i=0; $i<$nspx; $i+=$k){  
      my $sx=$spx[$i]; my $dx=$dcx[$i];
      my($sxb,$sxe)= split"-",$sx; my $sxw=1+$sxe-$sxb; my($dxb,$dxe)=split"-",$dx;
      (my $chrid=$dc) =~ s/^$refprefix//; # FIXME
      my $tid=join("_",$TAG,$chrid,$dxb,$sc); 
      $tid=~s/\W/_/g; $tid=~s/dmag/dm/;
      $tid=~s/[Cc]ontig/ct/; $tid=~s/[Ss]caffold/sc/; 
      my $cm=sprintf "%.5f", $dxb*$CB2CM; my $sfl=($dor eq "-")?16:0; 
      #? change here, two outs: OLKMAP, OSAM ? but this lkmap has more cols
      print OUT join("\t",$chrid,$tid,$cm,$dxb,"$sx/$dx","link.$li")."\n";  $nout++;
      print OUT join("\t",$tid,$sfl,$sc,$sxb,99,$sxw."M","\*",0,0,"\*","\*","Xl:i:$li")."\n"; 
    } 
  
  }
  close(IN); close(OUT);
  
  (my $outlkmap=$outf) =~ s/.lksamtab/.linkmap/;
  (my $outsam=$outf) =~ s/.lksamtab/.sam/;
  runcmd("grep link $outf | sort -k1,1 -k4,4n | cut -f1-3 > $outlkmap");
  runcmd("grep -v link $outf > $outsam");

  warn "#btall2lksamtab: nout=$nout, nskip=$nskip, nlow=$nlo, ndup=$ndup for $btall to $outf\n" if($debug);
  returndbg($nout,$outlkmap,$outsam,$outf); # warn for $nskip, $nlo ?
}

__END__

=item chromer try2
  .. removed ref-scafs with refchrlist
  .. decontam() failed for dmag20sk4abyss << ssssss extra s
     >> contam/dmag20sk4abys-contamb_daphgene.tab

pt=dmag20sk4abyss; idp=dmagsk4abys; 
env asm=${pt}_lsc idpre=$idp ref=dmag15nwblg2r_all refchrs=genome/dmag15nwblg2r_all.chrlist \
  contam=contam/$pt-contamb_daphgene.tab \
  ncpu=2  lkmapbin=$lkmap evigene=$evigene  ../dapblastaln6linkmap.pl >& lgmap6v.$pt.log

chromonomer --disable_splitting 
 --map l6vdmag20sk4abyss_lsc-dmag15nwblg2r_all.linkmap 
 --alns l6vdmag20sk4abyss_lsc-dmag15nwblg2r_all.sam 
 --agp genome/dmag20sk4abyss_lsc.agp --out_path lgmap6v_dmag20sk4abyss_lsc

  19448 scaffolds in the linkage map, from 19448 original scaffolds.
  Splits  Num Scaffolds
  0       19448
  85156 markers in the final map; 88724 inconsistent markers excluded.
  
  Chromosome lengths:
  >>> wrong idpre ? reusing refchr ids here, drop dmag15nwb_ prefix ***
  dmag15nwb_DC01:   22.1Mbp
  dmag15nwb_DC02:   25.8Mbp
  dmag15nwb_DC03:   14.4Mbp
  dmag15nwb_DC04:   16.0Mbp
  dmag15nwb_DC05:   15.3Mbp
  dmag15nwb_DC06:   15.1Mbp
  dmag15nwb_DC07:   16.5Mbp
  dmag15nwb_DC08:   15.5Mbp
  dmag15nwb_DC09:   11.6Mbp
  dmag15nwb_DC10:   16.7Mbp
    Total length:  169.5 Mbp

=item chromer dmag20ugspad4d_asm try3

  NOTE: cmp to prior lgmap5u_dmag20ugspad4d_nobac, using ~same bact contam but diff calc
  lgmap5u_dmag20ugspad4d_nobac.chrs total	106.4 Mb (10 Mb gaps)
  
  pt=dmag20ugspad4d_asm; idp=dmagug4spad
  env  asm=$pt idpre=$idp ref=dmag15nwblg2r_all refchrs=genome/dmag15nwblg2r_all.chrlist \
   contam=contam/$pt-contamb_daphgene.tab ncpu=2  ../dapblastaln6linkmap.pl >& lgmap6v.$pt.log
  ...
   
  14469 scaffolds examined on 10 linkage groups; 0 scaffolds were split.
  59448 markers in the final map; 18050 inconsistent markers excluded.
  
  Chromosome lengths:
   DC01:   16.6Mbp
   DC02:   12.7Mbp
   DC03:    8.7Mbp
   DC04:   10.9Mbp
   DC05:    9.1Mbp
   DC06:   10.5Mbp
   DC07:    7.0Mbp
   DC08:    9.3Mbp
   DC09:    8.9Mbp
   DC10:   11.4Mbp
  Total length:  105.7 Mbp # not much dif from prior 106 Mb

# chr.fasta: ncontig=14469 to nchr=10, size_Mb=107.1,96.2(nogap) in lgmap6v_dmag20ugspad4d_asm/dmagug4spad_chrs.fa
# chr.fasta: ncontig=29167 to nchr=29167, size_Mb=119.7,114.8(nogap) in lgmap6v_dmag20ugspad4d_asm/dmagug4spad_unscaf.fa
#        note very large amount in unplaced scafs ^^^ more bact? need ref-scaf info


=item chromer dmag20ug6bmac25v try4

  .. test blastn asm x contamdb to contam.tab
  pt=dmag20ug6bmac25v; idp=dmagug6bmac_;  
  env  asm=$pt idpre=$idp ref=dmag15nwblg2r_all refchrs=genome/dmag15nwblg2r_all.chrlist \
   contamdb=contam/dmag20contambact.fa.gz ncpu=2  ../dapblastaln6linkmap.pl >& lgmap6v.$pt.log
   

  
=item chromer dmag20ug6maca13ck try3

  pt=dmag20ug6maca13ck; idp=dmagug6mac; # >> chrid=dmagug6macDC01 ? add _
  env  asm=$pt idpre=$idp ref=dmag15nwblg2r_all refchrs=genome/dmag15nwblg2r_all.chrlist \
   contam=contam/$pt-contamb_daphgene.tab ncpu=4  ../dapblastaln6linkmap.pl >& lgmap6v.$pt.log
  ---
  
  #cmd=gunzip -c genome/dmag20ug6maca13ck.fa.gz | blastn -task megablast -evalue 1e-14 -perc_identity 90  -culling_limit 6 -outfmt 7  -num_threads 4 -db genome/bldb/dmag15nwblg2r_all -out l6vdmag20ug6maca13ck-dmag15nwblg2r_all.blastn

  decontam: genome/dmag20ug6maca13ck.fa.gz TO 
    nok=54385,213.1.M,genome/dmag20ug6maca13ck-clean.fa; 
    ncon=11173,20.6.M,genome/dmag20ug6maca13ck-contam.fa 

  #cmd= chromonomer-1.12/chromonomer  --disable_splitting \
   --map l6vdmag20ug6maca13ck-dmag15nwblg2r_all.linkmap \
   --alns l6vdmag20ug6maca13ck-dmag15nwblg2r_all.sam --agp genome/dmag20ug6maca13ck-clean.agp \
   --out_path lgmap6v_dmag20ug6maca13ck

  Loaded 179163 markers on 10 linkage groups.
  Pruned 17685 markers that have no alignments; 155964 markers remain.
  Parsing 'genome/dmag20ug6maca13ck-clean.agp'.
    Loaded assembly components for 54385 scaffolds.
  27045 total scaffolds; 1217 scaffolds mapped to multiple linkage groups.

  Processing linkage group 'DC10'...
  1724 scaffolds pruned from map nodes supported by fewer than 2 markers; removed 3731 markers supporting those nodes.
  2980 total scaffolds; 131 scaffolds mapped to multiple nodes in a linkage group; 0 successfully split; 131 failed to split.
  
  27045 scaffolds examined on 10 linkage groups; 0 scaffolds were split.
  98147 markers in the final map; 57817 inconsistent markers excluded.
    
  Chromosome lengths:
   DC01:   18.3Mbp
   DC02:   20.5Mbp
   DC03:   12.2Mbp
   DC04:   12.6Mbp
   DC05:   16.6Mbp
   DC06:   11.6Mbp
   DC07:   15.2Mbp
   DC08:   19.0Mbp
   DC09:    8.8Mbp
   DC10:   14.4Mbp
  Total length:  149.8 Mbp  # NOTE Mb count differs from below, gap counting differs

# chr.fasta: ncontig=27045 to nchr=10, size_Mb=152.4,125.5(nogap) in lgmap6v_dmag20ug6maca13ck/dmagug6mac_chrs.fa
# chr.fasta: ncontig=27340 to nchr=27340, size_Mb=63.3,61.6(nogap) in lgmap6v_dmag20ug6maca13ck/dmagug6mac_unscaf.fa
** ^^ FIXME add unscaf.fa (and chrs.fa) annot of ref.align, including ref.scafs
.. may want 3rd btall parse of ref.blastn for all ref chr+scaf

lgmap6v_dmag20ug6maca13ck/dmagug6mac_chrs.fa.gz 
  .. vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all is too long
  >dmagug6macDC01 length=18623956; gaps=2939925; contigs=2868; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC02 length=20895485; gaps=3619019; contigs=3490; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC03 length=12549578; gaps=2040407; contigs=2731; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC04 length=12981397; gaps=1958333; contigs=2887; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC05 length=16892586; gaps=3527657; contigs=2578; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC06 length=11842277; gaps=1756663; contigs=2061; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC07 length=15583682; gaps=2599276; contigs=2889; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC08 length=19287497; gaps=4398933; contigs=2483; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC09 length=9040900; gaps=1555490; contigs=2078; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmagug6macDC10 length=14797364; gaps=2540604; contigs=2980; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;

lgmap6v_dmag20ug6maca13ck/dmagug6mac_unscaf.fa.gz  
  >dmag20ug6maca13v_ctg108 length=692; gaps=0;  ; valid=clean; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmag20ug6maca13v_ctg199 length=532; gaps=0;  ; valid=clean; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmag20ug6maca13v_ctg219 length=541; gaps=0;  ; valid=clean; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  ..
  >dmag20ug6maca13v_scf54784 length=10395; gaps=40;  ; valid=maybecon:CP011774.1:40%,4179/1-10395:refchr:43%,238,dmag24nwb7d_contig32616; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmag20ug6maca13v_scf79388 length=41285; gaps=20;  ; valid=maybecon:CP011774.1:41%,17091/1-41176:1.gene,28163-28656:refchr:11%,69,dmag24nwb7d_contig30967; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;
  >dmag20ug6maca13v_ctg91883 length=3127; gaps=0;  ; valid=maybecon:CP037867.1:99%,3117/10-3127:18.gene,10-3003:refchr:100%,635,dmag24nwb7d_contig29854; vers=l6vdmag20ug6maca13ck-dmag15nwblg2r_all;


=item chromer dmag14bgi2vtop5k try1

  refchr=dmag15nwblg2r_all has lots of left over scaf/contig w/ ten DC 
    .. chrmer processed them, with many files
    .. want to exclude?
    
  chromonomer-1.12/chromonomer --disable_splitting \
   --map l6vdmag14bgi2vtop5k-dmag15nwblg2r_all.linkmap --alns l6vdmag14bgi2vtop5k-dmag15nwblg2r_all.sam \
   --agp genome/dmag14bgi2vtop5k-clean.agp --out_path lgmap6v_dmag14bgi2vtop5k

chromonomer_summary.log
  3611 scaffolds in the linkage map, from 3611 original scaffolds.
  Splits  Num Scaffolds
  0       3611
  16547 markers in the final map; 12980 inconsistent markers excluded.
  
  Chromosome lengths:
  dmag15nwb_DC01:   20.2Mbp
  dmag15nwb_DC02:   20.9Mbp
  dmag15nwb_DC03:   17.4Mbp
  dmag15nwb_DC04:   11.5Mbp
  dmag15nwb_DC05:   15.9Mbp
  dmag15nwb_DC06:   11.8Mbp
  dmag15nwb_DC07:   14.9Mbp
  dmag15nwb_DC08:   13.1Mbp
  dmag15nwb_DC09:   10.8Mbp
  dmag15nwb_DC10:   18.9Mbp
  
  >> want these ref scafs or not?
  >> maybe want 3 fasta piles, refchr-placed, refscaf-placed, unplaced on ref
  dmag24nwb7d_contig14481:       4719bp
  dmag24nwb7d_contig17705:      36937bp
  ...
  dmag24nwb7d_scaffold02234:      16857bp

  Total length:  171.1 Mbp
    chr nc=10,mb=155.9, scaf ns=716,mb=15.1
    4586 are placed, 2186 are placed on _DC chrs, 975 scafs are unplaced

  bgi run2, revised soft, only DC refchrs
    chr mb=168.5 Mb
    
=cut

=item btall2lksamtab

env tag=bcnw perl -ne 'BEGIN{ $CB2CM=$ENV{cb2cm}|| 0.000018;
$MAXN=$ENV{maxn}||10;  $TAG=$ENV{tag}; $MINA=$ENV{mina}||150; } 
next if(/^Query|^\W/); ($sc,$dc,$bs,$ida,$aln,$sw,$dw,$ssp,$dsp)=@v=split;
$li++; if($aln < $MINA){ $nlo++; next; } 
($spf,$spx)=split"/",$ssp; ($dcx,$dor)=split":",$dsp; 
@spx=split",",$spx; $nspx=@spx; @dcx=split",",$dcx;
if(@spx < 2) { my $pw= ($aln>899) ? 250 : 99; 
($spxx,$dcxx)= splitaln($pw,$spx,$dcx); @spx=@$spxx; @dcx=@$dcxx; }
elsif(@spx < 5) { my(@spxi,@dcxi);
  for(my $i=0; $i<$nspx; $i++) {
    my($sib,$sie)=split"-",$spx[$i]; my $sw=$sie-$sib;
    if($sw < 400) { push @spxi,$spx[$i]; push @dcxi,$dcx[$i]; }
    else { ($spxx,$dcxx)= splitaln(($sw>899) ? 250 : 200, $spx[$i],$dcx[$i]); 
      push @spxi,@$spxx; push @dcxi,@$dcxx; }
  } if(@spxi > @spx){ @spx=@spxi; @dcx=@dcxi; } }
$nspx=@spx; $k=($nspx >= 2*$MAXN)?int($nspx/$MAXN):1;  
for($i=0; $i<$nspx; $i+=$k){  $sx=$spx[$i]; $dx=$dcx[$i];
($sxb,$sxe)= split"-",$sx; $sxw=1+$sxe-$sxb; ($dxb,$dxe)=split"-",$dx;
$tid=join("_",$TAG,$dc,$dxb,$sc); $tid=~s/\W/_/g; $tid=~s/dmag/dm/;
$tid=~s/[Cc]ontig/ct/; $tid=~s/[Ss]caffold/sc/; 
$cm=sprintf "%.5f", $dxb*$CB2CM; $sfl=($dor eq "-")?16:0; 
print join("\t",$dc,$tid,$cm,$dxb,"$sx/$dx","link.$li")."\n"; 
print join("\t",$tid,$sfl,$sc,$sxb,99,$sxw."M","\*",0,0,"\*","\*","Xl:i:$li")."\n"; } 
sub splitaln{ my($pw,$spx,$dcx)=@_; my($tw,$ib,$ie,@sx,@dx); 
my($sb,$se)=split"-",$spx; my($db,$de)=split"-",$dcx; 
$tw=1+$se-$sb; for(my $i=0; $i<$tw; $i += 4 + $pw) { 
$ib=$sb+$i; $ie=$ib+$pw; push @sx, "$ib-$ie"; 
$ib=$db+$i; $ie=$ib+$pw; push @dx, "$ib-$ie"; } 
return(\@sx,\@dx); } ' \
  lkmapbaln/$pt-dmag15nwb2r_chrs.btall \
  > lgdata_$pt/dmag15nwb2r.lksamtab
  
=cut

=item blast2contam

($ncon,$contamtab,$blout)= blast2contam($aname,$asmfa,$contamtab,$contamfa,$genealigntab) 

from daphmag/gasm20set/dmag20reasm/contamug/contamugbact.info

env asm=dmag15nwb2asm.fa  pident=80 datad=`pwd` qsub -q debug run_contamblast.sh

gunzip -c ${pt}_dmag20ug4contambact80i.blastn.gz | perl -ne \
'if(/^# Query: (\S+)/){ puth() if($sw and $trd and $tal); $sid=$1; 
($sw)=m/(?:length|len)=(\d+)/; unless($sw){ $sw=($sid =~ /LG/)?999999:1999; }  
$trd=$tal=0; $tsb=$tse=0; } 
elsif(/^\w/){ ($sc,$rd,$pi,$al)=@v=split; ($sb,$se)=@v[6,7]; $aok=0; 
if($trd){ if($rd eq $trd){ $aok=1; } } else { $trd=$rd; $aok=1; } 
if($aok){ $tal+=$al; $tsb=$sb if($sb<$tsb or $tsb==0); $tse=$se if($se>$tse); } } 
END{ puth() if($sw and $trd and $tal); }
sub puth{ $tsp=$tse-$tsb; $tal=$tsp if($tsp<$tal); $pal=($sw>1)?int(100*$tal/$sw):0; 
if($sw>=$MINW and $tal>= $pMINA* $sw){ print join("\t",$sid,$sw,$trd,"$pal%,$tal/$tsb-$tse")."\n";
$tsw+=$sw; $ttal+=$tal; $tn++; } } 
END{ ($mb,$mba)=map{ int($_/100_000)/10; } ($tsw,$ttal); 
print "# contam n=$tn, mb=$mb, mbal=$mba for MINW=$MINW, pMINA=$pMINA\n"; } 
BEGIN{ $MINW=500; $pMINA=0.33; }' \
  > ${pt}-contambacb.tab
 
perl -ne '($d)=@v=split; if(@v<5){ ($sc,$sw,$bacid,$bacw)=@v;
if($genes=$genes{$sc}){ @gn=split";",$genes; my($gsb,$gse)=(0,0); map{
($sbe,$tid,$tlen,$cov)=split","; ($sb,$se)=split"-",$sbe; $gsb=$sb
if($sb<$gsb or $gsb==0); $gse=$se if($se>$gse); } @gn; $ngn=@gn;
$genes="$ngn.gene,$gsb-$gse";  } else { $genes="nogene"; }  print
join("\t",@v,$genes)."\n"; } elsif(/^Genome/){ @ghd=@v; }
elsif(/^\w/){ ($sc,$sbe,$so,$tid,$tlen,$cov,$pid,$nex)=
@v[0,1,2,3,6,7,8,11]; $ok=($cov>=20 or $tlen*$cov/100 > 120);
$genes{$sc}.="$sbe,$tid,$tlen,$cov;" if($ok);} ' \
   ../geneval/$pt-dmag14t1cds.align.tab $pt-contambacb.tab 
   > $pt-contamb_daphgene.tab

=cut