#!/bin/bash 
banner[1]='_______________________________________________________________________________'
banner[2]='                                                                               '
banner[3]='                            GETSOURCES (GETFILAMENTS)                          '
banner[4]='       Multi-Scale Multi-Wavelength Source & Filament Extraction Methods       '
banner[5]='              Alexander Men`shchikov, SAp IRFU CEA Saclay, France              '
banner[6]='                                Version 1.140127                               '
banner[7]='_______________________________________________________________________________'
#
# Development initiated on 2008/07/20 by A.M. (alexander.menshchikov@cea.fr)
#___________________________________________________________________________________________________________________________________

HISTORY ()
{
  for (( b=1; b <= 7; b++ ))
  do echo '#'"${banner[b]}"; done
  echo '#'
  echo '#                               HISTORY OF CHANGES'
  echo '#                               (only last months)'
  echo '#'
  echo '# ------------------------------ VERSION 1.140127 ------------------------------'
  echo '#'
  echo '# [FIX] 2019-01-13: Minor fix in copying files when restarting GETSOURCES.'
  echo '#'
  echo '# [FIX] 2018-11-29: Minor fix in all utilities: removed the STOP instruction,'
  echo '#       because it would lead to run-time messages about denormalized values,'
  echo '#       when using gfortran.'
  echo '#'
  echo '# [FIX] 2018-10-19: Replaced the older version of GETIMAGES (v2.180114) with the'
  echo '#       improved latest version v2.180830.'
  echo '#'
  echo '# [FIX] 2018-02-10: Removed a useless diagnostic message from SMEASURE about a'
  echo '#       source having zero equivalent radius.'
  echo '#'
  echo '# [FIX] 2018-02-04: Corrected an old problem in SFINDER that a "source" with'
  echo '#       only few pixels may appear and immediately vanish on the same scale.'
  echo '#       Such clusters of pixels should be marked as noise peaks, otherwise they'
  echo '#       would interfere on larger scales with a source at the same position.'
  echo '#       As a result, real sources at that position would be lost.'
  echo '#'
  echo '# [FIX] 2018-02-01: Accelerated SMEASURE by skipping measurements and deblending'
  echo '#       of the isolated sources with converged stationary (not expanding)'
  echo '#       footprints.'
  echo '#'
  echo '# [FIX] 2018-01-31: Accelerated SMEASURE by optimizing annuli handling.'
  echo '#'
  echo '# [FIX] 2018-01-27: Accelerated SMEASURE by taking IF-THEN-ELSE out of several'
  echo '#       innermost nested loops.'
  echo '#'
  echo '# [FIX] 2018-01-12: Fixed a bug in deblending in SMEASURE and FINALCAT affecting'
  echo '#       *only* the images with pixel size smaller than 1 arcsec. As a result,'
  echo '#       some overlapping sources may not be properly deblended in such images.'
  echo '#'
  echo '# [NEW] 2017-03-15: The GETIMAGES script added to GETSOURCES (described in the'
  echo '#       paper: Men’shchikov A. 2017, A&A, 607, A64). The new script can be used'
  echo '#       to accurately flatten the observed images before the extraction.'
  echo '#'
  echo '# [FIX] 2016-10-11: Fixed a minor bug in FITFLUXES (drawing progress bar).'
  echo '#'
  echo '# [FIX] 2016-05-02: Fixed a minor bug in headers of source intensity profiles.'
  echo '#'
  echo '# [FIX] Fixed a minor bug of not copying necessary files when starting combined'
  echo '#       initial extraction (bug introduced in v1.140116).'
  echo '#'
  echo '# [CHA] Minor improvement of FINALCAT: now the catalog headers document factors'
  echo '#       used to convert peak intensities from MJy/sr to Jy/beam.'
  echo '#'
  echo '# [CHA] Simplified GETSOURCES output by removing some unnecessary files. Cleaned'
  echo '#       up the source code of all FORTRAN utilities by removing fragments that'
  echo '#       were previously commented out.'
  echo '#'
  echo '# ------------------------------ VERSION 1.140124 ------------------------------'
  echo '#'
  echo '# [FIX] Fixed a problem when /bin/rm failed to remove many files because of a'
  echo '#       list of arguments that was too long.'
  echo '#'
  echo '# ------------------------------ VERSION 1.140118 ------------------------------'
  echo '#'
  echo '# [CHA] Modified SMEASURE in footprint expansion: only footprints of the sources'
  echo '#       with moderate size ratios AFWHM/BFWHM<2 will be expanded. This prevents'
  echo '#       unreasonable expansion of sources on bright steep intensity gradients.'
  echo '#'
  echo '# ------------------------------ VERSION 1.140116 ------------------------------'
  echo '#'
  echo '# [CHA] Moved measurement of filaments from the cleaning step to the measurement'
  echo '#       step; the latter now measures both filaments and sources.'
  echo '#'
  echo '# [CHA] Re-allowed sequential processing of wavelengths.'
  echo '#'
  echo '# ------------------------------ VERSION 1.140106 ------------------------------'
  echo '#'
  echo '# [FIX] Corrected in MODFITS a minor problem in cleaning skeletons. In rare'
  echo '#       cases, it caused FMEASURE to have troubles when finding the end points'
  echo '#       of some skeletons.'
  echo '#'
  echo '# ------------------------------ VERSION 1.131228 ------------------------------'
  echo '#'
  echo '# [NEW] Added in FINALCAT creation of an extra final catalog with more details.'
  echo '#'
  echo '# [CHA] Improved FITFLUXES in the criterion of the convergence of iterations.'
  echo '#'
  echo '# ------------------------------ VERSION 1.131217 ------------------------------'
  echo '#'
  echo '# [CHA] Improved FITFLUXES in the definition and exploration of the fitting'
  echo '#       model parameter space and in the convergence of iterations.'
  echo '#'
  echo '# ------------------------------ VERSION 1.131213 ------------------------------'
  echo '#'
  echo '# [CHA] Improved SMEASURE, making the algorithm of footprint expansion to work'
  echo '#       well for several nearby sources.'
  echo '#'
  echo '# ------------------------------ VERSION 1.131212 ------------------------------'
  echo '#'
  echo '# [NEW] Added FITFLUXES utility (external, not used by GETSOURCES) that fits'
  echo '#       fluxes of cataloged sources and derives temperatures, luminosities,'
  echo '#       masses, etc., producing an additional catalog of derived properties.'
  echo '#'
  echo '# ------------------------------ VERSION 1.131121 ------------------------------'
  echo '#'
  echo '# [NEW] Added to FMEASURE creation of images for visualizing mean, median, and'
  echo '#       total curvatures of filaments (skeletons).'
  echo '#'
  echo '# [CHA] Now FMEASURE computes and outputs only the curvatures that are smoothed'
  echo '#       along skeletons within nine-pixel sliding windows.'
  echo '#'
  echo '# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
  echo '# ++++ HISTORY FOR OLD REVISIONS MOVED TO THE FILE "OLD.HISTORY.OF.CHANGES" ++++'
  echo '# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
  echo '#'
  echo '# ------------------------------ VERSION 1.101210 ------------------------------'
  echo '#'
  echo '# [NEW] Initial version 1 of GETSOURCES. History of changes will be maintained.'
  echo '#'
  echo '# ------------------------------ VERSION 0.080720 ------------------------------'
  echo '#'
  echo '# [NEW] Development of GETSOURCES started on 2008/07/20.'
  echo '#_______________________________________________________________________________'
  echo '#'
}
#___________________________________________________________________________________________________________________________________

CONDITIONS ()
{
  echo '#  _____________________________________________________________________________'
  echo '# |                                                                             '
  echo '# |                           GETSOURCES (GETFILAMENTS)                         '
  echo '# |      Multi-Scale Multi-Wavelength Source & Filament Extraction Methods      '
  echo '# |             Alexander Men'\''shchikov, SAp IRFU CEA Saclay, France             '
  echo '# |                               '$versnum'                               '
  echo '# |_____________________________________________________________________________'
  echo '# |                                                                             '
  echo '# |    CONDITIONS OF USE (*1)                                                   '
  echo '# |                                                                             '
  echo '# | In what follows, "this software" refers to the Bash scripts GETSOURCES,     '
  echo '# | CONVOLVE, IOSPEED, PREPAREOBS, RESAMPLE, & the associated FORTRAN utilities '
  echo '# | CLEANBG, ELLIPSES, EXPANDA, FFTCONV, FINALCAT, FITFLUXES, FMEASURE, IMGSTAT,'
  echo '# | MODFITS, OPERATE, READHEAD, SEPARATE, SFINDER, SMEASURE, SPLITCUBE, and the '
  echo '# | library TOOLS, and "the author" refers to Alexander Men'\''shchikov of the  '
  echo '# | Service d'\''Astrophysique, IRFU, CEA Saclay, France.                          '
  echo '# |                                                                             '
  echo '# | It is assumed that anyone using this code ("the user") has read, understood,'
  echo '# | and agreed to the following conditions of use:                              '
  echo '# |                                                                             '
  echo '# | 1. Distribution of this software shall remain the purview of the author. A  '
  echo '# |    user is free to share this code with co-workers and students, but if it  '
  echo '# |    is requested by a colleague not working directly with the user, the user '
  echo '# |    is asked to redirect such requests to: alexander.menshchikov@cea.fr      '
  echo '# |                                                                             '
  echo '# | 2. This software shall be used exclusively for education, research, non-    '
  echo '# |    profit, and non-military purposes. Specific written permission from the  '
  echo '# |    author must be obtained before any commercial use of this software is    '
  echo '# |    undertaken.                                                              '
  echo '# |                                                                             '
  echo '# | 3. The banners of this software, these conditions of use, and information   '
  echo '# |    about the author shall remain with this software and any descendent      '
  echo '# |    developed from and still based substantially upon this software.         '
  echo '# |                                                                             '
  echo '# | 4. The names of the institutions with which the author is or has been       '
  echo '# |    affiliated shall not be used to publicise any data and (or) results      '
  echo '# |    generated by this software. All findings and their interpretation are    ' 
  echo '# |    the opinions of the user and do not necessarily reflect those of the     '
  echo '# |    author nor the institutions with which the author is or has been         '
  echo '# |    affiliated.                                                              '
  echo '# |                                                                             '
  echo '# | The author makes no representations about the suitability of this software  '
  echo '# | for any purpose. Subject to the above conditions, this software are provided'
  echo '# | "as is" without any expressed or implied warranty.                          '
  echo '# |                                                                             '
  echo '# | Inquiries about the code, bug reports, constructive criticism, etc., can be '
  echo '# | directed to: alexander.menshchikov@cea.fr                                   '
  echo '# |                                                                             '
  echo '# |    CITATIONS AND ACKNOWLEDGEMENTS (*1)                                      '
  echo '# |                                                                             '
  echo '# | The algorithms used in this software are described in:                '
  echo '# | Men'\''shchikov A. 2013, A&A, 560, A63                                         '
  echo '# | Men'\''shchikov A., Andre Ph., Didelon P., et al. 2012, A&A, 542, A81          '
  echo '# |                                                                             '
  echo '# | A very brief description of GETSOURCES has been published in:               '
  echo '# | Men'\''shchikov A., Andre Ph., Didelon P., et al. 2010, A&A, 518, L103         '
  echo '# |                                                                             '
  echo '# | It is requested that any publication reporting results obtained using this  '
  echo '# | software or any of its derivatives includes:                                '
  echo '# |                                                                             '
  echo '# | "Use of GETSOURCES (GETFILAMENTS), developed by A. Men'\''shchikov             '
  echo '# | at the SAp, IRFU, CEA Saclay, France, is hereby acknowledged." (*2)         '
  echo '# |_____________________________________________________________________________'
  echo '#                                                                               '
  echo '# (*1) Adapted from those written by David Clarke for the MHD code AZEuS.       '
  echo '# (*2) If only individual scripts or utilities (not the GETSOURCES script)      '
  echo '#      were used, substitute "GETSOURCES" with their names.                     '
}
#___________________________________________________________________________________________________________________________________
#
system=`uname`; homepath=`echo ~`; originpath=`pwd`; executing="$0"
scriptname=`basename "$executing"`; script=`echo $scriptname | tr a-z A-Z`
logfile='+log.'$script; logit='+log.'$script'.iter'
#___________________________________________________________________________________________________________________________________

USAGE ()
{
  echo
  echo '                         GETSOURCES: USAGE INFORMATION                         '
  echo
  echo ' '$scriptname' [<revision>|stopitnow|help]'
  echo
  echo ' Input data must be defined in a configuration file '\''+getsources.cfg'\''.' 
  echo ' If no config file exists in the current directory, a new default version of '
  echo ' the file is saved in that directory. One needs to edit the file as necessary,'
  echo ' then run '$scriptname' again.'
  echo
  echo ' An optional command-line parameter "<revision>" can be given if the user wants'
  echo ' to run a specific version (revision) of GETSOURCES. The parameter must be a'
  echo ' six-digit number representing the revision in the format yymmdd (year-month-'
  echo ' day). For example, if one wants to use the version 1.110320 of GETSOURCES and'
  echo ' its utilities and scripts, then <revision> is 110320. Then the version from'
  echo ' directory $GETSOURCES_BIN/v1.110320 will be used; here $GETSOURCES_BIN is the'
  echo ' environment variable pointing to a directory where the binaries are installed.'
  echo   
  echo ' Another optional parameter "stopitnow" can be used to gently stop GETSOURCES'
  echo ' when a user cannot access (or identify) the terminal session where the job is'
  echo ' running. The command "getsources stopitnow" issued in a directory where an'
  echo ' extraction is going on will terminate the execution of GETSOURCES as soon as'
  echo ' possible (note that it may still take a long time for large images and large'
  echo ' numbers of sources). Another way of getting the same effect is to create a'
  echo ' file with the name "+stopitnow!" in the extraction directory.'
  echo
  echo ' GETSOURCES calls a suite of FORTRAN utilities (written by A. Men`shchikov).'
  echo ' They use the CFITSIO library (by William D Pence). Optional but very useful'
  echo ' is the utility XY2SKY from WCSTools (by Jessica Mink): if it is installed and'
  echo ' found in the system, GETSOURCES will produce catalogs with WCS coordinates.'
  echo ' If XY2SKY is not found, the extraction catalogs will contain just offsets in'
  echo ' pixels and in arcseconds from the lower-left pixel.'
  echo
  echo '    NOTE 1: PROCESSING EFFICIENCY GUIDELINES.'
  echo
  echo ' 1. Always run GETSOURCES on a *local* (internal) hard drive physically'
  echo '    attached to the computer (CPU) used for extractions. The code performs'
  echo '    *lots* of read/write operations with FITS files containing images.'
  echo '    Users would benefit from the fastest possible I/O throughput.'
  echo
  echo ' 2. Never use hard drives attached over the local network, as the disk access'
  echo '    over the network is *very* slow compared to the local disks. GETSOURCES'
  echo '    may be very slow on the disks attached over networks.'
  echo
  echo ' 3. Processing speed depends on many circumstances in a given computer system.'
  echo '    If one wants to optimize the processing times, it is generally a good idea'
  echo '    to test available disk storage for speed.'
  echo
  echo ' 4. The script IOSPEED enables comparisons of available hard drives. One can'
  echo '    perform tests of the local and network disks, as well as of the virtual'
  echo '    RAM disks.'
  echo
  echo '    NOTE 2: FLATTENING OF DETECTION IMAGES.'
  echo
  echo ' 1. Observed images generally have *strongly* variable noise and backgrounds.'
  echo '    On the other hand, GETSOURCES computes constant thresholds over the entire'
  echo '    single-scale images to distinguish sources from the noise and background.'
  echo '    Here is an obvious difficulty, as such thresholding works best for images'
  echo '    with approximately uniform noise and background.'
  echo
  echo ' 2. To overcome the problem, GETSOURCES employs an algorithm of flattening for'
  echo '    the detection images to make their intensity variations due to background'
  echo '    and noise much more uniform. This requires a two-step approach, essentially'
  echo '    two full source extractions.'
  echo
  echo ' 3. The initial source extraction should be performed with the configuration'
  echo '    parameter FLATTENING set to "n". Full monochromatic extractions as well as'
  echo '    a full multi-wavelength extraction should be completed that would produce'
  echo '    footprints images for all wavelengths. In general, it is very likely that'
  echo '    the initial catalogs would be contaminated by spurious sources, in the'
  echo '    areas where the background or noise variations are very high compared to'
  echo '    the other parts of the images.'
  echo
  echo ' 4. The final (second) extraction should be done with FLATTENING set to "y"'
  echo '    and with a path pointing to the directory of the initial multi-wavelength'
  echo '    extraction. In this run, before any processing, GETSOURCES will remove all'
  echo '    sources detected in the initial extraction, produce flattening images, and'
  echo '    divide the original detection images by those to flatten them. Only then'
  echo '    will GETSOURCES perform the final accurate extraction.'
  echo
  echo ' 5. This is *the only* correct scheme for source extraction with GETSOURCES for'
  echo '    any images, independent of how variable the noise and background may look.'
  echo '    Without this two-step approach, clean results generally cannot be obtained.'
  echo
  echo '    NOTE 3: DETECTION AND SUBTRACTION OF FILAMENTS.'
  echo
  echo ' 1. Observed images generally have *lots* of filamentary structures on various'
  echo '    spatial scales, in addition to noise and more isotropic backgrounds. Such'
  echo '    elongated (filamentary) structures present a very serious problem for all'
  echo '    source extraction methods: they tend to detect many spurious sources on'
  echo '    top of filaments.'
  echo 
  echo ' 2. To overcome the problem, GETSOURCES detects filamentary structures during'
  echo '    the cleaning step at each spatial scale, accumulates them over all scales,'
  echo '    and subtracts the filaments from the detection image before its flattening.'
  echo '    This is possible, because the accumulated filaments are practically free of'
  echo '    sources and more isotropic backgrounds.'
  echo
  echo ' 3. The images of filamentary structures at each wavelength present a very good'
  echo '    view of the filaments at all scales and they are very useful in analysing'
  echo '    and understanding of observations. They also make source extraction results' 
  echo '    more robust in highly filamentary images.'
  echo
  echo ' For the information on how to install GETSOURCES and to quickly start using it'
  echo ' refer to the files "INSTALLATION.GUIDE", "QUICK.START.GUIDE", "USERS.CHECKLIST"'
  echo ' included in the distribution archive.'
  echo
  echo ' The algorithms used in this software are described in:'
  echo ' Men'\''shchikov A. 2013, A&A, 560, A63'
  echo ' Men'\''shchikov A., Andre Ph., Didelon P., et al. 2012, A&A, 542, A81'
  echo
  echo ' A very brief description of GETSOURCES has been published in:'
  echo ' Men'\''shchikov A., Andre Ph., Didelon P., et al. 2010, A&A, 518, L103'
}
#___________________________________________________________________________________________________________________________________
#
# Default values of the expert parameters (the strings should occupy 6 characters).
#
def_scale1='0     '
def_nscales='99    '
def_sfactor='0     '
def_fsbelowbeam='0.333 '
def_fscalemax='1.0   '
def_ffaintestscale='0.067 '
def_nsigmacutss='6     '
def_nsigmacutfloor='2.5   '
def_skewmaxfloor='0.2   '
def_kurtmaxfloor='0.2   '
def_minpixfloor='4     '
def_cleantuning='1.0   '
def_comboexpomax='7     '
def_comboexpomin='7     '
def_contranoise='1.3   '
def_factortotal='2.3   '
def_fdp='1 '
def_fbm='30 '
def_ffi='1 '
#
# Default values of the Herschel beams adopted by GETSOURCES (averaged). 
# When modifying them here, don't forget to change them also in PREPAREOBS!
#
b070s10=' 5.4'; b070s20=' 5.6'; b070s20p=' 5.9'; b070s60=' 7.2'; b070s60p=' 8.4'
b100s10=' 6.7'; b100s20=' 6.8'; b100s20p=' 7.0'; b100s60=' 8.2'; b100s60p=' 9.4'
b160s10='11.2'; b160s20='11.3'; b160s20p='11.7'; b160s60='12.3'; b160s60p='13.5'; b250='18.2'; b350='24.9'; b500='36.3'
#___________________________________________________________________________________________________________________________________

DEFAULTPARAMS ()  # Default parameters will be saved in a configuration file if no such file exists in the current directory.
{
  for (( v=1; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}"; done
  echo '#                    |                                        !'
  echo '# VALUES             | VARIABLES'\'' NAMES    {CHOICES/DEFAULTS} ! COMMENTS [NOTE: Default beams: Herschel fast (60"/s) parallel mode]'
  echo '#____________________|________________________________________!_____________________________________________________________________'
  echo '#'
  echo ' name~of~your~field  | prefix ....( should not contain dots ) ! name that will be used as a prefix for naming output files'
  echo ' 6                   | nwmax .................{ nwmax < 100 } ! maximum number of wavelengths in this configuration file'
  echo ' 6 1 2 3 4 5 6       | nwaves nw[i] ......................... ! number of waves and indices of the wavelengths to process'
  echo ' 070 '$b070s60p' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../070 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.070 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.070 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' 100 '$b100s60p' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../100 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.100 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.100 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' 160 '$b160s60p' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../160 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.160 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.160 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' 250 '$b250' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../250 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.250 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.250 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' 350 '$b350' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../350 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.350 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.350 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' 500 '$b500' 220 0 1 y 0 | ..................................... ! [-]wave, beam, [+]maxsize("FWHM), skmax, weight, apcorr, [+]aprad(")'
  echo ' /prepared/images ../500 | .................................. ! paths to prepared images and to single-wavelength extractions'
  echo ' detection.image.500 | ...................................... ! name of the detection image (used for processing, detections)'
  echo ' measuremt.image.500 | ...................................... ! name of the observed image  (only used for measurements)'
  echo ' /your/initial/combined/extraction | ........................ ! path to an initial combined extraction without flattening'
  echo ' y         <--user.. | flattening dofl .................{ y } ! {y|n} improve detection images by equalizing background rms'
  echo ' y         <--user.. | decomposing .....................{ y } ! {y|n} perform single-scale decomposition of detection images'
  echo ' y 1 1     <--user.. | cleaning nwc1 nsc1 ..........{ y 1 1 } ! {y|n}{#} perform cleaning single scales; restart wave nwc1 scale nsc1'
  echo ' y         <--user.. | combining .......................{ y } ! {y|n} combine single-scale images over all wavelengths'
  echo ' y y 1     <--user.. | detecting smf nsd1 ..........{ y y 1 } ! {y|n}{#} detect sources; execute SFINDER; restart scale nsd1'
  echo ' y y 1 30  <--user.. | measuring bgfi itn itx { y y[+] 1 30 } ! {y|n}{#} measure source properties; bgfi-subtract, iterate from itn to itx'
  echo ' y 1.0     <--user.. | visualizing good ............{ y 1.0 } ! {y|n}{#} visualize sources with ellipses/dots; minimum goodness'
  echo ' 7          ..user.. | sreliable ...............{ optimal 7 } ! significance of reliable sources in extraction catalogs'
  echo ' 5          ..user.. | stentative ..............{ optimal 5 } ! significance of tentative sources in extraction catalogs'
  echo ' 1.0        ..user.. | snratio1min ...........{ optimal 1.0 } ! minimum signal-to-noise ratio FP/FPERR for good sources to footprint'
  echo ' 1.0        ..user.. | snratio2min ...........{ optimal 1.0 } ! minimum signal-to-noise ratio FT/FTERR for good sources to footprint'
  echo ' 2          ..user.. | ndetwaves ..........{ 1~3; optimal 2 } ! required minimum number of wavelengths for source detection'
  echo ' 0.001      ..user.. | reldiffmax ..........{ optimal 0.001 } ! maximum relative difference of footprints area for convergence'
  echo ' 2          ..user.. | savespace ..........{ 0~2; optimal 2 } ! {0|1|2} disk space saving level: clean up more and more files'
  echo ' 0          ..user.. | verbosity ..........{ 0~2; optimal 0 } ! {0|1|2} verbosity level for the screen and log file output'
  echo ' '"$def_scale1"         '    ..expert | scale1 ..................{ optimal '$def_scale1       '} ! first (smallest) scale (FWHM") to begin decomposition with'
  echo ' '"$def_nscales"        '    ..expert | nscales ................{ optimal '$def_nscales       '} ! number of spatial scales an image must be decomposed in'
  echo ' '"$def_sfactor"        '    ..expert | sfactor .................{ optimal '$def_sfactor      '} ! scale factor by which single scales should be separated'
  echo ' '"$def_fsbelowbeam"    '    ..expert | fsbelowbeam ....{ 0~1; optimal '$def_fsbelowbeam      '} ! combine scales this factor smaller than the observational beam'
  echo ' '"$def_fscalemax"      '    ..expert | fscalemax .............{ optimal '$def_fscalemax      '} ! multiplicative factor for defining the largest spatial scale'
  echo ' '"$def_ffaintestscale" '    ..expert | ffaintestscale ......{ optimal '$def_ffaintestscale   '} ! faintest-scale fraction of maximum intensity over single scales'
  echo ' '"$def_nsigmacutss"    '    ..expert | nsigmacutss .............{ optimal '$def_nsigmacutss  '} ! initial number of nsigmas for finding cut-offs in single scales'
  echo ' '"$def_nsigmacutfloor" '    ..expert | nsigmacutfloor ........{ optimal '$def_nsigmacutfloor '} ! lower limit of nsigmas for defining cut-offs in single scales'
  echo ' '"$def_skewmaxfloor"   '    ..expert | skewmaxfloor ..........{ optimal '$def_skewmaxfloor   '} ! lower limit of skewmax for defining cut-offs in single scales'
  echo ' '"$def_kurtmaxfloor"   '    ..expert | kurtmaxfloor ..........{ optimal '$def_kurtmaxfloor   '} ! lower limit of kurtmax for defining cut-offs in single scales'
  echo ' '"$def_minpixfloor"    '    ..expert | minpixfloor ........{ 0~5; optimal '$def_minpixfloor  '} ! lower limit of minpix for removal of small clusters of pixels'
  echo ' '"$def_cleantuning"    '    ..expert | cleantuning ....{ 0.5~2; optimal '$def_cleantuning    '} ! tuning factor to slightly adjust the single-scale cleaning depth'
  echo ' '"$def_comboexpomax"   '    ..expert | comboexpomax .......{ 0~9; optimal '$def_comboexpomax '} ! maximum value of the exponent for preserving higher resolution'
  echo ' '"$def_comboexpomin"   '    ..expert | comboexpomin .......{ 0~9; optimal '$def_comboexpomin '} ! minimum value of the exponent for preserving higher resolution'
  echo ' '"$def_contranoise"    '    ..expert | contranoise ....{ 1.2~2; optimal '$def_contranoise    '} ! minimum intensity contrast for removal of spurious sources'
  echo ' '"$def_factortotal"    '    ..expert | factortotal ....{ 2~2.3; optimal '$def_factortotal    '} ! factor defining footprint size from full width at half-maximum'
  echo ' y '$def_fdp $def_fbm $def_ffi'  ..expert | filaments fdp fbm ffi ....{ y '$def_fdp $def_fbm $def_ffi'} ! {n|y}{#} produce single-scale images of filamentary backgrounds'
  echo ' n n 10     ..expert | sproima fproima npxstep ....{ n n 10 } ! {n|y}{#} intensity profiles and images for sources or filaments'
  echo '#___________________________________________________________________________________________________________________________________'
} 
#___________________________________________________________________________________________________________________________________

chk_rc ()
{
# Checking return code and exiting if abnormal termination.
 
  local rc=$?
  if [[ "$rc" == "0" && "$1" != "" ]]; then rc=$1; fi
  if [[ "$rc" != "0" ]]
  then 
    where=$script; if [[ $fun != "" ]]; then where=$where': '$fun; fi; echo ' ERROR in '$where': RC='$rc': Aborted.'; echo
    exit "$rc"
  fi
}
#___________________________________________________________________________________________________________________________________

CHECK_IMGSTAT ()
{
# Check results obtained from a call to IMGSTAT and diagnose a problem, if any.

  local minimum=$1; local maximum=$2; local sigma=$3; local scriptname=$4; local funname=$5; local funoname=$6; local place=$7

  if [[ ${minimum:0:1} == "*" || ${maximum:0:1} == "*" || ${sigma:0:1} == "*" || $sigma == "0.000000000" ]]
  then echo; echo ' '$scriptname': '$funname': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' WARNING: Results from IMGSTAT ('$place'): min max std: '$minimum $maximum $sigma
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funoname; return 99
  else \rm '.+imgstat2' 2>&1; chk_rc
  fi
}
#___________________________________________________________________________________________________________________________________

LEADZEROS ()
{
# Add $1 leading zeros to an integer given in $2 and return result in $3

  local zizi; local y; local numz=$1; zizi=$2

  if [[ $numz -eq 1 ]]; then if [[ $2 -lt 10 ]]; then zizi="0"$2  ; fi; fi
  if [[ $numz -eq 2 ]]; then if [[ $2 -lt 10 ]]; then zizi="00"$2 ; else if [[ $2 -lt 100  ]]; then zizi="0"$2 ; fi; fi; fi
  if [[ $numz -eq 3 ]]; then if [[ $2 -lt 10 ]]; then zizi='000'$2; else if [[ $2 -lt 100  ]]; then zizi='00'$2; else
                                                                         if [[ $2 -lt 1000 ]]; then zizi='0'$2 ; fi; fi; fi; fi
  y=\$"$3"; eval "$3=$zizi"
}
#___________________________________________________________________________________________________________________________________

POSITION ()
{
# Finding position of a substring in a string.

  local funo=$fun; fun='POSITION'
  if [[ $2 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local substr=$1; local string=$2 

  lensub=${#substr}; lenstr=${#string}; local dlen=$(( lenstr - lensub )); local i; returnposition=0
  if [[ $lensub -le $lenstr ]]
  then for (( i=0; i <= $dlen; i++ ))
  do if [[ "$substr" == "${string:$i:$lensub}" ]]; then returnposition=$(( i + 1 )); break; fi; done; fi

  fun=$funo; return $returnposition
}
#___________________________________________________________________________________________________________________________________

COMPARE_NUMBERS ()
{ 
# Comparing two either floating-point or integer numbers.

  local funo=$fun; fun='COMPARE_NUMBERS'
  if [[ $3 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $2 != ">" && $2 != "<" && $2 != "=" && $2 != "!=" && $2 != ">=" && $2 != "<=" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Unsupported operator: "'$2'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local num1=$1; local oper=$2; local num2=$3; local result=99; local i; local res1; local res2; local dot1; local dot2
  local sign1; local sign2
  if [[ ${num1:0:1} == "-" ]]; then sign1='-'; anum1=${num1:1}; else sign1=''; anum1=$num1; fi
  if [[ ${num2:0:1} == "-" ]]; then sign2='-'; anum2=${num2:1}; else sign2=''; anum2=$num2; fi
  'POSITION' '.' "$anum1"; dot1=$returnposition
  if [[ $dot1 -eq 0 ]]; then anum1=$anum1'.0'; 'POSITION' '.' "$anum1"; dot1=$returnposition; fi
  'POSITION' '.' "$anum2"; dot2=$returnposition
  if [[ $dot2 -eq 0 ]]; then anum2=$anum2'.0'; 'POSITION' '.' "$anum2"; dot2=$returnposition; fi
  local ddot=$(( dot1 - dot2 ))
  local len1=${#anum1}; local len2=${#anum2}; local dlen=$(( len1 - len2 ))
  local fra1=$(( len1 - dot1 )); local fra2=$(( len2 - dot2 )); local dfra=$(( fra1 - fra2 ))
  if [[ $ddot -lt 0 ]]; then for (( i=1; i <= -$ddot; i++ )); do anum1='0'$anum1; done; fi
  if [[ $ddot -gt 0 ]]; then for (( i=1; i <=  $ddot; i++ )); do anum2='0'$anum2; done; fi
  if [[ $dfra -lt 0 ]]; then for (( i=1; i <= -$dfra; i++ )); do anum1=$anum1'0'; done; fi
  if [[ $dfra -gt 0 ]]; then for (( i=1; i <=  $dfra; i++ )); do anum2=$anum2'0'; done; fi
  result='0'
  if [[ ${oper:0:1} == ">"  ]]
  then 
    if [[ $sign1 == ""  && $sign2 == "-" ]]; then result='1'; fi
    if [[ $sign1 == ""  && $sign2 == ""  && $anum1 > $anum2 ]]; then result='1'; fi
    if [[ $sign1 == "-" && $sign2 == "-" && $anum1 < $anum2 ]]; then result='1'; fi
    if [[ $oper == ">=" ]]; then if [[ $anum1 == $anum2 ]]; then result='1'; fi; fi
  fi
  if [[ ${oper:0:1} == "<"  ]]
  then 
    if [[ $sign1 == "-" && $sign2 == ""  ]]; then result='1'; fi
    if [[ $sign1 == ""  && $sign2 == ""  && $anum1 < $anum2 ]]; then result='1'; fi
    if [[ $sign1 == "-" && $sign2 == "-" && $anum1 > $anum2 ]]; then result='1'; fi
    if [[ $oper == "<=" ]]; then if [[ $anum1 == $anum2 ]]; then result='1'; fi; fi
  fi
  if [[ $oper == "="  && $anum1 == $anum2 ]]; then result='1'; fi
  if [[ $oper == "!=" && $anum1 != $anum2 ]]; then result='1'; fi

  fun=$funo; return $result
}
#___________________________________________________________________________________________________________________________________

PROGRESS_BAR ()
{ 
  local funo=$fun; fun='PROGRESS_BAR'
  if [[ $1 != "complete" && $6 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'" "'$4'" "'$5'" "'$6'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local i; local nbeg; local nend; local width; local ncur; local sym='='; local nrange
  progresstitle=$1; ncur=$2; nbeg=$3; nend=$4; width=$5; char=$6

  if [[ "$1" != "complete" ]]
  then
    if [[ $ncur -eq $nbeg ]]
    then                                   
      lnend=${#nend}; ltitle=${#progresstitle}; lbar=$(( width - 3 - ltitle - 1 - lnend - 1 ))
      if [[ $lbar -gt $nend ]]; then lbar=$nend; fi; lbarp1=$(( lbar + 1 )); lback=$(( lbarp1 + lnend + 1 ))
      if [[ "$char" == "-" ]]; then echo; echo -en ' '$progresstitle' ['; else echo -en "] $nend\033[${lback}D"; fi
      for (( i=1; i <= $lbar; i++ )); do echo -en "$char"; done; echo -en "] $nend\033[${lback}D"
      nprogress=1; npos=0; sleep 1
    else
      if [[ $nprogress -eq 0 ]]
      then echo; echo ' '$script': '$funo': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Initial value /= lower bound: '$ncur $nbeg $nend $width
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
    fi
  fi
  nbegm1=$(( nbeg - 1 )); nrange=$(( nend - nbegm1 ))
  ncurm1=$(( ncur - 1 )); lncur=${#ncur}; lncurm1=${#ncurm1}; lncurm1p1=$(( lncurm1 + 1 ))
  lenr=$(echo "scale=20; $nbegm1+($ncur-($nbeg-1))*($lbar-$nbeg)/$nrange" | bc); chk_rc
  if [[ ${lenr:0:1} != "-" ]]; then leni=${lenr%.*}; else leni=0; fi

  if [[ $1 == "complete" ]]
  then 
    if [[ $ncur -ge $nend ]]
    then
      many=''
      for (( i=1; i <= $lncur; i++ )); do many=$many$sym; done
      echo -en "\033[${lncur}D$many"
    fi
    echo; fun=$funo; return 0
  fi
  lenrold=$lenr
  leniold=$leni
  if [[ $leni -lt $nprogress ]]
  then
    if [[ $ncur -eq $nbeg ]]
    then 
      echo -en "$ncur"; npos=$(( npos + lncur )); sleep 1
    else 
      npos=$(( npos - lncurm1 + lncur ))
      if [[ $npos -gt $lbar ]]; then lncorr=$(( npos - lbar )); echo -en "\033[${lncorr}D"; npos=$(( npos - lncorr )); fi
      echo -en "\033[${lncurm1}D$ncur"
    fi
  else
    nprogress=$(( nprogress + 1 )); many=''; for (( i=1; i <= $lncurm1p1; i++ )); do many=$many$sym; done
    if [[ $npos -lt $lbar ]]; then echo -en "$sym"; npos=$(( npos + 1 )); fi
    echo -en "\033[${lncurm1p1}D$many\033[${lncur}D$ncur"
  fi
  
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

GET_VERSION ()
{
  local funo='NO_FUN'; fun='GET_VERSION'
  cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
           
  if [[ "$1" == 'stopitnow' ]]
  then
    echo '  ___________________________________________________________________________'
    echo ' |                                                                           |'
    echo ' | Telling GETSOURCES to stop as soon as possible... you may have to wait... |'
    echo ' |___________________________________________________________________________|'
    echo
    echo '#_______________________________________________________________________________'  > '+stopitnow!'
    echo '#                                                                               ' >> '+stopitnow!'
    echo '#          GETSOURCES = Multi-Scale Multi-Wavelength Source Extraction          ' >> '+stopitnow!'
    echo '#              Alexander Men`shchikov, SAp IRFU CEA Saclay, France              ' >> '+stopitnow!'
    echo '#_______________________________________________________________________________' >> '+stopitnow!'
    echo '#                                                                               ' >> '+stopitnow!'
    echo ' This file can be used to nicely stop GETSOURCES in case if a user cannot access' >> '+stopitnow!'
    echo ' (or identify) the terminal session where the job is running.                   ' >> '+stopitnow!'
    echo '                                                                                ' >> '+stopitnow!'
    echo ' When a user copies this file (or creates a file with the name "+stopitnow!") in' >> '+stopitnow!'
    echo ' a directory where GETSOURCES is running, the execution of GETSOURCES will be   ' >> '+stopitnow!'
    echo ' terminated as soon as possible.                                                ' >> '+stopitnow!'
    echo '                                                                                ' >> '+stopitnow!'
    echo ' One gets the same effect by running getsources with the command-line parameter ' >> '+stopitnow!'
    echo ' "stopitnow" in the directory where it is running, i.e. "getsources stopitnow". ' >> '+stopitnow!'
    exit 0
  fi
  
  if [[ "$1" == 'help' ]]
  then
    for (( b=1; b <= 7; b++ ))
    do echo "${banner[b]}"; done
    echo; echo '                         '$cdate
    'USAGE'
    echo '_______________________________________________________________________________'
    echo
    exit 0
  fi

  revision=$1

  if [[ $GETSOURCES_BIN == "" ]]
  then
    for (( b=1; b <= 7; b++ ))
    do echo "${banner[b]}"; done
    echo; echo '                         '$cdate
    'USAGE'
    echo '_______________________________________________________________________________'
    echo
    echo ' Executing: '"$executing"
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' ERROR: Environment variable GETSOURCES_BIN not set;'
    echo '        it must point to the binary directory (bin/+GETSOURCES)'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo '  HINT: Make sure that your ~/.bashrc file contains a line like this:'
    echo '        export GETSOURCES_BIN=/some/path/to/bin/+GETSOURCES'
    echo '        and ask your computer sysadmin for help if necessary'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi

  getsdefault="$GETSOURCES_BIN/getsources"                                              
  getsrevision="$GETSOURCES_BIN/v1.$revision/getsources"                                
                                                                                        
  if [[ $GETSOURCES_DEV != "" ]]
  then getsdefault="$GETSOURCES_DEV/getsources"
  fi
  if [[ $GETSOURCES_REL != "" ]]
  then getsrevision="$GETSOURCES_REL/v1.$revision/getsources"
  fi
  
  if [[ "$revision" == "" ]]
  then 
    if [[ ! -e $getsdefault ]]
    then
      for (( b=1; b <= 7; b++ ))
      do echo "${banner[b]}"; done
      echo; echo '                         '$cdate
      'USAGE'
      echo '_______________________________________________________________________________'
      echo
      echo ' Executing: '"$executing"
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' ERROR: Default installation of GETSOURCES does not exist: file not found:'
      echo '        '\'$getsdefault\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
  else 
    if [[ -e $getsrevision ]]
    then
      $getsrevision; exit $?
    else
      for (( b=1; b <= 7; b++ ))
      do echo "${banner[b]}"; done
      echo; echo '                         '$cdate
      'USAGE'
      echo '_______________________________________________________________________________'
      echo
      echo ' Executing: '"$executing"
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' ERROR: Revision v1.'$revision' of GETSOURCES does not exist: file not found:'
      echo '        '\'$getsrevision\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
  fi

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

GET_PARAMETERS ()
{
  local funo=$fun; fun='GET_PARAMETERS'
  echo; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`; local i; local j
  echo '                         '$cdate
  echo; echo ' Executing: '"$executing"

  lenexe=${#executing}; lenscr=${#scriptname}
  lastps=$(( lenexe - lenscr )); lastp=$(( lastps - 1 ))
  
  if [[ "${executing:lastps:lenexe}" == "$scriptname" ]]; then path=${executing:0:lastp}; else path=''; fi

  if [[ $path == "" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble obtaining the path to '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  if [[ $path == '/Users/amenshch/Astronomy/+Computing/+GETSOURCES' ]]
  then
    path='/Users/amenshch/bin/+GETSOURCES'
  fi
  
  configfile='+getsources.cfg'

# Read and store the header (version) information from the very beginning of this script.

  l=0
  {
  while read linefromthisfile
  do
    if [[ ${linefromthisfile:0:7} == "banner[" && $l -le 8 ]]
    then
      l=$(( l + 1 ))
      len=${#linefromthisfile}; last=$(( len - 12 ))
      version[l]="${linefromthisfile:11:$last}"
      'POSITION' ' Version' "${version[l]}"; ncv=$returnposition
      if [[ $ncv -gt 0 ]]; then versnum=${version[l]:ncv:16}; fi
    fi
    if [[ $l -eq 7 ]]; then break; fi
  done
  } < $executing

  headerinfo[1]='#  ___________________________________________________________________________________________________________________________________'
  headerinfo[2]='# |                                                                                                                                   '
  headerinfo[3]='# | GETSOURCES = Multi-Scale Multi-Wavelength Source Extraction = '$versnum' = Alexander Men'\''shchikov, SAp IRFU CEA Saclay      '
  headerinfo[4]='# |___________________________________________________________________________________________________________________________________'

  echo "${headerinfo[1]}"  > '+log.VERSION'
  echo "${headerinfo[2]}" >> '+log.VERSION'
  echo "${headerinfo[3]}" >> '+log.VERSION'
  echo "${headerinfo[4]}" >> '+log.VERSION'
  'HISTORY'    > '+log.HISTORY'
  'CONDITIONS' > '+log.CONDITIONS'

  if [[ ! -e "$configfile" ]]
  then 
    'USAGE'
    echo '_______________________________________________________________________________'
    echo
    echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Configuration file '\'$configfile\'' does not exist'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    'DEFAULTPARAMS' > $configfile
    echo ' HINT: Default parameters saved in a new configuration file '\'$configfile\'
    echo '       Review and modify the parameters before running '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
         
  if [[ "$1" != "" ]]; then echo; echo ' Parameters:' "$*"; fi
  hell='/dev/null'

  if [[ -e '+stopitnow!' ]]; then \rm '+stopitnow!' 2>&1; chk_rc; fi
  if [[ -e '+stopitnow!stopped' ]]; then \rm '+stopitnow!stopped' 2>&1; chk_rc; fi

# Make sure that all my required utilities can be found in the system.
         
  echo; echo ' GETSOURCES WILL USE THE FOLLOWING FORTRAN UTILITIES:'
                
  $path'/cleanbg'   : 2>$hell; rc=$?
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/cleanbg'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/cleanbg' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/ellipses'  : 2>$hell; rc=$?                                                                                              
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/ellipses'..." ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/ellipses' not found or error loading shared libraries..." ; echo; exit 99; fi
  $path'/expanda'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/expanda'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/expanda' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/fftconv'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/fftconv'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/fftconv' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/finalcat'  : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/finalcat'..." ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/finalcat' not found or error loading shared libraries..." ; echo; exit 99; fi
  $path'/fmeasure'  : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/fmeasure'..."; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/fmeasure' not found or error loading shared libraries..."; echo; exit 99; fi
  $path'/imgstat'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/imgstat'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/imgstat' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/modfits'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/modfits'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/modfits' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/operate'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/operate'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/operate' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/readhead'  : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/readhead'..." ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/readhead' not found or error loading shared libraries..." ; echo; exit 99; fi
  $path'/sfinder'   : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/sfinder'..."  ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/sfinder' not found or error loading shared libraries..."  ; echo; exit 99; fi
  $path'/smeasure'  : 2>$hell; rc=$?                                                                                        
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo; echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing '$path/smeasure'..." ; echo; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility '$path/smeasure' not found or error loading shared libraries..." ; echo; exit 99; fi
  echo
  echo
  echo ' GETSOURCES WILL USE THE WCSTOOLS UTILITY XY2SKY:'
  echo
  'xy2sky' -version 2>$hell; rc=$?; wcstools='yes'
  if [[ $rc -eq 126 || $rc -eq 127 ]]; then echo ' '$script': '$fun': ERROR:'; echo; fi
  if [[ $rc -eq 126 ]]; then echo "   Trouble executing 'xy2sky'..."; wcstools='no'; fi
  if [[ $rc -eq 127 ]]; then echo "   Utility 'xy2sky' not found or error loading shared libraries..."; wcstools='no'; fi
  if [[ $wcstools == "no" ]]
  then
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: GETSOURCES WILL PRODUCE CATALOGS WITHOUT WORLD COORDINATES  '
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Enable the conversion of pixel offsets to the coordinates   '
    echo '       installing WCSTools by Jessica Mink (jmink@cfa.harvard.edu) '
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo -n '       Press Enter to acknowledge...'; read -s -t 20 answer; echo ' OK'
  else
    echo -n ' '; 'xy2sky' -version 2>&1; rc=$?; wcstools='yes'
  fi
  echo
  echo ' GETSOURCES UTILITIES AND SCRIPTS WILL BE TAKEN FROM:'
  echo; echo ' '$path
  echo; echo -n ' [10s] Press Enter to acknowledge...'; read -s -t 10 answer; echo
  echo '_______________________________________________________________________________'

# Default parameters values.

  bpixmsk=8
  bpixmskp2=$(( bpixmsk + 2 ))  #<-- width of the borders to cut off the accumulated footprints to avoid problems in CLEANBG
  bpixmskp4=$(( bpixmsk + 4 ))  #<-- width of the borders to cut off the accumulated footprints to avoid problems in CLEANBG
  navecln=0   #<-- (= 0 seems optimal) tests showed that the method works best without averaging the end points of interpolation

# Default values for nsigma parameters (can be changed in the configuration file).
  
  nsigmacutss=6.0; npixclean=1; lastbrightscalemax=0; verbosity=0; skeletonpixwidth=3
  defaultbeam=11; beam=$defaultbeam; mysimsky='no'
  scale1=0; nscales=99; sfactor=0; fscalemax=1.0; ffaintestscale=0; snratiomin=1.5
  k=1; nb=1; nwmax=0; l=0; la=0; nwa=0; nhead=0; mrtrans='no'; lastline='no'; bgfisub='-'; smp=''

# Reading input parameters from '$configfile'.

  echo; echo ' Reading input parameters from '\'$configfile\''...' #; echo
  {
  while read v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9] v[10] v[11] v[12] v[13] v[14] v[15] v[16] v[17] v[18] v[20]\
         v[21] v[22] v[23] v[24] v[25] v[26] v[27] v[28] v[29] v[30] v[31] v[32] v[33] v[34] v[35] v[36] v[37] v[38] v[39] v[40]\
         v[41] v[42] v[43] v[44] v[45] v[46] v[47] v[48] v[49] v[50] v[51] v[52] v[53] v[54] v[55] v[56] v[57] v[58] v[59] v[60]\
         v[61] v[62] v[63] v[64] v[65] v[66] v[67] v[68] v[69] v[70] v[71] v[72] v[73] v[74] v[75] v[76] v[77] v[78] v[79] v[80]\
         v[81] v[82] v[83] v[84] v[85] v[86] v[87] v[88] v[89] v[90] v[91] v[92] v[93] v[94] v[95] v[96] v[97] v[98] v[99] v[100]
  do
    if [[ "${v[0]:0:1}" != "#" ]]
    then 
      if [[ "${v[0]}" == "" ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Line #1 of the file '\'$configfile\'' is empty.'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Remove empty line(s) from the beginning of the configuration file'
        echo '       before running '$script
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
      l=$(( l + 1 ))
      if [[ $l -eq 1 ]]; then prefix=${v[0]}; fi
      if [[ $l -eq 2 ]]; then nwmax=${v[0]}; for (( i=1; i <= $nwmax; i++ )); do usewaveincombining[i]='yes'; done; fi
      if [[ $l -eq 3 ]]
      then 
        nwaves=${v[0]}; nb=$(( l + 1 ))
        for (( i=1; i <= $nwaves; i++ ))
        do
          nw[i]=${v[i]}
          if [[ ${nw[i]:0:1} == "." || ${nw[i]:0:1} == "|" ]]
          then 
            echo; echo ' '$script': '$fun': ERROR:'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo ' INFO: Trouble reading line #'$(( nhead + 3 ))' from file '\'$configfile\'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo ' HINT: Make sure that the line with numbers of wavelengths is correct'
            echo '       before running '$script
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo; return 99
          fi
        done
      fi
      if [[ $l -eq 4 ]]
      then
        for (( i=1; i <= $nwmax; i++ ))
        do
          read vd1 vd2 vd3; l=$(( l + 1 )); read vm1 vm2; l=$(( l + 1 )); read vo1 vo2; l=$(( l + 1 ))
          cfgwave[i]=${v[0]}; if [[ "${cfgwave[i]:0:1}" == "-" ]]; then cfgwave[i]=${cfgwave[i]:1}; fi
          cfgbeam[i]=${v[1]}; cfgsize[i]=${v[2]}; cfgdirp[i]=$vd1; cfgdirm[i]=$vd2
          if [[ ${cfgdirp[i]:0:2} == "~/" ]]; then cfgdirp[i]=~/${cfgdirp[i]:2}; fi
          if [[ ${cfgdirm[i]:0:2} == "~/" ]]; then cfgdirm[i]=~/${cfgdirm[i]:2}; fi
          if [[ ! -e ${cfgdirp[i]} ]]
          then echo; echo ' '$script': '$fun': ERROR:'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo ' INFO: Directory does not exist:'
            echo '       '\'$vd1\'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo ' HINT: Verify parameters in '\'$configfile\'' before running '$script
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo; return 99
          fi
          cfgdetim[i]=${vm1/.fits/}
          cfgobsim[i]=${vo1/.fits/}
          if [[ $i -eq ${nw[k]} ]]
          then
            nwave[k]=$i
            wave[k]=${v[0]}; beam[k]=${v[1]}; srcmaxsize[k]=${v[2]}; skewmax[k]=${v[3]}; kurtmax[k]=${skewmax[k]}
            weight[k]=${v[4]}; apcorrect[k]=${v[5]}; aperture[k]=${v[6]}
            directory[k]=$vd1; dirmon[k]=$vd2; detimage[k]=${vm1/.fits/}; obsimage[k]=${vo1/.fits/}
            if [[ "${wave[k]:0:1}" == "-" ]]
            then 
              wave[k]=${wave[k]:1}
##              if [[ $nwaves -gt 1 ]]
##              then 
              usewaveincombining[k]='no'
              weight[k]='-'
##              fi
            fi
            if [[ ${weight[k]} == "y" || ${weight[k]} == "n" || ${weight[k]} == "|" ]]
            then 
              echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Invalid image weight "'${weight[k]}'" at wave #'$k' in '\'$configfile\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: Make sure the weight has a numeric value before running '$script
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            if [[ ${apcorrect[k]} != "y" && ${apcorrect[k]} != "n" ]]
            then 
              echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Invalid aperture correction "'${apcorrect[k]}'" at wave #'$k' in '\'$configfile\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: Make sure the parameter is "y" or "n" before running '$script
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            if [[ ${apcorrect[k]} == "y" ]]
            then 
              if [[ ${wave[k]} != "070" && ${wave[k]} != "0070" && ${wave[k]} != "70" && \
                    ${wave[k]} != "100" && ${wave[k]} != "0100" && ${wave[k]} != "160" && ${wave[k]} != "0160" && \
                    ${wave[k]} != "161" && ${wave[k]} != "0161" && ${wave[k]} != "250" && ${wave[k]} != "0250" && \
                    ${wave[k]} != "251" && ${wave[k]} != "0251" && ${wave[k]} != "350" && ${wave[k]} != "0350" && \
                    ${wave[k]} != "500" && ${wave[k]} != "0500" ]]
              then 
                echo; echo ' '$script': '$fun': ERROR:'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo ' INFO: Invalid wavelength "'${wave[k]}'" for aperture corrections in '\'$configfile\'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo ' HINT: For PACS & SPIRE use [00]70, [0]100, [0]160, [0]250, [0]350, [0]500;'
                echo '       for other instruments the aperture correction parameter must be "n"'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo; return 99
              fi
            fi
            if [[ ${aperture[k]} == "|" ]]
            then 
              echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Invalid aperture "'${aperture[k]}'" at wave #'$k' in '\'$configfile\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: Make sure the quantity has a numeric value before running '$script
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            k=$(( k + 1 ))
          fi
          read v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9] v[10]; l=$(( l + 1 ))
        done
      fi
      nx=$(( nb + nwmax * 4 - 1 ))
      if [[ ${v[0]} == "y"  ]]; then v[0]='yes'; fi
      if [[ ${v[0]} == "n"  ]]; then v[0]='no' ; fi
      if [[ ${v[1]} == "y+" ]]; then v[1]='yes'; smp='+'; fi
      if [[ ${v[1]} == "y"  ]]; then v[1]='yes'; fi
      if [[ ${v[1]} == "n"  ]]; then v[1]='no' ; fi
      if [[ $l -eq $(( nx +  1 )) ]]; then    pathinitial=${v[0]}; fi
      if [[ $l -eq $(( nx +  2 )) ]]; then     flattening=${v[0]}; doflatten=${v[1]}; fi
      if [[ $l -eq $(( nx +  3 )) ]]; then    decomposing=${v[0]}; fi
      if [[ $l -eq $(( nx +  4 )) ]]; then       cleaning=${v[0]}; nwc1=${v[1]}; nsc1=${v[2]}; fi
      if [[ $l -eq $(( nx +  5 )) ]]; then      combining=${v[0]}; fi
      if [[ $l -eq $(( nx +  6 )) ]]; then      detecting=${v[0]}; sfinding=${v[1]}; nsd1=${v[2]}; fi
      if [[ $l -eq $(( nx +  7 )) ]]; then      measuring=${v[0]}; bgfisub=${v[1]}; iterbeg=${v[2]}; itermax=${v[3]}; fi
      if [[ $l -eq $(( nx +  8 )) ]]; then    visualizing=${v[0]}; goodmin=${v[1]}; fi
      if [[ $l -eq $(( nx +  9 )) ]]; then      sreliable=${v[0]}; ssr=${v[0]:0:1}; if [[ $ssr == "+" ]]; then sreliable=${v[0]:1}; fi; fi
      if [[ $l -eq $(( nx + 10 )) ]]; then     stentative=${v[0]}; sst=${v[0]:0:1}; if [[ $sst == "+" ]]; then stentative=${v[0]:1}; fi; fi
      if [[ $l -eq $(( nx + 11 )) ]]; then    snratio1min=${v[0]}; fi
      if [[ $l -eq $(( nx + 12 )) ]]; then    snratio2min=${v[0]}; fi
      if [[ $l -eq $(( nx + 13 )) ]]; then      ndetwaves=${v[0]}; fi
      if [[ $l -eq $(( nx + 14 )) ]]; then     reldiffmax=${v[0]}; fi
      if [[ $l -eq $(( nx + 15 )) ]]; then      savespace=${v[0]}; fi
      if [[ $l -eq $(( nx + 16 )) ]]; then      verbosity=${v[0]}; fi
      if [[ $l -eq $(( nx + 17 )) ]]; then         scale1=${v[0]}; fi
      if [[ $l -eq $(( nx + 18 )) ]]; then        nscales=${v[0]}; fi
      if [[ $l -eq $(( nx + 19 )) ]]; then        sfactor=${v[0]}; fi
      if [[ $l -eq $(( nx + 20 )) ]]; then    fsbelowbeam=${v[0]}; fi
      if [[ $l -eq $(( nx + 21 )) ]]; then      fscalemax=${v[0]}; sfsx=${v[0]:0:1}; if [[ $sfsx == "+" ]]; then fscalemax=${v[0]:1}; fi; fi
      if [[ $l -eq $(( nx + 22 )) ]]; then ffaintestscale=${v[0]}; fi
      if [[ $l -eq $(( nx + 23 )) ]]; then    nsigmacutss=${v[0]}; fi
      if [[ $l -eq $(( nx + 24 )) ]]; then nsigmacutfloor=${v[0]}; fi
      if [[ $l -eq $(( nx + 25 )) ]]; then   skewmaxfloor=${v[0]}; fi
      if [[ $l -eq $(( nx + 26 )) ]]; then   kurtmaxfloor=${v[0]}; fi
      if [[ $l -eq $(( nx + 27 )) ]]; then    minpixfloor=${v[0]}; fi
      if [[ $l -eq $(( nx + 28 )) ]]; then    cleantuning=${v[0]}; fi
      if [[ $l -eq $(( nx + 29 )) ]]; then   comboexpomax=${v[0]}; fi
      if [[ $l -eq $(( nx + 30 )) ]]; then   comboexpomin=${v[0]}; fi
      if [[ $l -eq $(( nx + 31 )) ]]; then    contranoise=${v[0]}; scn=${v[0]:0:1}; if [[ $scn == "+" ]]; then contranoise=${v[0]:1}; fi; fi
      if [[ $l -eq $(( nx + 32 )) ]]; then    factortotal=${v[0]}; fi
      if [[ $l -eq $(( nx + 33 )) ]]; then      filaments=${v[0]}; fdp=${v[1]}; fbm=${v[2]}; ffi=${v[3]}; fi
      if [[ $l -eq $(( nx + 34 )) ]]; then        sproima=${v[0]}; fproima=${v[1]}; npxstep=${v[2]}; fi
      if [[ ${nsc1:0:3} == "<--" ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid cleaning restart scale '\'$nsc1\'' in file '\'$configfile\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the quantity has a numeric value before running '$script
        echo '       Save default configuration file to see valid options.'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
      if [[ $bgfisub != "-" && $bgfisub != "yes" && $bgfisub != "no" ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid measurement option '\'$bgfisub\'' in file '\'$configfile\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the quantity has value "y" or "n" before running '$script
        echo '       Save default configuration file to see valid options.'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
      if [[ ${fdp:0:2} == ".." || ${fbm:0:2} == ".." || ${elo:0:2} == ".." ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid parameters for filaments in file '\'$configfile\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the quantities have numeric values before running '$script
        echo '       Save default configuration file to see valid options.'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
      if [[ ${npxstep:0:2} == ".." ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid parameter NPXSTEP = '\'$npxstep\'' in file '\'$configfile\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the quantity has numeric value before running '$script
        echo '       Save default configuration file to see valid options.'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
    else
      nhead=$(( nhead + 1 )) 
    fi
    totalparams=34
    if [[ $l -eq $(( nx + totalparams )) && ${v[0]:0:4} == "#___" ]]; then lastline='yes'; fi
  done
  if [[ $lastline == "no" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble finding end of the configuration file '\'$configfile\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Make sure that the total number of lines is '$(( nhead + nx + totalparams ))
    echo '       before running '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  } < $configfile
#___________________________________________________________________________________________________________________________________

  if [[ ${pathinitial:0:2} == "~/" ]]; then pathinitial=~/${pathinitial:2}; fi
  if [[ ${pathinitial:0:1} != "/" ]]; then pathinitial=`\cd $pathinitial; pwd`; fi
  verb=''
  if [[ $verbosity -eq 0 ]]; then verb='-verb0'; fi
  if [[ $verbosity -eq 1 ]]; then verb='-verb1'; fi
  if [[ $verbosity -eq 2 ]]; then verb='-verb2'; fi
  if [[ $verb == "" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Verbosity '\'$verbosity\'' out of range [0,1,2] ('\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Only these values of verbosity level are supported: 0, 1, or 2'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi

  subdirbackups=$originpath'/+backups'
  subdircatalogs=$originpath'/+catalogs'
  subdirfilaments=$originpath'/+filaments'
  subdirinterface=$originpath'/+interface'
  subdiriterations=$originpath'/+iterations'
  subdirsources=$originpath'/+sources'
  subdirvisuals=$originpath'/+visuals'
  subdirannuli=$subdiriterations'/+annuli'
  subdirsprofiles=$subdirsources'/+profiles'

  finalcatalog=$prefix'.sw.final.relitent.cat'
  finellreliable=$subdirvisuals'/'$prefix'.sw.final.reliable.ell'
  finellrelitent=$subdirvisuals'/'$prefix'.sw.final.relitent.ell'
  findotreliable=$subdirvisuals'/'$prefix'.sw.final.reliable.dot'
  findotrelitent=$subdirvisuals'/'$prefix'.sw.final.relitent.dot'
  finfooreliable=$subdirvisuals'/'$prefix'.sw.final.reliable.foo'
  finfoorelitent=$subdirvisuals'/'$prefix'.sw.final.relitent.foo'

  for (( i=1; i <= $nwmax; i++ ))
  do
    for (( ii=1; ii <= $nwmax; ii++ ))
    do
      if [[ $ii != $i && "${cfgwave[ii]}" == "${cfgwave[i]}" ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Configuration file contains images with the same wavelength: '${cfgwave[i]}
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the wavelengths are different in at least a single digit'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
    done
    filmaxsize[i]=0
    filmaxsizeo[i]=0
  done
  if [[ ! -e $pathinitial ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Initial extraction directory in '\'$configfile\'' does not exist:'
    echo '       '\'$pathinitial\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Make sure the entire directory structure has been created'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
###    \mkdir -p $pathinitial
  fi
  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ ${directory[i]:0:2} == "~/" ]]; then directory[i]=~/${directory[i]:2}; fi
    if [[ ! -e ${directory[i]} ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Directory with prepared original images does not exist:'
      echo '       '\'${directory[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Correct the path in '\'$configfile\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ! -e ${directory[i]}'/'${detimage[i]}'.fits' ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File with the detection image does not exist:'
      echo '       '\'${directory[i]}'/'${detimage[i]}'.fits'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Correct the data in '\'$configfile\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    imagepath[i]=`\cd ${directory[i]}; pwd`
  done

  imagesize=`\du -sk ${imagepath[1]}'/'${detimage[1]}'.fits'`
  'POSITION' '/' "$imagesize"; ris=$returnposition
  if [[ $ris -eq 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble finding size of the file:'
    echo '       '\'${imagepath[1]}'/'${detimage[1]}'.fits'\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  ris=$(( ris - 2 ))
  imagesize=${imagesize:0:ris}
  imagesize=$(echo "scale=6; $imagesize/1024" | bc)
  if [[ ${imagesize:0:1} == "." ]]; then imagesize='0'$imagesize; fi
  echo
  echo ' Size of the input FITS images: '$imagesize' MB'

  'POSITION' "$homepath" "$originpath"; rchpath=$returnposition

  if [[ $rchpath -gt 0 ]]
  then
    lhpath=${#homepath}
    ihpath=$(( rchpath + lhpath - 1 ))
    tilde='~'
  else
    ihpath=0
    tilde=''
  fi
  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ ! -e ${dirmon[i]} ]]
    then 
      if [[ ${dirmon[i]} == '|' ]]
      then
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid monochromatic directory in '\'$configfile\'':'
        echo '       '\'${dirmon[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the separator symbol "|" has a leading space: " |"'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Monochromatic directory in '\'$configfile\'' does not exist:'
        echo '       '\'${dirmon[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make sure the entire directory structure has been created'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
###        \mkdir -p ${dirmon[i]}
      fi
    fi
  done
  suffix=$prefix'.' 
  currentroot=`\cd ..; pwd`
  initialroot=`\cd $pathinitial/..; pwd`
  echo
  echo ' Initial extraction:'
  echo ' '$tilde${initialroot:ihpath}
  echo
  echo ' Current extraction:'
  echo ' '$tilde${currentroot:ihpath}
  echo
  echo ' Current directory:'
  echo ' '$tilde${originpath:ihpath}
  echo
  if [[ $nwaves -eq 1 ]]
  then echo ' Monochromatic directory:'
  else echo ' Monochromatic directories:'
  fi
  for (( i=1; i <= $nwaves; i++ ))
  do
    suffix=$suffix${nwave[i]}
    dirmono[i]=`\cd ${dirmon[i]}; pwd`
    echo ' '$tilde${dirmono[i]:ihpath}
    if [[ -e ${dirmono[i]}'/'$prefix'.'${wave[i]}'.det.original.fits' || -e $prefix'.'${wave[i]}'.det.original.fits' ]]
    then
      flattening='done'
    fi
  done
  if [[ $flattening == 'yes' || $flattening == 'done' ]]
  then
    echo
    echo ' Initial combo directory:'
    echo ' '$tilde${pathinitial:ihpath}
  fi
  
  filmaxsizemax=0
###  srcmaxsizemax=0

  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ -e ${dirmono[i]}'/+interface' ]]
    then 
      if [[ $filaments == "yes" && ${dirmono[i]}'/+interface' != $subdirinterface && ${usewaveincombining[i]} == "yes" ]]
      then
        if [[ -e ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize' ]]
        then 
          if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi
          \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize' $subdirinterface 2>&1; chk_rc
  
          { read filmaxsize[i] 
          } < ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize'
            
          filmaxsize[i]=${filmaxsize[i]%.*}   #<-- make the number integer
          filmaxsizeo[i]=${filmaxsize[i]}
          if [[ ${filmaxsize[i]} -gt $filmaxsizemax ]]
          then filmaxsizemax=${filmaxsize[i]}
          fi 
        else
          echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Unsupported method of running GETSOURCES: this run is not possible:'
          echo '       directory or file not found:'
          echo '       '\'${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize'\'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: You may have incorrectly skipped some processing steps; new users are'
          echo '       invited to follow (as closely as possible) the approach described in'
          echo '       '\'$GETSOURCES_BIN'/QUICK.START.GUIDE'\'
          echo '       to ensure the easiest and most accurate source extraction'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; return 99
        fi
      fi
    fi
  done
  
  combinedinitialextraction='no'
  
  if [[ $flattening == "no" && $decomposing == "no" && $cleaning == "no" && ( $nwaves -gt 1 || $nwmax -eq 1 ) ]]
  then
    for (( i=1; i <= $nwaves; i++ ))
    do
      if [[ -e ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.srcmaxsize' ]]
      then
        combinedinitialextraction='yes'
        if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi

###        { read srcmaxsize[i]
###        } < ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.srcmaxsize'
###
###        srcmaxsize[i]=${srcmaxsize[i]%.*}   #<-- make the number integer
###        if [[ ${srcmaxsize[i]} -gt $srcmaxsizemax ]]
###        then srcmaxsizemax=${srcmaxsize[i]}
###        fi 
        
        if [[ ${dirmono[i]}'/+interface' != $subdirinterface ]]
        then
          \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.srcmaxsize' $subdirinterface 2>&1; chk_rc
          if [[ -e ${dirmono[i]}'/+interface/flatfoot.'${wave[i]}'.fits' ]]
          then \cp ${dirmono[i]}'/+interface/flatfoot.'${wave[i]}'.fits' $subdirinterface 2>&1; chk_rc
          fi
          if [[ $filaments == "yes" ]]
          then
            \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize' $subdirinterface 2>&1; chk_rc
            \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.fits' $subdirinterface 2>&1; chk_rc
            \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.masks.fits' $subdirinterface 2>&1; chk_rc
            \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.fits' $subdirinterface 2>&1; chk_rc

            'DEFINE_FILAMENTS_SCALES' ${beam[i]}

            for (( l=0; l <= $nsskel; l++ ))
            do
              zl=${zfilscale[l]}'as'
              if [[ -e ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.skeletons.'$zl'.fits' ]]
              then \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.skeletons.'$zl'.fits' $subdirinterface 2>&1; chk_rc
              fi
            done
##            if [[ `echo ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.'????'as.fits'` != \
##                  ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.????as.fits' ]]
##            then 
##              \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.'????'as.fits' $subdirinterface 2>&1; chk_rc
##            fi
            if [[ `echo ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.'????'as.fits'` != \
                  ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.????as.fits' ]]
            then 
              \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.'????'as.fits' $subdirinterface 2>&1; chk_rc
            fi
          fi
        fi

        for (( ii=1; ii <= $nwmax; ii++ ))
        do
          if [[ "${cfgwave[ii]}" == "${wave[i]}" ]]
          then
            if [[ "${cfgsize[ii]:0:1}" == "+" ]]
            then
              cfgsize[ii]=${cfgsize[ii]:1}
###              srcmaxsize[i]=${cfgsize[ii]}
###              echo ${srcmaxsize[i]} > $subdirinterface'/'$prefix'.'${wave[i]}'.srcmaxsize'
            else
              cfgsize[ii]=${cfgsize[ii]%.*}   #<-- make the number integer
###              cfgsize[ii]=${srcmaxsize[i]}
            fi
          fi
        done
      fi
    done
  fi
  
##  if [[ $combinedinitialextraction == "no" && $flattening == "no" && $nwaves -gt 1 ]]
##  then
##    echo; echo ' '$script': '$fun': ERROR:'
##    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##    echo ' INFO: Unsupported method of running GETSOURCES: the multi-wavelength run is'
##    echo '       not possible in this setup (see '\'$configfile\'')'
##    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##    echo ' HINT: You may have incorrectly skipped some processing steps; new users are'
##    echo '       invited to follow (as closely ad possible) the approach described in'
##    echo '       '\'$GETSOURCES_BIN'/QUICK.START.GUIDE'\'
##    echo '       to ensure the easiest and most accurate source extraction'
##    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##    echo; return 99
##  fi

  if [[ ${originpath:ihpath} != ${dirmono[1]:ihpath} && $nwaves -eq 1 && $nwmax -gt 1 && \
        ($decomposing == "yes" || $cleaning == "yes") ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Unsupported method of running GETSOURCES: wrong current directory for'
    echo '       a monochromatic extraction (see '\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: You may need to change to another monochrom directory; new users are'
    echo '       invited to follow (as closely ad possible) the approach described in'
    echo '       '\'$GETSOURCES_BIN'/QUICK.START.GUIDE'\'
    echo '       to ensure the easiest and most accurate source extraction'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  
  if [[ ($flattening == "yes" || $flattening == "done") || "$currentroot" != "$initialroot" ]]
  then
    for (( ii=1; ii <= $nwmax; ii++ ))
    do
      ni=0
      for (( i=1; i <= $nwaves; i++ ))
      do
        if [[ "${cfgwave[ii]}" == "${wave[i]}" ]]
        then ni=$i; break
        fi
      done

      if [[ -e $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.srcmaxsize' || "${cfgsize[ii]:0:1}" == "+" ]]
      then
        if [[ "${cfgsize[ii]:0:1}" == "+" ]]
        then
          cfgsize[ii]=${cfgsize[ii]:1}
        else
          { read cfgsize[ii] 
          } < $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.srcmaxsize'
        fi
        if [[ $ni -gt 0 ]]
        then
          srcmaxsize[ni]=${cfgsize[ii]}
        fi
      else
        for (( i=1; i <= $nwaves; i++ ))
        do
          if [[ "${cfgwave[ii]}" == "${wave[i]}" ]]
          then
            if [[ ! -e $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.srcmaxsize' ]]
            then
              echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Unsupported method of running GETSOURCES: the flattening run is not'
              echo '       possible: directory or file not found:'
              echo '       '\'$pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.srcmaxsize'\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: You may have incorrectly skipped some processing steps; new users are'
              echo '       invited to follow (as closely ad possible) the approach described in'
              echo '       '\'$GETSOURCES_BIN'/QUICK.START.GUIDE'\'
              echo '       to ensure the easiest and most accurate source extraction'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
          fi
        done
      fi

      if [[ -e $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.filmaxsize' && ${usewaveincombining[ii]} == "yes" ]]
      then
        { read filmaxsizeii 
        } < $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.filmaxsize'

        filmaxsizeii=${filmaxsizeii%.*}   #<-- make the number integer
        if [[ $filmaxsizeii -gt $filmaxsizemax ]]
        then filmaxsizemax=$filmaxsizeii
        fi
        if [[ $ni -gt 0 ]]
        then
          filmaxsize[ni]=$filmaxsizeii
          filmaxsizeo[ni]=${filmaxsize[ni]}
        fi
      else
        for (( i=1; i <= $nwaves; i++ ))
        do
          if [[ "${cfgwave[ii]}" == "${wave[i]}" ]]
          then
            if [[ ! -e $pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.filmaxsize' ]]
            then
              echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Unsupported method of running GETSOURCES: the final extraction run is'
              echo '       not possible: directory or file not found:'
              echo '       '\'$pathinitial'/+interface/'$prefix'.'${cfgwave[ii]}'.filmaxsize'\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: You may have incorrectly skipped some processing steps; new users are'
              echo '       invited to follow (as closely ad possible) the approach described in'
              echo '       '\'$GETSOURCES_BIN'/QUICK.START.GUIDE'\'
              echo '       to ensure the easiest and most accurate source extraction'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
          fi
        done
      fi
    done
  fi
  
  for (( ii=1; ii <= $nwmax; ii++ ))
  do
    if [[ "${cfgsize[ii]:0:1}" == "+" ]]
    then
      cfgsize[ii]=${cfgsize[ii]:1}
    fi
    cfgsize[ii]=${cfgsize[ii]%.*}   #<-- make the number integer
  done

  workingpath=$originpath

  'POSITION' '.' "$prefix"; dot=$returnposition
  
  if [[ $dot -gt 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Dots in the PREFIX '\'$prefix\'' not allowed ('\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: PREFIX specifies a suitable name to be used for naming output files'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  if [[ $nwmax -ge 100 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Maximum number of wavelengths NWMAX exceeds 9 ('\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: This version of GETSOURCES is limited to maximum 9 wavebands'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi

  sfactorcfg=$sfactor

  if [[ ${sfactor:0:1} == "0" && ${nscales:0:1} == "0" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid choice of both SFACTOR = 0 and NSCALES = 0 ('\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Only one of the quantities may have a value equal to zero'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  if [[ $iterbeg -le 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Number of first iteration ITERBEG <= 0 ('\'$configfile\'')'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: The number of the first measurement iteration must be greater than zero'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi
  if [[ $iterbeg -gt 1 && ! -e $subdiriterations ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Sub-directory for measurement iterations not found:'
    echo '       '\'$subdiriterations\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi

# Initialize variables and arrays.

  nwavesm1=$(( nwaves - 1 )); nwavesm2=$(( nwaves - 2 )); nsb1=0
  if [[ $nwc1 -lt 1 || $nwc1 -gt $nwaves  ]]; then nwc1=1; fi
  if [[ $nsd1 -lt 1 || ($nscales -gt 0 && $nsd1 -gt $nscales) || ($nscales -eq 0 && $nsd1 -gt 99) ]]; then nsd1=1; fi

# Determine maximum beam size over all waves.

  cfgbeammin=999; cfgbeammax=0; cfgmaxsizemax=0

  for (( i=1; i <= $nwmax; i++ ))
  do
    'COMPARE_NUMBERS' ${cfgbeam[i]} '<' $cfgbeammin; rslt=$?
    if [[ $rslt -eq 1 ]]; then cfgbeammin=${cfgbeam[i]}; fi
    'COMPARE_NUMBERS' ${cfgbeam[i]} '>' $cfgbeammax; rslt=$?
    if [[ $rslt -eq 1 ]]; then cfgbeammax=${cfgbeam[i]}; fi
    'COMPARE_NUMBERS' ${cfgsize[i]} '>' $cfgmaxsizemax; rslt=$?
    if [[ $rslt -eq 1 ]]; then cfgmaxsizemax=${cfgsize[i]}; fi 
  done
    
  beamav=0; beammin=999; beammax=0; srcmaxsizebmax=0; filmaxsizebmax=0; aperturemax=0

  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ "${beam[i]:0:1}" == "0" && "${beam[i]:0:2}" != "0." ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Leading zeros in beam sizes not allowed ('\'$configfile\'')'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Remove leading zeros from beam sizes; they should have a usual form'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi

    'COMPARE_NUMBERS' ${beam[i]} '<' $beammin; rslt=$?
    if [[ $rslt -eq 1 ]]; then beammin=${beam[i]}; fi
    'COMPARE_NUMBERS' ${beam[i]} '>' $beammax; rslt=$?
    if [[ $rslt -eq 1 ]]; then beammax=${beam[i]}; fi

    beamav=$(echo "scale=3; $beamav+${beam[i]}/$nwaves" | bc); chk_rc
           
    if [[ "${srcmaxsize[i]:0:1}" == "+" ]]
    then
      srcmaxsize[i]=${srcmaxsize[i]:1}
    fi
###    srcmaxsize[i]=${srcmaxsize[i]%.*}   #<-- make the number integer
    srcmaxsizeb[i]=${srcmaxsize[i]}
    filmaxsizeb[i]=${filmaxsize[i]}
    beamb[i]=${beam[i]}

    'COMPARE_NUMBERS' ${srcmaxsizeb[i]} '>' $srcmaxsizebmax; rslt=$?
    if [[ $rslt -eq 1 ]]; then srcmaxsizebmax=${srcmaxsizeb[i]}; fi
    'COMPARE_NUMBERS' ${filmaxsizeb[i]} '>' $filmaxsizebmax; rslt=$?
    if [[ $rslt -eq 1 ]]; then filmaxsizebmax=${filmaxsizeb[i]}; fi

    if [[ "${aperture[i]:0:1}" == "+" ]]
    then aperturei=${aperture[i]:1}
    else aperturei=${aperture[i]}
    fi
    'COMPARE_NUMBERS' $aperturei '>' $aperturemax; rslt=$?
    if [[ $rslt -eq 1 ]]; then aperturemax=$aperturei; fi
  done
  
  if [[ $aperturemax == '0' ]]
  then apertures='n'
  else apertures='y'
  fi

# Diagnose problems with the lengths of wavelengths.
    
  lenwavo=0; lenmono=0
  for (( i=1; i <= $nwmax; i++ ))
  do
    lenwav=${#cfgwave[i]}
    if [[ $lenwavo -gt 0 && $lenwav -ne $lenwavo ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Lengths of the wavelengths differ in '\'$configfile\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use leading zeros to make sure the waves have the same length'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    lenwavo=$lenwav
    lenmon=${#cfgdirm[i]}
    if [[ $lenmono -gt 0 && $lenmon -ne $lenmono ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Lengths of the monochromatic directories differ in '\'$configfile\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use leading zeros to make sure the names have the same length'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    lenmono=$lenmon
  done
  lenbmx=${#beammax}
  lenszx=${#srcmaxsizebmax}
  lenfix=${#filmaxsizebmax}
  for (( i=1; i <= $nwaves; i++ ))
  do
    lenbm=${#beamb[i]}; ladbz=$(( lenbmx - lenbm ))
    lensz=${#srcmaxsizeb[i]}; ladsz=$(( lenszx - lensz ))
    lenfi=${#filmaxsizeb[i]}; ladfi=$(( lenfix - lenfi ))
    if [[ $ladbz -gt 0 ]]
    then 
      for (( l=1; l <= $ladbz; l++ )); do beamb[i]=' '"${beamb[i]}"; done
    fi
    if [[ $ladsz -gt 0 ]]
    then 
      for (( l=1; l <= $ladsz; l++ )); do srcmaxsizeb[i]=' '"${srcmaxsizeb[i]}"; done
    fi
    if [[ $ladfi -gt 0 ]]
    then 
      for (( l=1; l <= $ladfi; l++ )); do filmaxsizeb[i]=' '"${filmaxsizeb[i]}"; done
    fi
    detectionclone[i]=$prefix'.'${wave[i]}'.det'
    measuremtclone[i]=$prefix'.'${wave[i]}'.obs'
    imageomask[i]=$prefix'.'${wave[i]}'.omask'
    imagebsomask[i]=$prefix'.'${wave[i]}'.bs.omask'
  done
  
# Check the input images for correctness of the FITS keywords.
# Diagnose problems with the paths or files.

  lendir=${#pathinitial}
  lendirm1=$(( lendir - 1 ))
  if [[ ${pathinitial:lendirm1} == "/" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trailing slash "/" is found in the configuration path:'
    echo '       '\'${pathinitial}\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Trailing slashes should not be used in the names of directories'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  fi

  for (( i=1; i <= $nwaves; i++ ))
  do 
    lendir=${#dirmono[i]}
    lendirm1=$(( lendir - 1 ))
    if [[ ${dirmono[i]:lendirm1} == "/" ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Trailing slash "/" is found in the configuration path:'
      echo '       '\'${dirmono[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Trailing slashes should not be used in the names of directories'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    lendir=${#imagepath[i]}
    lendirm1=$(( lendir - 1 ))
    if [[ ${imagepath[i]:lendirm1} == "/" ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Trailing slash "/" is found in the configuration path:'
      echo '       '\'${imagepath[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Trailing slashes should not be used in the names of directories'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ${dirmono[i]:0:3} == "..." ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Invalid name of the monochromatic extraction directory:'
      echo '       '\'${dirmono[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: The name starts with at least three dots'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ! -e ${dirmono[i]} ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Monochromatic extraction directory not found:'
      echo '       '\'${dirmono[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: The directory for source extraction must exist; check the path for typos'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ! -e ${imagepath[i]} ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Directory with input images not found:'
      echo '       '\'${imagepath[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: The directory with prepared images must exist; check the path for typos'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ! -e ${imagepath[i]}'/'${detimage[i]}'.fits' ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File with a detection image not found:'
      echo '       '\'${imagepath[i]}'/'${detimage[i]}'.fits'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Prepared detection image must exist; check the path for typos'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    if [[ ! -e ${imagepath[i]}'/'${obsimage[i]}'.fits' ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File with a measurement image not found:'
      echo '       '\'${imagepath[i]}'/'${obsimage[i]}'.fits'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Prepared measurement image must exist; check the path for typos'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; return 99
    fi
    imagetype[i]='other'
  done
    
# Copy files to the current directory.
# Should only be done when processing images in the main steps.
  
  if [[ $flattening == 'yes' || $decomposing == 'yes' || $cleaning == "yes" || $combining == "yes" || $detecting == "yes" ]]
  then
    for (( i=1; i <= $nwaves; i++ ))
    do 
      echo
      im1=$(( i - 1 ))
      if [[ ${obsimage[i]:0:5} == "sky_c" || ${obsimage[i]:0:5} == "skysc" || ${obsimage[i]:0:5} == "sky_i" ]]
      then
        mysimsky='yes'
      fi

      if [[ $flattening != 'yes' && $flattening != 'done' && \
            ("$workingpath" == "${dirmono[i]}" || ("$workingpath" == "$pathinitial" && $cleaning == "yes")) ]]
      then
        echo ' Directory with images:'
        echo ' '${directory[i]}
        echo ' Copying '${obsimage[i]}'.fits...'
        \cp ${imagepath[i]}'/'${obsimage[i]}'.fits' ${measuremtclone[i]}'.fits' 2>&1; chk_rc
      else
        if [[ "$workingpath" != "${dirmono[i]}" && -e ${dirmono[i]}'/'${measuremtclone[i]}'.fits' ]]
        then
          echo ' Directory with images:'
          echo ' '${dirmono[i]}
          echo ' Copying '${dirmon[i]}'/'${measuremtclone[i]}'.fits...'
          \cp ${dirmono[i]}'/'${measuremtclone[i]}'.fits' ${measuremtclone[i]}'.fits' 2>&1; chk_rc
          echo ' Copying '${dirmon[i]}'/'${measuremtclone[i]}'.fs.fits...'
          \cp ${dirmono[i]}'/'${measuremtclone[i]}'.fs.fits' ${measuremtclone[i]}'.fs.fits' 2>&1; chk_rc
          echo ' Copying '${dirmon[i]}'/'${measuremtclone[i]}'.fs+.fits...'
          \cp ${dirmono[i]}'/'${measuremtclone[i]}'.fs+.fits' ${measuremtclone[i]}'.fs+.fits' 2>&1; chk_rc
        else
          if [[ $cleaning == "yes" && -e $pathinitial'/'${measuremtclone[i]}'.fits' ]]
          then
            echo ' Directory with images:'
            echo ' '$pathinitial
            echo ' Copying '${measuremtclone[i]}'.fits...'
            \cp $pathinitial'/'${measuremtclone[i]}'.fits' ${measuremtclone[i]}'.fits' 2>&1; chk_rc
            echo ' Copying '${measuremtclone[i]}'.fs.fits...'
            \cp $pathinitial'/'${measuremtclone[i]}'.fs.fits' ${measuremtclone[i]}'.fs.fits' 2>&1; chk_rc
            echo ' Copying '${measuremtclone[i]}'.fs+.fits...'
            \cp $pathinitial'/'${measuremtclone[i]}'.fs+.fits' ${measuremtclone[i]}'.fs+.fits' 2>&1; chk_rc
          else
            if [[ ! -e ${measuremtclone[i]}'.fits' ]]
            then echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Observed image not found: '\'${measuremtclone[i]}'.fits'\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' HINT: Verify correctness of directory names in '\'$configfile\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            echo ' Using existing image ./'${measuremtclone[i]}'.fits...'
            if [[ $filaments == "yes" || $filaments == "done" ]]
            then
              echo ' Using existing image ./'${measuremtclone[i]}'.fs.fits...'
              echo ' Using existing image ./'${measuremtclone[i]}'.fs+.fits...'
            fi
          fi
        fi
      fi
      
      if [[ $flattening != 'yes' && $flattening != 'done' && \
            ("$workingpath" == "${dirmono[i]}" || ("$workingpath" == "$pathinitial" && $cleaning == "yes")) ]]
      then
        echo ' Copying '${detimage[i]}'.fits...'
        \cp ${imagepath[i]}'/'${detimage[i]}'.fits' ${detectionclone[i]}'.fits' 2>&1; chk_rc
      
        echo ' Copying '${detimage[i]}'.omask.fits...'
        if [[ ! -e ${imagepath[i]}'/'${detimage[i]}'.omask.fits' ]]
        then echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Observational mask '\'${detimage[i]}'.omask.fits'\'
          echo '       not found in '\'${imagepath[i]}\'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; return 99
        fi
        \cp ${imagepath[i]}'/'${detimage[i]}'.omask.fits' ${imageomask[i]}'.fits' 2>&1; chk_rc
      else
        if [[ "$workingpath" != "${dirmono[i]}" && -e ${dirmono[i]}'/'${detectionclone[i]}'.fits' ]]
        then
          echo ' Copying '${dirmon[i]}'/'${detectionclone[i]}'.fits...'
          \cp ${dirmono[i]}'/'${detectionclone[i]}'.fits' ${detectionclone[i]}'.fits' 2>&1; chk_rc
          echo ' Copying '${dirmon[i]}'/'${detectionclone[i]}'.fs.fits...'
          \cp ${dirmono[i]}'/'${detectionclone[i]}'.fs.fits' ${detectionclone[i]}'.fs.fits' 2>&1; chk_rc
          echo ' Copying '${dirmon[i]}'/'${detectionclone[i]}'.fs+.fits...'
          \cp ${dirmono[i]}'/'${detectionclone[i]}'.fs+.fits' ${detectionclone[i]}'.fs+.fits' 2>&1; chk_rc
        else
          if [[ $flattening != 'done' && "$workingpath" != "$pathinitial" && -e $pathinitial'/'${detectionclone[i]}'.fits' ]]
          then
            echo ' Copying '${detectionclone[i]}'.fits...'
            \cp $pathinitial'/'${detectionclone[i]}'.fits' ${detectionclone[i]}'.fits' 2>&1; chk_rc
            echo ' Copying '${detectionclone[i]}'.fs.fits...'
            \cp $pathinitial'/'${detectionclone[i]}'.fs.fits' ${detectionclone[i]}'.fs.fits' 2>&1; chk_rc
            echo ' Copying '${detectionclone[i]}'.fs+.fits...'
            \cp $pathinitial'/'${detectionclone[i]}'.fs+.fits' ${detectionclone[i]}'.fs+.fits' 2>&1; chk_rc
          else
            if [[ ! -e ${detectionclone[i]}'.fits' ]]
            then echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Detection image not found: '\'${detectionclone[i]}'.fits'\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            echo ' Using existing image ./'${detectionclone[i]}'.fits...'
            if [[ $filaments == "yes" || $filaments == "done" ]]
            then
              echo ' Using existing image ./'${detectionclone[i]}'.fs.fits...'
              echo ' Using existing image ./'${detectionclone[i]}'.fs+.fits...'
            fi
          fi
        fi
      
        if [[ "$workingpath" != "${dirmono[i]}" && -e ${dirmono[i]}'/'${imageomask[i]}'.fits' ]]
        then
          echo ' Copying '${dirmon[i]}'/'${imageomask[i]}'.fits...'
          \cp ${dirmono[i]}'/'${imageomask[i]}'.fits' ${imageomask[i]}'.fits' 2>&1; chk_rc
        else
          if [[ "$workingpath" != "$pathinitial" && -e $pathinitial'/'${imageomask[i]}'.fits' ]]
          then
            echo ' Copying '${imageomask[i]}'.fits...'
            \cp $pathinitial'/'${imageomask[i]}'.fits' ${imageomask[i]}'.fits' 2>&1; chk_rc
          else
            if [[ ! -e ${imageomask[i]}'.fits' ]]
            then echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Observational mask not found: '\'${imageomask[i]}'.fits'\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; return 99
            fi
            echo ' Using existing image ./'${imageomask[i]}'.fits...'
          fi
        fi
      fi
      
      $path'/imgstat' savein -nomed ${imageomask[i]} ${imageomask[i]} $verb; chk_rc
      
      read min max mea med tots sig skew kurt edgemean < '.+imgstat2'; chk_rc

      'CHECK_IMGSTAT' $min $max '' $script $fun $funo '1'
                                                 
      'COMPARE_NUMBERS' ${min:0:6} '=' '0.0000'; rslt0=$?
      'COMPARE_NUMBERS' ${max:0:6} '=' '1.0000'; rslt1=$?
      'COMPARE_NUMBERS' ${min:0:6} '=' ${max:0:6}; rslt2=$?
      
      if [[ ($rslt0 -eq 0 && $rslt2 -eq 0) || $rslt1 -eq 0 ]]
      then
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid observational mask: min = '$min', max = '$max
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make a mask image with the minimum = 0.0000 and maximum = 1.0000'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; return 99
      fi
####    if [[ $answer != '~' ]]; then echo; fi

# Additionally copy exact rms image for the sky.

      if [[ $mysimsky == "yes" ]]
      then
        rmsname=${obsimage[i]}'.backrms'
        if [[ -e ${imagepath[i]}'/'$rmsname'.fits' ]]
        then
          echo ' Copying '$rmsname'.fits...'
          \cp ${imagepath[i]}'/'$rmsname'.fits' $prefix'.'${wave[i]}'.backrms.fits' 2>&1; chk_rc
        fi                                
      fi
    done
    
    'VERIFY_INPUT_IMAGES'; chk_rc
  fi
  
# Determine type of the images.

  answer=''
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ ${wave[i]} == "070" || ${wave[i]} == "0070" || ${wave[i]} == "70" ]]
    then       
      if [[ "${beam[i]}" == "${b070s10:1}" || "${beam[i]}" == "${b070s20:1}" || "${beam[i]}" == "${b070s20p:1}" || \
            "${beam[i]}" == "${b070s60:1}" || "${beam[i]}" == "${b070s60p:1}" ]]
      then
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel PACS wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not one of those adopted by GETSOURCES'
        echo '       ('${b070s10:1}' '${b070s20:1}' '${b070s20p:1}' '${b070s60:1}' '${b070s60p:1}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
    if [[ ${wave[i]} == "100" || ${wave[i]} == "0100" ]]
    then       
      if [[ "${beam[i]}" == "${b100s10:1}" || "${beam[i]}" == "${b100s20:1}" || "${beam[i]}" == "${b100s20p:1}" || \
            "${beam[i]}" == "${b100s60:1}" || "${beam[i]}" == "${b100s60p:1}" ]]
      then
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel PACS wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not one of those adopted by GETSOURCES'
        echo '       ('${b100s10:1}' '${b100s20:1}' '${b100s20p:1}' '${b100s60:1}' '${b100s60p:1}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
    if [[ ${wave[i]} == "160" || ${wave[i]} == "0160" ]]
    then       
      if [[ "${beam[i]}" == "${b160s10}" || "${beam[i]}" == "${b160s20}" || "${beam[i]}" == "${b160s20p}" || \
            "${beam[i]}" == "${b160s60}" || "${beam[i]}" == "${b160s60p}" ]]
      then
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel PACS wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not one of those adopted by GETSOURCES'
        echo '       ('${b160s10}' '${b160s20}' '${b160s20p}' '${b160s60}' '${b160s60p}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
    if [[ ${wave[i]} == "250" || ${wave[i]} == "0250" ]]
    then       
      if [[ "${beam[i]}" == "$b250" ]]
      then 
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel SPIRE wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not the one adopted by GETSOURCES ('${b250}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
    if [[ ${wave[i]} == "350" || ${wave[i]} == "0350" ]]
    then       
      if [[ "${beam[i]}" == "$b350" ]]
      then 
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel SPIRE wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not the one adopted by GETSOURCES ('${b350}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
    if [[ ${wave[i]} == "500" || ${wave[i]} == "0500" ]]
    then       
      if [[ "${beam[i]}" == "$b500" ]]
      then 
        imagetype[i]='Herschel'
      else
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: The band at '${wave[i]}' microns is one of the Herschel SPIRE wavebands, but'
        echo '       the beam ('${beam[i]}' arcsec) is not the one adopted by GETSOURCES ('${b500}')'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Has the '${wave[i]}' micron image been observed by Herschel (y/N)?: '; read -s answer; rc=$?
    
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='n'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" || $answer == "" ]]
        then 
          answer='n'; echo 'no!'
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
        then 
          echo 'yes!'; imagetype[i]='Herschel'
        fi
        sleep 1
      fi
    fi
  done
  
# Useful zero file for later initializations.

  $path'/modfits' multiply 0 ${detectionclone[1]} -o 'z0' $verb > $hell; chk_rc

# Create total observational mask (an intersection between all observational masks at specific waves).
    
  detectingomask=''
  coaddedomask=$prefix'.coadded.omask'
  \cp 'z0.fits' $coaddedomask'.fits' 2>&1; chk_rc

  for (( i=1; i <= $nwaves; i++ ))
  do
    'CLEAR_IMAGE_BORDERS' border $bpixmsk ${imageomask[i]} ${imageomask[i]}; chk_rc
  done
    
# Create observational masks for combining single scales over wavelengths.
# Combining omask can be used to exclude some images or their areas from combining.

  beamavcombo=0; beammincombo=9999; beammaxcombo=0; wavemincombo=9999; wavemaxcombo=0; nwavescombo=0; srcmaxsizemax=0; echoed=''
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    combiningomask[i]=$prefix'.combining.'${wave[i]}'.omask.fits'
    if [[ -e ${imagepath[i]}'/combining.'${wave[i]}'.omask.fits' ]]
    then
      if [[ $echoed == "" ]]; then echo; echoed='yes'; fi
      echo ' Copying mask for combining: '${combiningomask[i]}'...'
      \cp ${imagepath[i]}'/combining.'${wave[i]}'.omask.fits' ${combiningomask[i]} 2>&1; chk_rc
    else
      $path'/modfits' addconst 1 'z0' -o ${combiningomask[i]} $verb; chk_rc
    fi
    $path'/imgstat' savein -nomed ${combiningomask[i]} ${combiningomask[i]} $verb; chk_rc
    read min max mea med tots sig skew kurt edgemean < '.+imgstat2'; chk_rc
    'CHECK_IMGSTAT' $min $max '' $script $fun $funo '2'

    'COMPARE_NUMBERS' ${max:0:6} '=' '0.0000'; rslt1=$?
    if [[ $rslt1 -eq 1 || ${usewaveincombining[i]} == "no" ]]
    then 
      usewaveincombining[i]='no'
    else
      'COMPARE_NUMBERS' ${wave[i]} '<' $wavemincombo; rslt=$?
      if [[ $rslt -eq 1 ]]; then wavemincombo=${wave[i]}; fi
      'COMPARE_NUMBERS' ${wave[i]} '>' $wavemaxcombo; rslt=$?
      if [[ $rslt -eq 1 ]]; then wavemaxcombo=${wave[i]}; fi
      'COMPARE_NUMBERS' ${beam[i]} '<' $beammincombo; rslt=$?
      if [[ $rslt -eq 1 ]]; then beammincombo=${beam[i]}; fi
      'COMPARE_NUMBERS' ${beam[i]} '>' $beammaxcombo; rslt=$?
      if [[ $rslt -eq 1 ]]; then beammaxcombo=${beam[i]}; fi

      beamavcombo=$(echo "scale=3; $beamavcombo+${beam[i]}" | bc); chk_rc
      nwavescombo=$(( nwavescombo + 1 ))

      $path'/operate' ${imageomask[i]} + $coaddedomask -o $coaddedomask $verb; chk_rc

      'COMPARE_NUMBERS' ${srcmaxsize[i]} '>' $srcmaxsizemax; rslt=$?
      if [[ $rslt -eq 1 ]]; then srcmaxsizemax=${srcmaxsize[i]}; fi
    fi
  done
  
  if [[ $nwaves -gt 1 && $nwavescombo -eq 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: No wavelengths for detection in '\'$configfile\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; return 99
  else
    if [[ $nwavescombo -gt 0 ]]
    then
      beamavcombo=$(echo "scale=3; $beamavcombo/$nwavescombo" | bc); chk_rc
    fi
  fi
  
  combiningmess=''; detectingmess=''; measuringmess=''; visualizingmess=''

  if [[ $nwavescombo -lt $nwaves ]]
  then
    echo
    for (( i=1; i <= $nwaves; i++ ))
    do
      if [[ ${usewaveincombining[i]} == "no" ]]
      then 
        if [[ $nwaves -eq 1 ]]
        then
          if [[ $combining   == "yes" ]]; then   combiningmess='<~ changed from '$combining;   fi;   combining='no'
          if [[ $detecting   == "yes" ]]; then   detectingmess='<~ changed from '$detecting;   fi;   detecting='no'
          if [[ $measuring   == "yes" ]]; then   measuringmess='<~ changed from '$measuring;   fi;   measuring='no'
          if [[ $visualizing == "yes" ]]; then visualizingmess='<~ changed from '$visualizing; fi; visualizing='no'
          if [[ $flattening != "yes" && $flattening != "done" ]]
          then
            if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi
            echo 0 > $subdirinterface'/'$prefix'.'${wave[i]}'.srcmaxsize'
          fi
        fi
        if [[ $decomposing == "yes" ]]
        then
          if [[ $cleaning == "yes" ]]
          then
            if [[ $measuring == "yes" ]]
            then echo ' Image at '${wave[i]}' um will only be decomposed, cleaned, and measured.'
            else echo ' Image at '${wave[i]}' um will only be decomposed and cleaned.'
            fi
          else
            echo ' Image at '${wave[i]}' um will only be decomposed.'
          fi
        else
          if [[ $cleaning == "yes" ]]
          then
            if [[ $measuring == "yes" ]]
            then echo ' Image at '${wave[i]}' um will only be cleaned and measured.'
            else echo ' Image at '${wave[i]}' um will only be cleaned.'
            fi
          else
            if [[ $measuring == "yes" ]]
            then echo ' Image at '${wave[i]}' um will only be measured.'
            else echo ' Image at '${wave[i]}' um will not be processed.'
            fi
          fi
        fi
      fi
    done
    sleep 2
  fi
  
# Create and intersect a special detecting omask.

  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ -e ${imagepath[i]}'/detecting.omask.fits' ]]
    then
      if [[ $detectingomask == "" ]]
      then
        detectingomask=$prefix'.detecting.omask.fits'
        echo; echo ' Making a special mask for detecting: '$detectingomask'...'
        $path'/modfits' addconst 1 'z0' -o $detectingomask $verb; chk_rc
      fi
      $path'/operate' ${imagepath[i]}'/detecting.omask.fits' x $detectingomask -o $detectingomask $verb; chk_rc
  
      $path'/imgstat' savein -nomed $detectingomask $detectingomask $verb; chk_rc
      read min max mea med tots sig skew kurt edgemean < '.+imgstat2'; chk_rc
      'CHECK_IMGSTAT' $min $max '' $script $fun $funo '3'
                                                 
      'COMPARE_NUMBERS' ${min:0:6} '=' ${max:0:6}; rslt1=$?
      'COMPARE_NUMBERS' ${max:0:6} '=' '1.0000'; rslt2=$?
      if [[ $rslt1 -eq 0 || $rslt2 -eq 0 ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Invalid detecting.omask.fits: min = '$min', max = '$max
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: Make a mask with minimum = 0.0000 and maximum = 1.0000'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
    fi
  done
  
  $path'/modfits' maximum 1 n $coaddedomask -o $coaddedomask $verb; chk_rc

  if [[ $detectingomask == "" ]]
  then
    detectingomask=$coaddedomask
  fi

  if [[ $cleaning == "no" && ( $combining == "yes" || $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ) ]]
  then
    echo; echo -n ' Checking if the clean images have been moved...'
  else
    if [[ $combining == "no" && ( $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ) ]]
    then echo; fi
  fi
  correctpaths=''
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    filedecomposing[i]=${dirmono[i]}'/'${detectionclone[i]}'.decomposing'
    filecleaning[i]=${dirmono[i]}'/'${detectionclone[i]}'.cleaning'

    if [[ -e ${dirmono[i]}'/'${detectionclone[i]}'.cleaning.(+)' ]]
    then enforcedthresh[i]='(+)'
    else enforcedthresh[i]=''
    fi
    
    if [[ $cleaning == "no" && ( $combining == "yes" || $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ) ]]
    then
      if [[ -e ${dirmono[i]}'/'${detectionclone[i]}'.lastbright' ]]
      then read lastbrightscale < ${dirmono[i]}'/'${detectionclone[i]}'.lastbright'
      else echo; echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${dirmono[i]}'/'${detectionclone[i]}'.lastbright'\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: You may have incorrectly skipped some processing steps'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      if [[ ! -e ${filecleaning[i]} ]]
      then echo; echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      filewithnamez=${dirmono[i]}'/.'${detectionclone[i]}'.filenamez'
      if [[ -e $filewithnamez ]]
      then \rm $filewithnamez 2>&1; chk_rc; fi
      jscale=0
      {
      while read filename q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 q16 q17 q18 q19 q20 q21 q22 q23 q24
      do
        if [[ ${filename:0:1} != '#' ]]
        then
          jscale=$(( jscale + 1 ))
          'POSITION' "${dirmono[i]}" "$filename"; origp=$returnposition
          if [[ $origp -eq 0 || $correctpaths == "yes" ]]
          then
            if [[ $correctpaths == '' ]]
            then correctpaths='yes'; echo -n ' fixing paths...'
            fi 
            'POSITION' "${detectionclone[i]}" "$filename"; imagp=$returnposition; imagp=$(( imagp - 1 ))
            if [[ $imagp -gt 0 ]]
            then
              filenamexx=${filename:imagp}
              imnl=${#filenamexx}; imnl=$(( imnl - 1 ))
              if [[ -e ${dirmono[i]}'/'${filename:imagp:imnl} ]]
              then
                echo "'${dirmono[i]}/${filename:imagp:imnl}'" \
                "$q1 $q2 $q3 $q4 $q5 $q6 $q7 $q8 $q9 $q10 $q11 $q12 $q13 $q14 $q15 $q16 $q17 $q18 $q19 $q20 $q21 $q22 $q23 $q24" \
                 >> $filewithnamez
              fi
            else
              echo; echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: File name '\'${detectionclone[i]}'.fits'\'' is not in '\'$filename\'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; fun=$funo; return 99
            fi
          else
            \rm $filewithnamez 2>&1; chk_rc; break
          fi
        else
          echo "$filename" \
          "$q1 $q2 $q3 $q4 $q5 $q6 $q7 $q8 $q9 $q10 $q11 $q12 $q13 $q14 $q15 $q16 $q17 $q18 $q19 $q20 $q21 $q22 $q23 $q24" \
          >> $filewithnamez
        fi
      done
      } < ${filecleaning[i]}

      if [[ -e $filewithnamez ]]
      then 
        \rm ${filecleaning[i]} 2>&1; chk_rc
        \mv $filewithnamez ${filecleaning[i]} 2>&1; chk_rc
      fi
    fi
  done

  if [[ $correctpaths = 'yes' ]]
  then echo -n ' done.'
  fi
  correctpaths=''
  filecombining=$originpath'/'$prefix'.sw.det.combining'

  if [[ $combining == "no" && ( $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ) ]]
  then
    echo; echo -n ' Checking if the combo images have been moved...'

    if [[ -e $originpath'/'$prefix'.sw.det.lastbright' ]]
    then read lastbrightscale < $originpath'/'$prefix'.sw.det.lastbright'
    else echo; echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File not found:'
      echo '       '\'$tilde${originpath:ihpath}'/'$prefix'.sw.det.lastbright'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: You may have incorrectly skipped some processing steps ('$configfile')'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
    if [[ ! -e $originpath'/'$prefix'.sw.det.combined' ]]
    then echo; echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File not found:'
      echo '       '\'$tilde${originpath:ihpath}'/'$prefix'.sw.det.combined'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: You may have incorrectly skipped some processing steps ('$configfile')'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99               
    fi
    if [[ ! -e $filecombining ]]
    then echo; echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File not found:'
      echo '       '\'$filecombining\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
    filewithswnamez=$originpath'/.'$prefix'.sw.det.filenamez'
    if [[ -e $filewithswnamez ]]
    then \rm $filewithswnamez 2>&1; chk_rc; fi
    jscale=0
    {
    while read filename q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 q16 q17 q18 q19 q20 q21 q22 q23 q24
    do
      if [[ ${filename:0:1} != '#' ]]
      then
        jscale=$(( jscale + 1 ))
        'POSITION' "$originpath" "$filename"; origp=$returnposition
        if [[ $origp -eq 0 || $correctpaths == "yes" ]]
        then
          if [[ $correctpaths == '' ]]
          then correctpaths='yes'; echo -n ' fixing paths...'
          fi 
          'POSITION' $prefix'.sw.det.' "$filename"; imagp=$returnposition; imagp=$(( imagp - 1 ))
          if [[ $imagp -gt 0 ]]
          then
            filenamexx=${filename:imagp}
            imnl=${#filenamexx}; imnl=$(( imnl - 1 ))
            if [[ -e $originpath'/'${filename:imagp:imnl} ]]
            then
              echo "'$originpath/${filename:imagp:imnl}'" \
              "$q1 $q2 $q3 $q4 $q5 $q6 $q7 $q8 $q9 $q10 $q11 $q12 $q13 $q14 $q15 $q16 $q17 $q18 $q19 $q20 $q21 $q22 $q23 $q24" \
              >> $filewithswnamez
            else
              if [[ $jscale -le $lastbrightscale ]]
              then echo; echo; echo ' '$script': '$fun': ERROR:'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo ' INFO: File not found:'
                echo '       '\'$originpath'/'${filename:imagp:imnl}\'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo; fun=$funo; return 99
              fi
            fi
          else
            echo; echo; echo ' '$script': '$fun': ERROR:'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo ' INFO: File name '\'$prefix'.*.fits'\'' is not in '\'$filename\'
            echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            echo; fun=$funo; return 99
          fi
        else
          if [[ $jscale -eq 1 ]]
          then correctpaths='no'
          fi 
          \rm $filewithswnamez 2>&1; chk_rc; break
        fi
      else
        echo "$filename" \
        "$q1 $q2 $q3 $q4 $q5 $q6 $q7 $q8 $q9 $q10 $q11 $q12 $q13 $q14 $q15 $q16 $q17 $q18 $q19 $q20 $q21 $q22 $q23 $q24" \
        >> $filewithswnamez
      fi
    done
    } < $filecombining

    if [[ -e $filewithswnamez ]]
    then 
      \rm $filecombining 2>&1; chk_rc
      \mv $filewithswnamez $filecombining 2>&1; chk_rc
    fi
    if [[ $correctpaths = 'yes' ]]
    then echo ' done.'
    else echo
    fi
  else
    if [[ $cleaning == "no" && ( $combining == "yes" || $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ) ]]
    then echo
    fi
  fi

# Define some names that will be used in the measurement phase.

  for (( i=1; i <= $nwaves; i++ ))
  do
    cbobsimage[i]=${measuremtclone[i]}'.cb'
    wkobsimage[i]=${measuremtclone[i]}'.wk'
    imeasurebs[i]=${measuremtclone[i]}'.bs'
    imaskingbs[i]=${detectionclone[i]}'.bs'
    wavecatname[i]='sm.'${measuremtclone[i]}'.cat'
    smfcatname[i]=${wavecatname[i]/.cat/.smf.cat}
    detfootprints[i]='sm.'${detectionclone[i]}'.foots.fits'
    obsfootprints[i]=${wavecatname[i]/.cat/.foots.fits}
    obsfootprinta[i]=${wavecatname[i]/.cat/.foota.fits}
    subsfootprints[i]=${wavecatname[i]/.cat/.subsfp.fits}
    maskscalesfinalsum[i]=$prefix'.mask.s~max.w'${wave[i]}'.sum'
  done
  maskscaleswavesfinalsum=$prefix'.mask.s~max.w'${wave[1]}'~'${wave[nwaves]}'.sum'
#___________________________________________________________________________________________________________________________________

# Cut off the '.fits' name extension, if present.

  image=${image/.fits/}
  prefix=${prefix/.fits/}

  'POSITION' ' ' "$def_scale1"; len=$(( returnposition - 1 )); def_scale1=${def_scale1:0:len}
  if [[ $scale1 != $def_scale1 ]]
  then scale1mess=' <~ default value: '\'$def_scale1\'; else scale1mess=''; fi
  'POSITION' ' ' "$def_nscales"; len=$(( returnposition - 1 )); def_nscales=${def_nscales:0:len}
  if [[ $nscales != $def_nscales ]]
  then nscalesmess=' <~ default value: '$def_nscales; else nscalesmess=''; fi
  'POSITION' ' ' "$def_sfactor"; len=$(( returnposition - 1 )); def_sfactor=${def_sfactor:0:len}
  if [[ $sfactor != $def_sfactor ]]
  then sfactormess=' <~ default value: '$def_sfactor; else sfactormess=''; fi
  'POSITION' ' ' "$def_fsbelowbeam"; len=$(( returnposition - 1 )); def_fsbelowbeam=${def_fsbelowbeam:0:len}
  if [[ $fsbelowbeam != $def_fsbelowbeam ]]
  then fsbelowbeammess=' <~ default value: '$def_fsbelowbeam; else fsbelowbeammess=''; fi
  'POSITION' ' ' "$def_fscalemax"; len=$(( returnposition - 1 )); def_fscalemax=${def_fscalemax:0:len}
  if [[ $fscalemax != $def_fscalemax ]]
  then fscalemaxmess=' <~ default value: '$def_fscalemax; else fscalemaxmess=''; fi
  'POSITION' ' ' "$def_ffaintestscale"; len=$(( returnposition - 1 )); def_ffaintestscale=${def_ffaintestscale:0:len}
  if [[ $ffaintestscale != $def_ffaintestscale ]]
  then ffaintestscalemess=' <~ default value: '$def_ffaintestscale; else ffaintestscalemess=''; fi
  'POSITION' ' ' "$def_nsigmacutss"; len=$(( returnposition - 1 )); def_nsigmacutss=${def_nsigmacutss:0:len}
  if [[ $nsigmacutss != $def_nsigmacutss ]]
  then nsigmacutssmess=' <~ default value: '$def_nsigmacutss; else nsigmacutssmess=''; fi
  'POSITION' ' ' "$def_nsigmacutfloor"; len=$(( returnposition - 1 )); def_nsigmacutfloor=${def_nsigmacutfloor:0:len}
  if [[ $nsigmacutfloor != $def_nsigmacutfloor ]]
  then nsigmacutfloormess=' <~ default value: '$def_nsigmacutfloor; else nsigmacutfloormess=''; fi
  'POSITION' ' ' "$def_skewmaxfloor"; len=$(( returnposition - 1 )); def_skewmaxfloor=${def_skewmaxfloor:0:len}
  if [[ $skewmaxfloor != $def_skewmaxfloor ]]
  then skewmaxfloormess=' <~ default value: '$def_skewmaxfloor; else skewmaxfloormess=''; fi
  'POSITION' ' ' "$def_kurtmaxfloor"; len=$(( returnposition - 1 )); def_kurtmaxfloor=${def_kurtmaxfloor:0:len}
  if [[ $skewmaxfloor != $def_kurtmaxfloor ]]
  then kurtmaxfloormess=' <~ default value: '$def_kurtmaxfloor; else kurtmaxfloormess=''; fi
  'POSITION' ' ' "$def_minpixfloor"; len=$(( returnposition - 1 )); def_minpixfloor=${def_minpixfloor:0:len}
  if [[ $minpixfloor != $def_minpixfloor ]]
  then minpixfloormess=' <~ default value: '$def_minpixfloor; else minpixfloormess=''; fi
  'POSITION' ' ' "$def_cleantuning"; len=$(( returnposition - 1 )); def_cleantuning=${def_cleantuning:0:len}
  if [[ $cleantuning != $def_cleantuning ]]
  then cleantuningmess=' <~ default value: '$def_cleantuning; else cleantuningmess=''; fi
  'POSITION' ' ' "$def_comboexpomax"; len=$(( returnposition - 1 )); def_comboexpomax=${def_comboexpomax:0:len}
  if [[ $comboexpomax != $def_comboexpomax ]]
  then comboexpomaxmess=' <~ default value: '$def_comboexpomax; else comboexpomaxmess=''; fi
  'POSITION' ' ' "$def_comboexpomin"; len=$(( returnposition - 1 )); def_comboexpomin=${def_comboexpomin:0:len}
  if [[ $comboexpomin != $def_comboexpomin ]]
  then comboexpominmess=' <~ default value: '$def_comboexpomin; else comboexpominmess=''; fi
  'POSITION' ' ' "$def_contranoise"; len=$(( returnposition - 1 )); def_contranoise=${def_contranoise:0:len}
  if [[ $contranoise != $def_contranoise ]]
  then contranoisemess=' <~ default value: '$def_contranoise; else contranoisemess=''; fi
  'POSITION' ' ' "$def_factortotal"; len=$(( returnposition - 1 )); def_factortotal=${def_factortotal:0:len}
  if [[ $factortotal != $def_factortotal ]]
  then factortotalmess=' <~ default value: '$def_factortotal; else factortotalmess=''; fi
  'POSITION' ' ' "$def_fdp"; len=$(( returnposition - 1 )); def_fdp=${def_fdp:0:len}
  'POSITION' ' ' "$def_fbm"; len=$(( returnposition - 1 )); def_fbm=${def_fbm:0:len}
  'POSITION' ' ' "$def_ffi"; len=$(( returnposition - 1 )); def_ffi=${def_ffi:0:len}
  if [[ $fdp != $def_fdp || $fbm != $def_fbm || $ffi != $def_ffi ]]
  then filamentsmess=' <~ default values: '$def_fdp' '$def_fbm' '$def_ffi; else filamentsmess=''; fi

  ndetwavesmess=''
  if [[ $ndetwaves -lt $nwavescombo ]]; then ndetwavesmin=$ndetwaves; else ndetwavesmin=$nwavescombo; fi
  if [[ $ndetwaves -gt $ndetwavesmin ]]; then ndetwavesmess='<~ down from '$ndetwaves; ndetwaves=$ndetwavesmin; fi
  stentativemess=''; sreliablemess=''

  contranoisefloor='1.20'; factortotalfloor='2.0'; sreliablefloor='4'; stentativefloor='2'; fdpfloor='0.6'

  if [[ $ndetwaves -gt 1 ]]
  then 
    stentativemess=$stentativemess'<~ down from '$stentative': ndetwaves='$ndetwaves
    stentative=$(echo "scale=1; $stentative/sqrt($ndetwaves)" | bc); chk_rc
    'COMPARE_NUMBERS' $stentative '<' $stentativefloor; rslt=$?
    if [[ $rslt -eq 1 ]]; then stentative=$stentativefloor; stentativemess='<~ lower limit: '$stentative; fi
  fi

  'COMPARE_NUMBERS' $sreliable '<' $sreliablefloor; rslt=$?
  if [[ $rslt -eq 1 ]]; then sreliable=$sreliablefloor; sreliablemess='<~ lower limit: '$sreliable; fi
                                                     
  'COMPARE_NUMBERS' $factortotal '<' $factortotalfloor; rslt=$?
  if [[ $rslt -eq 1 ]]; then factortotal=$factortotalfloor; factortotalmess='<~ lower limit: '$factortotal; fi

  if [[ $flattening != "yes" && $flattening != "done" ]]
  then
    if [[ $ssr != "+" ]]
    then
      'COMPARE_NUMBERS' $sreliable '>' $sreliablefloor; rslt=$?
      if [[ $rslt -eq 1 ]]; then sreliablemess='<~ down from '$sreliable; sreliable=$sreliablefloor; fi
    fi
    if [[ $sst != "+" ]]
    then
      'COMPARE_NUMBERS' $stentative '>' $stentativefloor; rslt=$?
      if [[ $rslt -eq 1 ]]; then stentativemess='<~ down from '$stentative; stentative=$stentativefloor; fi
    fi
    if [[ $scn != "+" ]]
    then
      'COMPARE_NUMBERS' $contranoise '>' $contranoisefloor; rslt=$?
      if [[ $rslt -eq 1 ]]; then contranoisemess='<~ down from '$contranoise' '$contranoisemess; contranoise=$contranoisefloor; fi
    fi
    if [[ $ndetwaves -gt 1 ]]; then ndetwavesmess='<~ down from '$ndetwaves' '$ndetwavesmess; ndetwaves='1'; fi
  else
    if [[ $nwmax -gt 1 && $nwaves -eq 1 && $cleaning == "yes" ]]
    then
      if [[ $combining == "yes" || $detecting == "yes" || $measuring == "yes" || $visualizing == "yes" ]]
      then 
        echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: For the FINAL MONOCHROMATIC extraction, it is not necessary to process '
        echo '       all steps, if the primary interest is in a MULTI-WAVELENGTH extraction '
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: To save computing time and disk space, one can safely skip all steps   '
        echo '       after cleaning (i.e., combining, detecting, measuring, and visualizing)'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo -n ' QQQQ: Would you like to skip the steps beyond cleaning (Y/n)?: '
        answer=''; read -s -t 30 answer; rc=$?
    
        if [[ $rc -eq 1 ]]; then answer='y'; fi
        if [[ ${answer:0:1} != "n" && ${answer:0:1} != "N" && ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
        then
          answer='y'; echo -n 'assuming '
        fi
        if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" || $answer == "" ]]
        then 
          answer='y'; echo 'yes!'
          if [[ $combining   == "yes" ]]; then   combiningmess='<~ changed from '$combining  ;   combining='no'; fi
          if [[ $detecting   == "yes" ]]; then   detectingmess='<~ changed from '$detecting  ;   detecting='no'; fi
          if [[ $measuring   == "yes" ]]; then   measuringmess='<~ changed from '$measuring  ;   measuring='no'; fi
          if [[ $visualizing == "yes" ]]; then visualizingmess='<~ changed from '$visualizing; visualizing='no'; fi
        fi
        if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" ]]
        then 
          echo 'no!'
        fi
        sleep 1
      fi
    fi
  fi
  smfindermess=$sfinding
  if [[ $detecting == "yes" && $sfinding == "no" ]]; then smfindermess=$sfinding' ~> skipping sfinder'; fi
  echo '_______________________________________________________________________________'
  echo
  echo '       GETSOURCES: INPUT PARAMETERS'
  echo  
  echo '        sreliable:' $sreliable       $sreliablemess
  echo '       stentative:' $stentative      $stentativemess
  echo '      snratio1min:' $snratio1min
  echo '      snratio2min:' $snratio2min
  echo '        ndetwaves:' $ndetwaves       $ndetwavesmess
  echo '       reldiffmax:' $reldiffmax
  echo '        savespace:' $savespace
  echo '        verbosity:' ${verb:5:1}
  echo '           scale1:' $scale1          $scale1mess
  echo '          nscales:' $nscales         $nscalesmess
  echo '          sfactor:' $sfactor         $sfactormess
  echo '      fsbelowbeam:' $fsbelowbeam     $fsbelowbeammess
  echo '        fscalemax:' $fscalemax       $fscalemaxmess
  echo '   ffaintestscale:' $ffaintestscale  $ffaintestscalemess
  echo '      nsigmacutss:' $nsigmacutss     $nsigmacutssmess
  echo '   nsigmacutfloor:' $nsigmacutfloor  $nsigmacutfloormess
  echo '     skewmaxfloor:' $skewmaxfloor    $skewmaxfloormess
  echo '     kurtmaxfloor:' $kurtmaxfloor    $kurtmaxfloormess
  echo '      minpixfloor:' $minpixfloor     $minpixfloormess
  echo '      cleantunung:' $cleantuning     $cleantuningmess
  echo '     comboexpomax:' $comboexpomax    $comboexpomaxmess
  echo '     comboexpomin:' $comboexpomin    $comboexpominmess
  echo '      contranoise:' $contranoise     $contranoisemess
  echo '      factortotal:' $factortotal     $factortotalmess
  echo '        filaments:' $filaments $fdp $fbm $ffi  $filamentsmess
  echo '       profimages:' $sproima $fproima $npxstep
  for (( i=1; i <= $nwaves; i++ ))
  do
    'LEADZEROS' 1 $i zi
    echo '       detimage'$zi': '${detimage[i]}
  done
  for (( i=1; i <= $nwaves; i++ ))
  do
    'LEADZEROS' 1 $i zi
    echo '       obsimage'$zi': '${obsimage[i]} \
         '~> type: '"${imagetype[i]}"
  done
  for (( i=1; i <= $nwaves; i++ ))
  do
    'LEADZEROS' 1 $i zi
    echo '     imageomask'$zi': ./'${imageomask[i]}
  done
  for (( i=1; i <= $nwaves; i++ ))
  do
    'LEADZEROS' 1 $i zi
    echo ' detectionclone'$zi': ./'${detectionclone[i]} \
         '~> maxsizes: '"${srcmaxsizeb[i]} ${filmaxsizeb[i]}"' weight: '"${weight[i]}"' skmax: '"${skewmax[i]}" \
         "${enforcedthresh[i]}"
  done
  for (( i=1; i <= $nwaves; i++ ))
  do
    'LEADZEROS' 1 $i zi
    echo ' measuremtclone'$zi': ./'${measuremtclone[i]} \
         '~> beam: '"${beamb[i]}"' apcorr: '"${apcorrect[i]}"' aprad: '"${aperture[i]}"
  done
  if [[ $doflatten != "no" &&  $doflatten != "+" ]]; then doflatten=''; fi
  echo '       flattening:' $flattening  $doflatten
  echo '      decomposing:' $decomposing
  echo '         cleaning:' $cleaning    $nwc1 $nsc1
  echo '        combining:' $combining   $combiningmess                     
  echo '        detecting:' $detecting   $detectingmess   $smfindermess $nsd1
  echo '        measuring:' $measuring   $measuringmess   $bgfisub$smp  $iterbeg $itermax 
  echo '      visualizing:' $visualizing $visualizingmess $goodmin                  
  echo
  if [[ $flattening != "yes" && $flattening != "done" ]]
  then echo '       INITIAL EXTRACTION'
  else echo '       FINAL EXTRACTION'
  fi         
  echo
  echo -n ' QQQQ: Are the above parameters correct (Y/n)?: '; answer=''; read -s -t 30 answer; rc=$?

  if [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" ]]
  then echo; echo; echo ' Answer '\'$answer\'' received - aborted.'; exit 99
  fi
  if [[ $rc -eq 1 ]]; then echo -n 'assuming your answer is '; fi
  if [[ ${answer:0:1} != "y" && ${answer:0:1} != "Y" && $answer != "" ]]
  then echo -n 'not no... assuming '
  fi
  echo 'yes!'
  
  allapertures=''
  for (( i=1; i <= $nwaves; i++ ))
  do
    allapertures=$allapertures' '${aperture[i]}
  done

  'COMPARE_NUMBERS' $fsbelowbeam '>=' '0.0'; rslt1=$?
  'COMPARE_NUMBERS' $fsbelowbeam '<=' '1.0'; rslt2=$?
  if [[ $rslt1 -eq 0 || $rslt2 -eq 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid parameter FSBELOWBEAM = '$fsbelowbeam' (must be between 0.0 and 1.0)'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

  if [[ $apertures == "y" ]]
  then
    echo
    echo ' *WARNING*  MEASUREMENT APERTURES:'$allapertures' ARCSEC'
    echo '            __________________________________________________________________ '
    echo ' *WARNING* |                                                                  |'
    echo ' *WARNING* |  You have chosen to apply user-defined MEASUREMENT APERTURES in  |'
    echo ' *WARNING* |  this extraction. Note that indiscriminate use of the apertures  |'
    echo ' *WARNING* |  may easily lead to meaningless results, as they can strongly    |'
    echo ' *WARNING* |  influence the background subtraction and deblending. Since the  |'
    echo ' *WARNING* |  observed astrophysical backgrounds are highly-variable on all   |'
    echo ' *WARNING* |  scales, the fixed apertures may result in overestimating the    |'
    echo ' *WARNING* |  fluxes (or sizes) for some sources and in underestimating them  |'
    echo ' *WARNING* |  for other sources. All this may introduce biases, depending on  |'
    echo ' *WARNING* |  the actual size and location of a source, that are impossible   |'
    echo ' *WARNING* |  to predict in a general case.                                   |'
    echo ' *WARNING* |                                                                  |'
    echo ' *WARNING* |  THE AUTHOR DOES NOT GUARANTEE CORRECT RESULTS WHEN ARBITRARY    |'
    echo ' *WARNING* |  APERTURES ARE USED FOR BACKGROUND SUBTRACTION AND MEASUREMENTS. |'
    echo ' *WARNING* |  THIS IS *NOT* A STANDARD WAY OF SOURCE EXTRACTION; ONE HAS TO   |'
    echo ' *WARNING* |  TEST THE EFFECTS EXTENSIVELY BEFORE PUBLISHING ANY RESULTS.     |'
    echo ' *WARNING* |                                                                  |'
    echo ' *WARNING* |  THE USER SHOULD KNOW EXACTLY WHAT IS BEING DONE AND WILL TAKE   |'
    echo ' *WARNING* |  FULL RESPONSIBILITY FOR ACTIVATING THIS FEATURE OF GETSOURCES.  |'
    echo ' *WARNING* |__________________________________________________________________|'
    echo
    echo -n ' *WARNING* ~> PRESS ENTER TO AGREE: YOU HAVE READ AND UNDERSTOOD THE MESSAGE.'
    read -s answer; echo
  fi
  echo '_______________________________________________________________________________'

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

VERIFY_FITS_HEADERS ()
{
  local funo=$fun; fun='VERIFY_FITS_HEADERS'
  if [[ $4 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'" "'$4'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local bunit; local bunitc; local bzero; local bzeroc; local bscale; local bscalec; local abort
  local fpath=$1; local origimage=$2; local cloneimage=$3; local wavelength=$4

  abort='no'

  if [[ ! -e $fpath'/'$origimage'.fits' ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$fpath'/'$origimage'.fits'\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
    
# Check the image for correctness of the keyword BUNIT.
  
  $path'/readhead' save BUNIT $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]; then read bunitc bunit < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc; fi
  
  if [[ ${bunit:1:8} == '       ' || ${bunit:1:8} == 'UNKNOWN' || ${bunit:1:8} == 'unknown' || $rch -eq 2 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Missing/blank/bad value '\'${bunit:1:8}\'' of BUNIT in the image'
    echo '       '$origimage'.fits'
    echo '       BUNIT:' ${bunit:1:8}
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to correct the keyword BUNIT and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi
  if [[ ${bunit:1:6} != "MJy/sr" && ${bunit:1:8} != "no-units" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid value '\'${bunit:1:8}\'' of BUNIT in the image'
    echo '       '$origimage'.fits'
    echo '       BUNIT:' ${bunit:1:8}
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to set the keyword BUNIT = MJy/sr and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

# Check the image for correctness of the keyword BZERO.
  
  $path'/readhead' save BZERO $fpath'/'$origimage $verb &> $hell; rch=$?
  
if [[ $rch -eq 0 ]]; then read bzeroc bzero < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc; fi
       
  if [[ ${bzero:0:19} != '0.0000000000000E+00' && ${bzero:0:18} != '0.000000000000E+00' && \
        ${bzero:0:17} != '0.00000000000E+00' && ${bzero:0:16} != '0.000000000E+00' && ${bzero:0:15} != '0.0000000E+00' && \
        ${bzero:0:14} != '0.00000000E+00' && ${bzero:0:13} != '0.0000000E+00' && ${bzero:0:12} != '0.000000E+00' && \
        ${bzero:0:11} != '0.00000E+00' && ${bzero:0:10} != '0.0000E+00' && ${bzero:0:9} != '0.000E+00' ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid value '\'$bzero\'' of BZERO in the image'
    echo '       '$origimage'.fits'
    echo '       BZERO:' $bzero
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to set the keyword BZERO = 0.0 and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

# Check the image for correctness of the keyword BSCALE.

  $path'/readhead' save BSCALE $fpath'/'$origimage $verb &> $hell; rch=$?

  if [[ $rch -eq 0 ]]; then read bscalec bscale < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc; fi

  if [[ ${bscale:0:19} != '1.0000000000000E+00' && ${bscale:0:18} != '1.000000000000E+00' && \
        ${bscale:0:17} != '1.00000000000E+00' && ${bscale:0:16} != '1.000000000E+00' && ${bscale:0:15} != '1.0000000E+00' && \
        ${bscale:0:14} != '1.00000000E+00' && ${bscale:0:13} != '1.0000000E+00' && ${bscale:0:12} != '1.000000E+00' && \
        ${bscale:0:11} != '1.00000E+00' && ${bscale:0:10} != '1.0000E+00' && ${bscale:0:9} != '1.000E+00' ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid value '\'$bscale\'' of keyword BSCALE in the input image'
    echo '       '$origimage'.fits'
    echo '       BSCALE:' $bscale
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to set the keyword BSCALE = 1.0 and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  $path'/readhead' save CDELT1 CDELT2 $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]
  then
    read cdeltc cdelt1 cdeltc cdelt2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble reading the keyword CDELT1 or CDELT2 in the input image'
    echo '       '$origimage'.fits'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  $path'/readhead' save CRPIX1 CRPIX2 $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]
  then
    read crpixc crpix1 crpixc crpix2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble reading the keyword CRPIX1 or CRPIX2 in the input image'
    echo '       '$origimage'.fits'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  $path'/readhead' save CRVAL1 CRVAL2 $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]
  then
    read crvalc crval1 crvalc crval2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble reading the keyword CRVAL1 or CRVAL2 in the input image'
    echo '       '$origimage'.fits'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  $path'/readhead' save CTYPE1 CTYPE2 $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]
  then
    read ctypec ctype1 ctypec ctype2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble reading the keyword CTYPE1 or CTYPE2 in the input image'
    echo '       '$origimage'.fits'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  $path'/readhead' save RA DEC $fpath'/'$origimage $verb &> $hell; rch=$?
  
  if [[ $rch -eq 0 ]]
  then
    read rascenc rascen declinc declin < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble reading the keyword RA or DEC in the input image'
    echo '       '$fpath
    echo '       '$origimage'.fits'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  if [[ $crval1 != $rascen ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: The keywords CRVAL1 and RA do not match in the input image'
    echo '       '$fpath
    echo '       '$origimage'.fits'
    echo '       CRVAL1:' $crval1 'RA:' $rascen
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo '       The easiest fix is to multiply the image by 1 using MODFITS:'
    echo '       modfits multiply 1 '$origimage' -o '$origimage
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  if [[ $crval2 != $declin ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: The keywords CRVAL2 and DEC do not match in the input image'
    echo '       '$fpath
    echo '       '$origimage'.fits'
    echo '       CRVAL2:' $crval2 'DEC:' $declin
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use READHEAD, MODFITS to correct the header and then run '$script
    echo '       The easiest fix is to multiply the image by 1 using MODFITS:'
    echo '       modfits multiply 1 '$origimage' -o '$origimage
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  if [[ ${ctype1:1:8} != "RA---TAN" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid value of the keyword CTYPE1: '\'$ctype1\'' in the input image'
    echo '       '$fpath
    echo '       '$origimage'.fits'
    echo '       CTYPE1:' $ctype1
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to make CTYPE1 = RA---TAN and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  if [[ ${ctype2:1:8} != "DEC--TAN" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Invalid value of the keyword CTYPE2: '\'$ctype2\'' in the input image'
    echo '       '$fpath
    echo '       '$origimage'.fits'
    echo '       CTYPE2:' $ctype2
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' HINT: Use MODFITS to make CTYPE2 = DEC--TAN and then run '$script
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    abort='yes'
  fi

  if [[ $abort == "yes" ]]; then echo; fun=$funo; return 99; fi

  $path'/readhead' save WAVE $fpath'/'$origimage $verb &> $hell; rch=$?; \rm '.+readhead' 2>&1; chk_rc
 
  if [[ $rch -eq 2 ]]
  then 
    echo; echo ' '$script': '$fun': WARNING: Inserting missing WAVE keyword...'
 
    $path'/modfits' key WAVE $wavelength $cloneimage -o $cloneimage $verb; chk_rc
  fi

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

VERIFY_INPUT_IMAGES ()
{
  local funo=$fun; fun='VERIFY_INPUT_IMAGES'

  echo; echo -n ' Verifying that all images have been correctly prepared... '

  obscd1o=''; obscd2o=''; obscrp1o=''; obscrp2o=''; obscrv1o=''; obscrv2o=''; obsraso=''; obsdeto=''
  detcd1o=''; detcd2o=''; detcrp1o=''; detcrp2o=''; detcrv1o=''; detcrv2o=''; detraso=''; detdeto=''
  mskcd1o=''; mskcd2o=''; mskcrp1o=''; mskcrp2o=''; mskcrv1o=''; mskcrv2o=''; mskraso=''; mskdeto=''
  abort='no'

  for (( i=1; i <= $nwmax; i++ ))
  do 
    echo -n $i
    if [[ ${cfgdirp[i]:0:2} == "~/" ]]
    then cfgimpath[i]=`\cd ~/${cfgdirp[i]:2}; pwd`
    else cfgimpath[i]=`\cd ${cfgdirp[i]}; pwd`
    fi
    im1=$(( i - 1 ))

    'VERIFY_FITS_HEADERS' ${cfgimpath[i]} ${cfgobsim[i]} $prefix'.'${cfgwave[i]}'.obs' ${cfgwave[i]}; chk_rc

    obscd1=$cdelt1; obscd2=$cdelt2; obscrp1=$crpix1; obscrp2=$crpix2; obscrv1=$crval1; obscrv2=$crval2; obsras=$rascen; obsdec=$declin
                                    
    'VERIFY_FITS_HEADERS' ${cfgimpath[i]} ${cfgdetim[i]} $prefix'.'${cfgwave[i]}'.det' ${cfgwave[i]}; chk_rc
    
    detcd1=$cdelt1; detcd2=$cdelt2; detcrp1=$crpix1; detcrp2=$crpix2; detcrv1=$crval1; detcrv2=$crval2; detras=$rascen; detdec=$declin
                                    
    'VERIFY_FITS_HEADERS' ${cfgimpath[i]} ${cfgdetim[i]}'.omask' ${cfgdetim[i]}'.omask' ${cfgwave[i]}; chk_rc
    
    mskcd1=$cdelt1; mskcd2=$cdelt2; mskcrp1=$crpix1; mskcrp2=$crpix2; mskcrv1=$crval1; mskcrv2=$crval2; mskras=$rascen; mskdec=$declin

    if [[ $obscd1 != $detcd1 || $obscd2 != $detcd2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CDELT1 or CDELT2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}
      echo '       1st image: CDELT1:' $obscd1 'CDELT2:' $obscd2
      echo '       2nd image: CDELT1:' $detcd1 'CDELT2:' $detcd2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CDELT#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}' -o '${cfgdetim[i]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obscd1 != $mskcd1 || $obscd2 != $mskcd2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CDELT1 or CDELT2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}'.omask'
      echo '       1st image: CDELT1:' $obscd1 'CDELT2:' $obscd2
      echo '       2nd image: CDELT1:' $mskcd1 'CDELT2:' $mskcd2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CDELT#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}'.omask -o '${cfgdetim[i]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obscrp1 != $detcrp1 || $obscrp2 != $detcrp2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRPIX1 or CRPIX2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}
      echo '       1st image: CRPIX1:' $obscrp1 'CRPIX2:' $obscrp2
      echo '       2nd image: CRPIX1:' $detcrp1 'CRPIX2:' $detcrp2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRPIX#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}' -o '${cfgdetim[i]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obscrp1 != $mskcrp1 || $obscrp2 != $mskcrp2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRPIX1 or CRPIX2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}'.omask'
      echo '       1st image: CRPIX1:' $obscrp1 'CRPIX2:' $obscrp2
      echo '       2nd image: CRPIX1:' $mskcrp1 'CRPIX2:' $mskcrp2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRPIX#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}'.omask -o '${cfgdetim[i]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obscrv1 != $detcrv1 || $obscrv2 != $detcrv2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRVAL1 or CRVAL2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}
      echo '       1st image: CRVAL1:' $obscrv1 'CRVAL2:' $obscrv2
      echo '       2nd image: CRVAL1:' $detcrv1 'CRVAL2:' $detcrv2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRVAL#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}' -o '${cfgdetim[i]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obscrv1 != $mskcrv1 || $obscrv2 != $mskcrv2 ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRVAL1 or CRVAL2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}'.omask'
      echo '       1st image: CRVAL1:' $obscrv1 'CRVAL2:' $obscrv2
      echo '       2nd image: CRVAL1:' $mskcrv1 'CRVAL2:' $mskcrv2
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRVAL#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}'.omask -o '${cfgdetim[i]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obsras != $detras || $obsdec != $detdec ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords RA or DEC do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}
      echo '       1st image: RA:' $obsras 'DEC:' $obsdec
      echo '       2nd image: RA:' $detras 'DEC:' $detdec
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same RA# DEC#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}' -o '${cfgdetim[i]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $obsras != $mskras || $obsdec != $mskdec ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords RA or DEC do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgdetim[i]}'.omask'
      echo '       1st image: RA:' $obsras 'DEC:' $obsdec
      echo '       2nd image: RA:' $mskras 'DEC:' $mskdec
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same RA# DEC#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgdetim[i]}'.omask -o '${cfgdetim[i]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($obscd1 != $obscd1o || $obscd2 != $obscd2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CDELT1 or CDELT2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgobsim[im1]}
      echo '       1st image: CDELT1:' $obscd1  'CDELT2:' $obscd2
      echo '       2nd image: CDELT1:' $obscd1o 'CDELT2:' $obscd2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CDELT#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgobsim[im1]}' -o '${cfgobsim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($detcd1 != $detcd1o || $detcd2 != $detcd2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CDELT1 or CDELT2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}
      echo '       2nd image: '${cfgdetim[im1]}
      echo '       1st image: CDELT1:' $detcd1  'CDELT2:' $detcd2
      echo '       2nd image: CDELT1:' $detcd1o 'CDELT2:' $detcd2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CDELT#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}' h '${cfgdetim[im1]}' -o '${cfgdetim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($mskcd1 != $mskcd1o || $mskcd2 != $mskcd2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CDELT1 or CDELT2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}'.omask'
      echo '       2nd image: '${cfgdetim[im1]}'.omask'
      echo '       1st image: CDELT1:' $mskcd1  'CDELT2:' $mskcd2
      echo '       2nd image: CDELT1:' $mskcd1o 'CDELT2:' $mskcd2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CDELT#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}'.omask h '${cfgdetim[im1]}'.omask -o '${cfgdetim[im1]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($obscrp1 != $obscrp1o || $obscrp2 != $obscrp2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRPIX1 or CRPIX2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgobsim[im1]}
      echo '       1st image: CRPIX1:' $obscrp1  'CRPIX2:' $obscrp2
      echo '       2nd image: CRPIX1:' $obscrp1o 'CRPIX2:' $obscrp2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRPIX#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgobsim[im1]}' -o '${cfgobsim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($detcrp1 != $detcrp1o || $detcrp2 != $detcrp2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRPIX1 or CRPIX2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}
      echo '       2nd image: '${cfgdetim[im1]}
      echo '       1st image: CRPIX1:' $detcrp1  'CRPIX2:' $detcrp2
      echo '       2nd image: CRPIX1:' $detcrp1o 'CRPIX2:' $detcrp2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRPIX#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}' h '${cfgdetim[im1]}' -o '${cfgdetim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($mskcrp1 != $mskcrp1o || $mskcrp2 != $mskcrp2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRPIX1 or CRPIX2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}'.omask'
      echo '       2nd image: '${cfgdetim[im1]}'.omask'
      echo '       1st image: CRPIX1:' $mskcrp1  'CRPIX2:' $mskcrp2
      echo '       2nd image: CRPIX1:' $mskcrp1o 'CRPIX2:' $mskcrp2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRPIX#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}'.omask h '${cfgdetim[im1]}'.omask -o '${cfgdetim[im1]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($obscrv1 != $obscrv1o || $obscrv2 != $obscrv2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRVAL1 or CRVAL2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgobsim[im1]}
      echo '       1st image: CRVAL1:' $obscrv1  'CRVAL2:' $obscrv2
      echo '       2nd image: CRVAL1:' $obscrv1o 'CRVAL2:' $obscrv2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRVAL#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgobsim[im1]}' -o '${cfgobsim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($detcrv1 != $detcrv1o || $detcrv2 != $detcrv2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRVAL1 or CRVAL2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}
      echo '       2nd image: '${cfgdetim[im1]}
      echo '       1st image: CRVAL1:' $detcrv1  'CRVAL2:' $detcrv2
      echo '       2nd image: CRVAL1:' $detcrv1o 'CRVAL2:' $detcrv2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRVAL#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}' h '${cfgdetim[im1]}' -o '${cfgdetim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($mskcrv1 != $mskcrv1o || $mskcrv2 != $mskcrv2o) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords CRVAL1 or CRVAL2 do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}'.omask'
      echo '       2nd image: '${cfgdetim[im1]}'.omask'
      echo '       1st image: CRVAL1:' $mskcrv1  'CRVAL2:' $mskcrv2
      echo '       2nd image: CRVAL1:' $mskcrv1o 'CRVAL2:' $mskcrv2o
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same CRVAL#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}'.omask h '${cfgdetim[im1]}'.omask -o '${cfgdetim[im1]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($obsras != $obsraso || $obsdec != $obsdeco) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords RA or DEC do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgobsim[i]}
      echo '       2nd image: '${cfgobsim[im1]}
      echo '       1st image: RA:' $obsras  'DEC:' $obsdec
      echo '       2nd image: RA:' $obsraso 'DEC:' $obsdeco
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same RA# DEC#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgobsim[i]}' h '${cfgobsim[im1]}' -o '${cfgobsim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($detras != $detraso || $detdec != $detdeco) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords RA or DEC do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}
      echo '       2nd image: '${cfgdetim[im1]}
      echo '       1st image: RA:' $detras  'DEC:' $detdec
      echo '       2nd image: RA:' $detraso 'DEC:' $detdeco
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same RA# DEC#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}' h '${cfgdetim[im1]}' -o '${cfgdetim[im1]}
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi
    if [[ $im1 -gt 0 && ($mskras != $mskraso || $mskdec != $mskdeco) ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Keywords RA or DEC do not match in input images in the directory'
      echo '       '${cfgimpath[i]}
      echo '       1st image: '${cfgdetim[i]}'.omask'
      echo '       2nd image: '${cfgdetim[im1]}'.omask'
      echo '       1st image: RA:' $mskras  'DEC:' $mskdec
      echo '       2nd image: RA:' $mskraso 'DEC:' $mskdeco
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: Use READHEAD, MODFITS, or OPERATE to make images have the same RA# DEC#'
      echo '       The easiest fix is to copy the header using OPERATE, e.g.:'
      echo '       operate '${cfgdetim[i]}'.omask h '${cfgdetim[im1]}'.omask -o '${cfgdetim[im1]}'.omask'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      abort='yes'
    fi

### Check if the original images are significantly offset from zero; if so, diagnose a potential problem.
### Although extractions are background-subtracted and do not depend on the offset (in principle), in practice it may create problems 
### when creating single scales, as the available numerical precision may not be sufficient. In essence, the question is whether a 
### subtraction of two successive convolutions of an image with slightly different beams gives the huge loss of precision or not. 
### This affects mostly the areas of very small variations from pixel to pixel and may differ for different images.
##
##    $path'/imgstat' savein ${cfgimpath[i]}'/'${cfgdetim[i]} ${cfgimpath[i]}'/'${cfgdetim[i]}'.omask' $verb; chk_rc
##    read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
##    'CHECK_IMGSTAT' $min $max '' $script $fun $funo '4'
##    sig3=$(echo "scale=5; 3*$sig" | bc); chk_rc
##
##    'COMPARE_NUMBERS' $med '>' $sig3; rsltmed=$?
##    if [[ $rsltmed -eq 1 ]]
##    then
##      suggested=$(echo "scale=5; $sig-$med" | bc); chk_rc
##      echo; echo ' '$script': '$fun': ERROR:'
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo ' INFO: Detection image has a large offset:'
##      echo '       '${cfgimpath[i]}
##      echo '       '${cfgdetim[i]}'.fits'
##      echo '       median value = '$med', standard deviation = '$sig
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo ' HINT: Although extractions are background-subtracted and (in principle) do not' 
##      echo '       depend on constant offsets, in practice it may create problems for image'
##      echo '       decomposition, due to finite numerical precision. One should subtract'
##      echo '       large offsets from both detection and measurement images to make their'
##      echo '       pixel distributions peaking closer to zero. One can remove constant'
##      echo '       offsets using the MODFITS utility, e.g.:'
##      echo '       modfits add '$suggested' '${cfgdetim[i]}' -o '${cfgdetim[i]}
##      echo '       modfits add '$suggested' '${cfgobsim[i]}' -o '${cfgobsim[i]}
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo; fun=$funo; return 99
##    fi
##
### Check if the input detection and measurement images are similar, as for detection images strongly differing from the
### observed images, subtraction of filaments from the latter will likely produce wrong results.
##  
##    $path'/imgstat' savein ${cfgimpath[i]}'/'${cfgdetim[i]} ${cfgimpath[i]}'/'${cfgdetim[i]}'.omask' $verb; chk_rc
##    
##    read min1 max1 mea1 med1 totsum sig1 skew kurt edgemean < '.+imgstat2'; chk_rc
##
##    'CHECK_IMGSTAT' $min1 $max1 '' $script $fun $funo '5'
##
##    $path'/imgstat' savein ${cfgimpath[i]}'/'${cfgobsim[i]} ${cfgimpath[i]}'/'${cfgdetim[i]}'.omask' $verb; chk_rc
##    
##    read min2 max2 mea2 med2 totsum sig2 skew kurt edgemean < '.+imgstat2'; chk_rc
##
##    'CHECK_IMGSTAT' $min2 $max2 '' $script $fun $funo '6'
##
##    med2med='1.0'
##
##    'COMPARE_NUMBERS' $med2 '>' $med1; rsltmed=$?
##    if [[ $rsltmed -eq 1 ]]
##    then 
##      'COMPARE_NUMBERS' $med1 '=' '0.0'; rsltmed1=$?
##      if [[ $rsltmed1 -eq 0 ]]; then med2med=$(echo "scale=5; $med2/$med1" | bc); chk_rc; fi
##    else 
##      'COMPARE_NUMBERS' $med2 '=' '0.0'; rsltmed2=$?
##      if [[ $rsltmed2 -eq 0 ]]; then med2med=$(echo "scale=5; $med1/$med2" | bc); chk_rc; fi
##    fi
##    'COMPARE_NUMBERS' $med2med '>' '3.0'; rsltm2m=$?
##    if [[ $rsltm2m -eq 1 ]]
##    then echo; echo ' '$script': '$fun': WARNING:'
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo ' INFO: Detection and measurement images are significantly different:'
##      echo '       '${cfgimpath[i]}
##      echo '       detection image: '${cfgdetim[i]}'.fits'
##      echo '       measuremt image: '${cfgobsim[i]}'.fits'
##      echo '       detection image median value = '$med1
##      echo '       measuremt image median value = '$med2
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo ' HINT: Although detection images may (in principle) be quite different from' 
##      echo '       measurement images, in practice it will create problems when subtracting'
##      echo '       filaments. One can continue using very different detection images only'
##      echo '       when the configuration parameter FILAMENTS is set to "n". This, however,'
##      echo '       is not recommended for strongly filamentary images, as it may result in'
##      echo '       extracting considerable numbers of spurious sources.'
##      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
##      echo -n ' QQQQ: Do you still want to continue (timeout 60 min) (y/N)?: '; read -s -t 3600 answer; rc=$?
##      if [[ $rc -eq 1 ]]; then answer='?'; fi
##      if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
##      then answer='y'; echo 'yes...'
##      elif [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" ]]
##      then answer='n'; echo 'no!'
##      else answer='n'; echo 'assuming no!'
##      fi  
##      if [[ $answer == "n" ]]
##      then fun=$funo; return 99
##      fi
##    fi
  
    obscd1o=$obscd1; obscd2o=$obscd2; obscrp1o=$obscrp1; obscrp2o=$obscrp2; obscrv1o=$obscrv1; obscrv2o=$obscrv2; obsraso=$obsras; obsdeco=$obsdec
    detcd1o=$detcd1; detcd2o=$detcd2; detcrp1o=$detcrp1; detcrp2o=$detcrp2; detcrv1o=$detcrv1; detcrv2o=$detcrv2; detraso=$detras; detdeco=$detdec
    mskcd1o=$mskcd1; mskcd2o=$mskcd2; mskcrp1o=$mskcrp1; mskcrp2o=$mskcrp2; mskcrv1o=$mskcrv1; mskcrv2o=$mskcrv2; mskraso=$mskras; mskdeco=$mskdec
  done
  
  echo ' ok'

  if [[ $abort == "yes" ]]; then echo; fun=$funo; return 99; fi

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

GET_IMAGE_SIZES ()
{
  local funo=$fun; fun='GET_IMAGE_SIZES'; title=$script': => '\'$fun\'
  echo; echo ' '$title ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  local image=$1; local i

# Get the numbers of pixels in both dimensions (from sky at the 1st wavelength).
  
  $path'/readhead' save NAXIS1 NAXIS2 $image $verb; chk_rc

  read naxis1 nx naxis2 ny < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  if [[ $nx -le $ny ]]; then pixmin=$nx; else pixmin=$ny; fi             
  if [[ $nx -ge $ny ]]; then pixmax=$nx; else pixmax=$ny; fi             

# Get the pixel sizes in both dimensions (in degrees).
  
  $path'/readhead' save CDELT1 CDELT2 $image $verb; chk_rc

  read cdelt1 dx cdelt2 dy < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

# Avoid negative pixel sizes.

  if [[ ${dx:0:1} == "-" ]]; then dx=${dx:1}; fi                        

# Convert pixel sizes from scientific notation to the fixed floating-point format.

  lendx=${#dx}; lendy=${#dy}; dexpx=${dx:(-4)}; dexpy=${dy:(-4)}

  if [[ ${dexpx:0:1} == "E" || ${dexpx:0:1} == "e" ]]
  then dexpx=${dexpx:1}; dx=$(echo "scale=20; ${dx:0:(lendx-4)}*10^$dexpx" | bc); chk_rc
  fi
  if [[ ${dexpy:0:1} == "E" || ${dexpy:0:1} == "e" ]]
  then dexpy=${dexpy:1}; dy=$(echo "scale=20; ${dy:0:(lendy-4)}*10^$dexpy" | bc); chk_rc
  fi

# Convert pixel and image sizes in arcseconds and degrees.

     dxas=$(echo "scale=20; $dx*3600"  | bc); chk_rc;    dyas=$(echo "scale=20; $dy*3600"  | bc); chk_rc
  sidexas=$(echo "scale=20; $nx*$dxas" | bc); chk_rc; sideyas=$(echo "scale=20; $ny*$dyas" | bc); chk_rc
  sidexdg=$(echo "scale=20; $nx*$dx"   | bc); chk_rc; sideydg=$(echo "scale=20; $ny*$dy"   | bc); chk_rc
  sqpixas=$(echo "scale=20; $dxas*$dyas" | bc); chk_rc
  if [[ ${sidexdg:0:1} == "." ]]; then sidexdg='0'$sidexdg; fi
  if [[ ${sideydg:0:1} == "." ]]; then sideydg='0'$sideydg; fi
  echo
  echo ' '$script': Image sizes: '$nx' x '$ny' pixels, dx = '${dxas:0:6}', dy = '${dyas:0:6}' arcsec'
  echo ' '$script': Image sizes: '${sidexas:0:6}' x '${sideyas:0:6}' arcsec = '${sidexdg:0:6}' x '${sideydg:0:6}' degrees'

# Observational beam should not be smaller than 2 pixels in well-sampled images.

  for (( i=1; i <= $nwaves; i++ ))
  do
    dxas2=$(echo "scale=20; 2.0*$dxas" | bc); chk_rc
    dyas2=$(echo "scale=20; 2.0*$dyas" | bc); chk_rc
    'COMPARE_NUMBERS' ${beam[i]} '<=' $dxas2; rsltx=$?
    'COMPARE_NUMBERS' ${beam[i]} '<=' $dyas2; rslty=$?

    if [[ $rsltx -eq 1 || $rslty -eq 1 ]]
    then echo
      echo ' '$script': WARNING: Image pixel is too large at '${wave[i]}' um:'
      echo ' '$script': WARNING: beam: '${beam[i]}' arcsec, pixel: '${dxas:0:11}' arcsec'
      echo ' '$script':  ADVICE: Think about it now! (timeout 1 minute)...'
      read -s -t 60 answer; rc=$?
    fi

# MINPIX is computed from a fraction of the beam area.

    minpix[i]=$(echo "scale=20; (1/3)*3.14159*(${beam[i]}/2)^2/$sqpixas" | bc); chk_rc
    if [[ ${minpix[i]:0:1} == "." ]]; then minpix[i]='0'${minpix[i]}; fi
    minpix[i]=${minpix[i]%.*}   #<-- make the number integer
   
    if [[ ${minpix[i]} -lt $minpixfloor ]]; then minpix[i]=$minpixfloor; fi
  done
  
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

GET_SMOOTHING_BEAMS ()
{          
  local funo=$fun; fun='GET_SMOOTHING_BEAMS'; title=$script': => '\'$fun\'
  if [[ $decomposing == "no" ]]; then fun=$funo; return 0; fi
  echo; echo ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  local i; local j; local strucmaxsize=0; local hibound; local lobound; local scalemaxsize; local firstscaleminimum
  local cfgbeamminm; local bigbeam; local dxasm

# Define default (automatic, optimal) values for the first (smallest) scale.

  dxasm=$(echo "scale=20; 2.0*$dxas" | bc); chk_rc
  cfgbeamminm=$(echo "scale=20; $fsbelowbeam*$cfgbeammin" | bc); chk_rc
  'COMPARE_NUMBERS' $dxasm '<' $cfgbeamminm; rslt=$?
 
  if [[ $rslt -eq 1 ]]
  then firstscaleminimum=$cfgbeamminm
  else firstscaleminimum=$dxasm
  fi
  if [[ $scale1 == "0" ]]; then scale1=$firstscaleminimum; fi
  if [[ ${scale1:0:1} == "." ]]; then scale1='0'$scale1; fi

# Limit the largest smoothing beam.

  'COMPARE_NUMBERS' $sidexas '<=' $sideyas; rslt=$?
  if [[ $rslt -eq 1 ]]
  then sizeimage=$sidexas
  else sizeimage=$sideyas
  fi

  fullimagesize=$(echo "scale=20; $sizeimage*$fscalemax" | bc); chk_rc; fullimagesize=${fullimagesize%.*}

  if [[ $sfsx == "+" ]]
  then
    filsrcmaxsize=$fullimagesize
  else
    strucmaxsize=$(echo "scale=20; 3*$srcmaxsizemax*$fscalemax" | bc); chk_rc; strucmaxsize=${strucmaxsize%.*}
    filammaxsize=$(echo "scale=20; 3*$filmaxsizemax*$fscalemax" | bc); chk_rc; filammaxsize=${filammaxsize%.*}
    if [[ $filammaxsize -gt $strucmaxsize ]]
    then filsrcmaxsize=$filammaxsize
    else filsrcmaxsize=$strucmaxsize
    fi 
  fi
  
  if [[ $flattening != "yes" && $flattening != "done" ]]
  then
    scalemaxsize=$fullimagesize
  else
    if [[ $filsrcmaxsize -gt $fullimagesize ]]
    then scalemaxsize=$fullimagesize
    else scalemaxsize=$filsrcmaxsize
    fi 
  fi

  if [[ ${sfactorcfg:0:1} == "0" ]]
  then 
    sfactor=$(echo "scale=20; 1.00001*e(l($scalemaxsize/$scale1)/($nscales-1))" | bc -l); chk_rc
    'COMPARE_NUMBERS' $sfactor '<' '1.03000000000000000000'; rslt=$?
    if [[ $rslt -eq 1 ]]; then sfactor='1.03000000000000000000'; fi
    scale1=$(echo "scale=20; $scale1/$sfactor" | bc); chk_rc
    if [[ ${scale1:0:1} == "." ]]; then scale1='0'$scale1; fi
    sfactor=$(echo "scale=20; 1.00001*e(l($scalemaxsize/$scale1)/($nscales-1))" | bc -l); chk_rc
    'COMPARE_NUMBERS' $sfactor '<' '1.03000000000000000000'; rslt=$?
    if [[ $rslt -eq 1 ]]; then sfactor='1.03000000000000000000'; fi
  fi

  hibound=$(echo "scale=20; $scalemaxsize*$sfactor" | bc); chk_rc; hibound=${hibound%.*}   #<-- make the number integer
  lobound=$scalemaxsize; lobound=${lobound%.*}   #<-- make the number integer

  if [[ $mysimsky != "yes" ]]
  then
    firstscaleminimumx=$(echo "scale=20; $firstscaleminimum/$sfactor" | bc); chk_rc
    'COMPARE_NUMBERS' $scale1 '<' $firstscaleminimumx; rslt=$?
 
    if [[ $rslt -eq 1 ]]
    then echo
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' '$script': WARNING: First scale too small for a beam of '$cfgbeammin' arcsec'
      echo ' '$script': WARNING: Scale1: '$scale1' arcsec < First scale: '${firstscaleminimumx:0:11}' arcsec'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' '$script':  ADVICE: Change scale1 to '${firstscaleminimumx:0:11}' arcsec (timeout 1 min)...'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      read -s -t 60 answer; rc=$?
    fi

    fullimagesize=${fullimagesize%.*}   #<-- make the number integer

    if [[ $flattening != 'yes' && $flattening != 'done' ]]
    then
      if [[ $fullimagesize -lt $filsrcmaxsize ]]
      then echo
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' '$script': WARNING: Image too small for a largest scale of '$filsrcmaxsize' arcsec'
        echo ' '$script': WARNING: Full image: '$fullimagesize' arcsec < Required size: '$filsrcmaxsize' arcsec'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' '$script':  ADVICE: If the extraction is done on a sub-field of a large'
        echo ' '$script':          field, one should cut out a larger sub-field with a'
        echo ' '$script':          size of at least '$filsrcmaxsize' arcsec (timeout 1 min)...'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        read -s -t 60 answer; rc=$?
      fi
    fi
  fi
  if [[ $verb != "-verb0" ]]; then echo; fi
                                             
# Initialize variables and starting scale.

  k=0; sbeam[k]=0; addpix[k]=0; nsb1=0; nsb2=0
  if [[ $nscales -gt 0 ]]; then nscalesmax=$(( nscales + 1 )); else nscalesmax=100; fi
  if [[ $mrtrans == "yes" ]]
  then scale=$(echo "scale=20; $dxas*sqrt($sfactor)" | bc); chk_rc  #<-- k=0 scale for compatibility mode with 'mr_transform'
  else scale=$(echo "scale=20; $scale1/$sfactor*1.00000001" | bc); chk_rc  #<-- k=0 scale when no compatibility is desired
  fi
  scaleo=$scale
  
# Define beams for smoothing to different scales, as well as additional beams and pixels.
# Compute scale (in arcseconds) between the beam size and the entire image scale.

  while [[ ${scale%.*} -le $hibound ]]
  do
    km1=$k; k=$(( k + 1 ))
    scale=$(echo "scale=20; $scale*$sfactor" | bc); chk_rc
    sbeam[k]=${scale:0:6}
    
    if [[ ${scale%.*} -ge ${scale1%.*} ]]
    then
      if [[ $nsb1 -eq 0 ]]; then nsb1=$k; nsb2=$(( nsb1 + 1 )); fi

# Additional beams to convolve to next resolution (incrementally).

      if [[ $k -eq 1 ]]
      then addbeam[k]=$scale
      else addbeam[k]=$(echo "scale=20; sqrt($scale^2-$scaleo^2)" | bc); chk_rc
      fi
      
# Determine additional number of pixels to expand the image to reduce the border effects.
  
      addpix[k]=$(echo "scale=20; 1.5*${addbeam[k]}/$dxas" | bc); chk_rc
      if [[ ${addpix[k]:0:1} == "." ]]; then addpix[k]='0'${addpix[k]}; fi; addpix[k]=${addpix[k]%.*}

      if [[ $k -ge $nscalesmax && ${scale%.*} -lt $lobound ]]
      then 
        echo
        if [[ $nscales -eq 0 ]]
        then
          echo ' '$script': '$fun': WARNING:'; echo
          echo '   Could not reach maximum range of' $lobound'~'$hibound 'arcsec'
          echo '   One can reduce image size or increase sfactor'; sleep 3
        fi
        break
      fi
      if [[ $k -lt $nscalesmax ]]
      then 
        nsbeams=$k

# Some informational output.

        ratio=$(echo "scale=20; $scale/$scaleo" | bc); chk_rc
        addpixb=${addpix[k]}

        'LEADZEROS' 3 $addpixb addpixb; 'LEADZEROS' 1 $k zk

        if [[ $verb != "-verb0" ]]
        then 
          echo ' Beam' $zk':' ${sbeam[k]} '('${scale:0:11}') ratio:' ${ratio:0:8} 'addbeam:' ${addbeam[k]:0:6} 'addpix:' $addpixb
        fi
      fi
      if [[ ${scale%.*} -ge $lobound && ${scale%.*} -le $hibound ]]
      then 
        echo; echo ' '$script': Scale sizes reached maximum range of' $lobound'~'$hibound 'arcsec'; break
      fi
    fi
    scaleo=$scale
  done
  nsbeamsp1=$(( nsbeams + 1 )); nsbm1=$(( nsb1 - 1 )); nums=$(( nsbeamsp1 - nsb1 ))
  bigbeam=${sbeam[nsbeams]}

  echo ' '$script': Total of '$nums' scales between '${sbeam[nsb1]}' and '${sbeam[nsbeams]}' arcsec'
  echo ' '$script': Scale factor used: '$sfactor

  if [[ ${bigbeam%.*} -lt ${scalemaxsize%.*} ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Scales could not reach SCALEMAXSIZE ('${scalemaxsize%.*}' arcsec)'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

  if [[ $nsd1 -lt 1 || ($nscales -gt 0 && $nsd1 -gt $nscales) ]]
  then
    nsd1=1; echo; echo ' '$script': '$fun': WARNING: Parameter NSD1 has been reset to 1.'
  fi
  
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CLEAR_IMAGE_BORDERS ()
{
  local funo=$fun; fun='CLEAR_IMAGE_BORDERS'; title=$script': => '\'$fun\'
  local clrtype=$1; local width=$2; local imagenamein=$3; local imagenameout=$4
  if [[ $4 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'" "'$4'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$fun': '$clrtype' '$width' '$imagenamein; fi
  if [[ ! -e $imagenamein && ! -e $imagenamein'.fits' ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$imagenamein\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

# Clean several-pixel border around the image to clean it of border effects.

  $path'/modfits' border   -$width $imagenamein  -o $imagenameout $verb; chk_rc
  $path'/modfits' $clrtype  $width $imagenameout -o $imagenameout $verb; chk_rc

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CREATE_MASKS ()
{                          
  local funo=$fun; fun='CREATE_MASKS'; title=$script': => '\'$fun\'
  local cutoff=$1; local maskimagein=$2; local maskimageout=$3
  if [[ $3 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$fun': '$maskimagein; fi
  if [[ ! -e $maskimagein && ! -e $maskimagein'.fits' ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$maskimagein\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
 
  $path'/modfits' minimum $cutoff y $maskimagein  -o $maskimageout $verb; chk_rc
  $path'/modfits' maximum $cutoff n $maskimageout -o $maskimageout $verb; chk_rc
  $path'/modfits' divide  $cutoff   $maskimageout -o $maskimageout $verb; chk_rc

  'CLEAR_IMAGE_BORDERS' border $bpixmsk $maskimageout $maskimageout; chk_rc

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CREATE_BG_MASKS ()
{                          
  local funo=$fun; fun='CREATE_BG_MASKS'; title=$script': => '\'$fun\'
  local maskimagein=$1; local maskimageout=$2; local obsmaskimage=$3
  if [[ $3 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$fun': '$maskimagein; fi
  if [[ ! -e $maskimagein && ! -e $maskimagein'.fits' ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$maskimagein\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

  $path'/modfits' addconst -1     $maskimagein  -o $maskimageout $verb; chk_rc
  $path'/modfits' negate          $maskimageout -o $maskimageout $verb; chk_rc
  $path'/modfits' minimum 0.01 y  $maskimageout -o $maskimageout $verb; chk_rc
  $path'/operate' $obsmaskimage x $maskimageout -o $maskimageout $verb; chk_rc 

  'CLEAR_IMAGE_BORDERS' border $bpixmsk $maskimageout $maskimageout; chk_rc

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CONVOLVE_MASKS ()
{                          
  local funo=$fun; fun='CONVOLVE_MASKS'; title=$script': => '\'$fun\'
  local cbeam=$1; local maskimagein=$2; local maskimageout=$3
  if [[ $3 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$fun': '$cbeam' '$maskimagein; fi
  maskimagein=${maskimagein/.fits/}; maskimageout=${maskimageout/.fits/}
  if [[ ! -e $maskimagein'.fits' ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$maskimagein'.fits'\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local beamsize; local addpix

  beamsize=$(echo "scale=20; $cbeam" | bc); chk_rc
  addpix=$(echo "scale=20; 1.5*$beamsize/$dxas" | bc); chk_rc
  if [[ ${addpix:0:1} == "." ]]; then addpix='0'$addpix; fi; addpix=${addpix%.*}   #<-- make the number integer
 
  $path'/modfits' maximum 0.99 n $maskimagein -o $maskimageout $verb; chk_rc

  'CONVOLVE_IMAGE' border border $addpix $beamsize $maskimageout $maskimageout; chk_rc

  'CREATE_MASKS' 0.01 $maskimageout $maskimageout; chk_rc

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CONVOLVE_IMAGE ()
{                          
  local funo=$fun; fun='CONVOLVE_IMAGE'; title=$script': => '\'$fun\'
  local what1=$1; local what2=$2; local addpixels=$3; local beamsize=$4; local imagein=$5; local imageout=$6; local maskimage=$7
  if [[ $6 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'" "'$4'" "'$5'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$fun': '$addpixels' '$beamsize' '$imagein; fi
  imagein=${imagein/.fits/}; imageout=${imageout/.fits/}
  if [[ ! -e $imagein'.fits' ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$imagein'.fits'\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

# Convolve the rms image with a large smoothing beam; if requested, expand masked area of the image before convolution.

  if [[ $maskimage == "" ]]
  then
    if [[ $imagein != $imageout ]]
    then
      \cp $imagein'.fits' $imageout'.fits' 2>&1; chk_rc
    fi
  else
    $path'/expanda' 1 $imagein $maskimage -o $imageout $verb; chk_rc
  fi
  $path'/modfits' $what1  $addpixels $imageout -o $imageout $verb; chk_rc
  $path'/fftconv'        $beamsize 0 $imageout -o $imageout $verb; chk_rc
  $path'/modfits' $what2 -$addpixels $imageout -o $imageout $verb; chk_rc

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

DECOMPOSE_IMAGES ()
{                          
  local funo=$fun; fun='DECOMPOSE_IMAGES'; title=$script': => (1) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $decomposing == "no" ]]; then echo ' ~~~~~> skipping...'; fun=$funo; return 0; else echo; fi
  decomp_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  local scale1=0; local nscales=0; local sfactor=2; local usm=''; local msu=''; local con=''; local pos=''; local origpath
  local image; local maskimage; local i; local j; local zj; local nparams=${#*}; local nmust=3
  if [[ $nparams -lt $nmust ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  nprogress=0
    
  if [[ $1 != "0" ]]; then scale1=$1; fi; if [[ $2 != "0" ]]; then nscales=$2; fi; if [[ $3 != "0" ]]; then sfactor=$3; fi

# Decompose all images in spatial scales.
  
  for (( i=1; i <= $nwaves; i++ ))
  do    
    if [[ $originpath != ${dirmono[i]} ]]
    then origpath=${dirmono[i]}
    else origpath='.'
    fi
    image=${detectionclone[i]}
    maskimage=${imageomask[i]}

    $path'/expanda' 1 $image $maskimage -o $image'.con' $verb; chk_rc

    if [[ $savespace -eq 0 ]]
    then
      \cp 'z0.fits' $image'.sum.fits' 2>&1; chk_rc
    fi

    if [[ -e ${filedecomposing[i]} ]]
    then 
      if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
      if [[ -e $subdirbackups'/'${filedecomposing[i]} ]]
      then
        backtimestamp=`date +%y%m%d.%H%M%S`
        \mv $subdirbackups'/'${filedecomposing[i]} $subdirbackups'/'${filedecomposing[i]}'.'$backtimestamp 2>&1; chk_rc
      fi
      \cp ${filedecomposing[i]} $subdirbackups 2>&1; chk_rc
    fi
    
    echo '#'"${headerinfo[1]:3}" > ${filedecomposing[i]}
    for (( v=2; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}" >> ${filedecomposing[i]}; done
    echo '#' >> ${filedecomposing[i]}
    echo '#' $cdate >> ${filedecomposing[i]}
    echo '#' >> ${filedecomposing[i]}
    echo '# List of the decomposed single-scale detection images: scale factor = '$sfactor >> ${filedecomposing[i]}
    echo '#' >> ${filedecomposing[i]}

# Perform image transformations.
    
    for (( j=$nsb1; j <= $nsbeams; j++ ))
    do 
      if [[ $verb == "-verb0" ]]
      then 
        if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
        'PROGRESS_BAR' "$script: DECOMPOSING$iw" $j $nsb1 $nsbeams 79 "-"
      fi
      jm1=$(( j - 1 ))
      'LEADZEROS' 1 $j zj; 'LEADZEROS' 1 $jm1 zjm1
      imageusm=$image'.~'$zj'.c'${sbeam[j]}'as'    #<-- unsharp-mask image
      imagemsu=$image'.'$zj'~.c'${sbeam[j]}'as'    #<-- convolved image 
      imagessc=$image'.'$zj'.c'${sbeam[j]}'as'     #<-- single-scale image
      imagecon=$image'.c'${sbeam[j]}'as'           #<-- largest convolved image
    
# Expand the image incrementally to minimize border effects.
# Convolve incrementally to save time and memory (especially when 'sfactor' is close to 1).
# Remove the expanded border and save image under the same name. 
                                                                                           
      'CONVOLVE_IMAGE' expand border ${addpix[j]} ${addbeam[j]} $image'.con' $image'.con'; chk_rc
    
# Subtract the smoothed (unsharp) image from the original image.
    
      $path'/operate' $image - $image'.con' -o $imageusm $verb; chk_rc
    
# Subtract all previous scales to determine a single-scale image.
    
      if [[ $j -eq $nsb1 ]]
      then 
        \cp $imageusm'.fits' $imagessc'.fits' 2>&1; chk_rc
      else
        $path'/operate' $imageusm - $imageusmo -o $imagessc $verb; chk_rc
      fi
      $path'/operate' $imagessc x $maskimage -o $imagessc $verb; chk_rc
             
# Sum up all previous scales to check for consistency.
    
      if [[ $savespace -eq 0 ]]
      then
        $path'/operate' $image'.sum' + $imagessc -o $image'.sum' $verb; chk_rc
      fi
    
      if [[ $origpath != "." ]]
      then
        \mv $imagessc'.fits' $origpath 2>&1; chk_rc
      fi
    
      if [[ $usm != "-usm" && $j -ge $nsb2 ]]
      then
        \rm $imageusmo'.fits' 2>&1; chk_rc
      else
        if [[ $j -ge $nsb2 ]]
        then
          $path'/operate' $imageusmo x $maskimage -o $imageusmo $verb; chk_rc
        fi
      fi
      if [[ $con == "-con" ]]
      then 
        \cp $image'.con.fits' $imagecon'.fits' 2>&1; chk_rc
      fi
      if [[ $msu == "-msu" ]]
      then 
        \cp $image'.con.fits' $imagemsu'.fits' 2>&1; chk_rc
        $path'/operate' $imagemsu x $maskimage -o $imagemsu $verb; chk_rc
      fi
      imageusmo=$imageusm

      echo \'${dirmono[i]}'/'$imagessc'.fits'\' >> ${filedecomposing[i]}

      if [[ -e '+stopitnow!' ]]
      then 
        \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
        echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE.'; echo; exit 99
      fi
    done                               
    
    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' 'complete' $nsbeams $nsb1 $nsbeams 79 "-"
    fi
    
    if [[ $usm != "-usm" ]]; then \rm $imageusm'.fits' 2>&1; chk_rc; fi
    
# What remains is a smoothed image containing all largest scales.
# The sum of all scales must be equal to the original input image.
                        
    \mv $image'.con.fits' $imagecon'.fits' 2>&1; chk_rc

    if [[ $savespace -le 1 ]]
    then
      if [[ $savespace -eq 0 ]]
      then
        $path'/operate' $image'.sum' + $imagecon -o $image'.sum' $verb; chk_rc
      fi
      if [[ $origpath != "." ]]
      then
        \mv $imagecon'.fits' $origpath 2>&1; chk_rc
      fi
    fi
  done
  
  decomp_end=`date +%s`; decomp_time=$((decomp_end - decomp_beg))
  echo; echo ' GETSOURCES: '$decomp_time' SECONDS'
  fun=$funo
} 
#___________________________________________________________________________________________________________________________________

ITERATE_CUT-OFFS ()
{
  local funo=$fun; fun='ITERATE_CUT-OFFS'; title=$script': => '\'$fun\'
  if [[ $5 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'" "'$3'" "'$4'" "'$5'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$title; fi  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  local it; local itm1; local itm2; local itm3; local itp1; local itmax=20; local ratio; local converged=''
  local sigma[0]='999999999.999999999'; local relcorrit1; local relcorrit2='1.000000000'; local relcorrit3='1.000000000'
  local relcorrmax='0.010000000'; local relcorritco='0.0'; local xsigma

  local iwave=$1; local jscale=$2; local imagein=$3; local nsigmacut=$4; local obsmask=$5; local firstsig=$6

  echo >> $logit; echo \'$imagein\'': iterating cut-off levels to a relative accuracy of '${relcorrmax:0:6} >> $logit; echo >> $logit

  'LEADZEROS' 1 $jscale zjscale

# Define initial cut-off level (note that generally it's not good to define it as level=0 for the images themselves).
  
  $path'/imgstat' savein -nomed $imagein $obsmask $verb; chk_rc

  read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc

  'CHECK_IMGSTAT' $min $max $sig $script $fun $funo '7'

  if [[ ${min:0:1} == "-" ]]; then min=${min:1}; fi
  if [[ ${min:0:1} == "." ]]; then min='0'$min; fi
  if [[ ${max:0:1} == "-" ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Maximum is negative: '$max
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  if [[ $firstsig != "" ]]; then sig=$firstsig; fi
  if [[ ${sig:0:1} == "." ]]; then sig='0'$sig; fi
  firstcut=$(echo "scale=20; $nsigmacut*$sig" | bc); chk_rc
  if [[ ${firstcut:0:1} == "." ]]; then firstcut='0'$firstcut; fi

  echo ' iter: 00  meanbg:' ${mea:0:11} ' sigma:' ${sig:0:11} ' sigma*'${nsigmacut:0:7}':' ${firstcut:0:11} >> $logit

# Create initial mask images normalized to 1 (cut-off level for the first iteration).

  'CREATE_MASKS' $firstcut $imagein $imagein'.mask.01'; chk_rc

  $path'/fftconv' ${sbeam[jscale]} 0 $imagein'.mask.01' scalepeak -o $imagein'.mask.01' $verb; chk_rc
  $path'/modfits' minimum 0.01 y $imagein'.mask.01' -o $imagein'.mask.01' $verb; chk_rc
  $path'/modfits' maximum 0.01 n $imagein'.mask.01' -o $imagein'.mask.01' $verb; chk_rc
  $path'/modfits' divide  0.01 $imagein'.mask.01' -o $imagein'.mask.01' $verb; chk_rc

# Iterations for best possible cut-off level.

  for (( it=1; it <= $itmax; it++ ))
  do
    itm1=$(( it - 1 )); itp1=$(( it + 1 )); 'LEADZEROS' 1 $it zit; 'LEADZEROS' 1 $itp1 zitp1
    itm2=$(( it - 2 )); if [[ $itm2 -lt 0 ]]; then itm2=0; fi
    itm3=$(( it - 3 )); if [[ $itm3 -lt 0 ]]; then itm3=0; fi

# Get new intensity cut-off level from only pixels outside the mask. Those pixels have values closer to 0 (from both positive
# and negative sides) than the cut-off level from the previous iteration. This is kind of a clipping procedure: we clip off
# pixels with values exceeding (in absolute value) a given threshold and consider only remaining pixels when computing
# rms value for the background.

# Multiply by the observational mask to only consider the areas we want to.

    $path'/operate' $obsmask x $imagein'.mask.'$zit -o $imagein'.mask.'$zit $verb; chk_rc 

# Special case when input `nsigmacut` is 0 (useful when there is no noisy background in images)

    'COMPARE_NUMBERS' $nsigmacut '!=' '0'; rslt=$?

# Create a mask for the background by negating the mask of the sources.
# Multiply by the observational mask to exclude garbage in high-noise border areas.
# Compute sigma value over the observed background area (excluding the sources).

    if [[ $rslt -eq 1 ]]
    then
      'CREATE_BG_MASKS' $imagein'.mask.'$zit $imagein'.mask.'$zit'.bg' $obsmask; chk_rc

# Check if the background mask is still large enough for statistical values to be meaningful.

      $path'/imgstat' savein -nomed $imagein'.mask.'$zit'.bg' $imagein'.mask.'$zit'.bg' $verb; chk_rc

      read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc

      numpixmin=$(echo "scale=20; 20*3.14159*(${sbeam[jscale]}/2)^2/$sqpixas" | bc); chk_rc
      numpixmin=${numpixmin%.*}   #<-- make the number integer
      'COMPARE_NUMBERS' $totsum '<=' $numpixmin; rctotsum=$?
      
      if [[ $rctotsum -eq 1 ]]
      then echo >> $logit
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' >> $logit
        echo ' INFO: Too few pixels remain in the background: '$totsum' < '$numpixmin' (20 beams)'        >> $logit
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' >> $logit
        \rm $imagein'.mask.'$zit'.fits' 2>&1; chk_rc
        \rm $imagein'.mask.'$zit'.bg.fits' 2>&1; chk_rc 
        toofewbgpixels=$jscale; toofewbgpixscale=${sbeam[jscale]}; fun=$funo; return 212
      else \rm '.+imgstat2' 2>&1; chk_rc
      fi

      $path'/imgstat' savein -nomed $imagein $imagein'.mask.'$zit'.bg' $verb; chk_rc
      read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
      'COMPARE_NUMBERS' $min '=' $max; rcminmax=$?
      'COMPARE_NUMBERS' $min '=' '0.000000000'; rcminzero=$?
      if [[ $rcminmax -eq 1 && $rcminzero -eq 1 ]]
      then \rm '.+imgstat2' 2>&1; chk_rc; fun=$funo; return 200
      fi
      'CHECK_IMGSTAT' $min $max $sig $script $fun $funo '8'

      \rm $imagein'.mask.'$zit'.bg.fits' 2>&1; chk_rc

      meanbg=$mea; if [[ ${meanbg:0:1} == "." ]]; then meanbg='0'$meanbg; fi
      if [[ $it -eq 1 && $firstsig != "" ]]; then sig=$firstsig; fi
      if [[ ${sig:0:1} == "." ]]; then sig='0'$sig; fi
      sigma[it]=$sig
    else
      sigma[it]='0.00001'
    fi
    
# Attempt to accelerate convergence as much as possible.
      
    relcorritc=$(echo "scale=20; ${sigma[it]}/${sigma[itm1]}-1" | bc); chk_rc
    sigmaratio=$(echo "scale=20; ${sigma[itm1]}/${sigma[it]}" | bc); chk_rc
    relcorratio=$(echo "scale=20; $relcorritco/($relcorritc+0.000001)" | bc); chk_rc  
    'COMPARE_NUMBERS' $sigmaratio   '>' '1.0'; rslt1=$?
    'COMPARE_NUMBERS' $sigmaratio  '<=' '2.0'; rslt2=$?
    'COMPARE_NUMBERS' $relcorratio '<=' '2.0'; rslt3=$?

    if [[ $it -ge 2 && $rslt1 -eq 1 && $rslt2 -eq 1 && $rslt3 -eq 1 ]]
    then
      corrfact=$(echo "scale=20; 2.0/$sigmaratio" | bc); chk_rc
    else
      corrfact='1.0'
    fi
    
    relcorritco=$relcorritc

    sigma[it]=$(echo "scale=20; ${sigma[itm1]}+$corrfact*(${sigma[it]}-${sigma[itm1]})" | bc); chk_rc
    if [[ ${sigma[it]:0:1} == "." ]]; then sigma[it]='0'${sigma[it]}; fi

    sigmas=$(echo "scale=20; $nsigmacut*${sigma[it]}" | bc); chk_rc
    if [[ ${sigmas:0:1} == "." ]]; then sigmas='0'$sigmas; fi

    if [[ $it -eq 1 ]]; then sigmas1=$sigmas; fi

# Check whether iterations converge (ratio < 1) or diverge (ratio > 1).

    ratio=$(echo "scale=20; ${sigma[it]}/${sigma[itm1]}" | bc); chk_rc
    if [[ ${ratio:0:1} == "." ]]; then ratio='0'$ratio; fi
    ratio=${ratio%.*}   #<-- make the number integer

# Compute convergence criterion based on relative correction.

    relcorrit1=$(echo "scale=20; ${sigma[it]}/${sigma[itm1]}-1" | bc); chk_rc
    if [[ ${relcorrit1:0:1} == "-" ]]; then relcorrit1=${relcorrit1:1}; fi
    if [[ ${relcorrit1:0:1} == "." ]]; then relcorrit1='0'$relcorrit1 ; fi

# In difficult convergence cases it may be necessary to check also this relative correction.

    if [[ $it -ge 2 ]]
    then relcorrit2=$(echo "scale=20; ${sigma[it]}/${sigma[itm2]}-1" | bc); chk_rc
      if [[ ${relcorrit2:0:1} == "-" ]]; then relcorrit2=${relcorrit2:1}; fi
      if [[ ${relcorrit2:0:1} == "." ]]; then relcorrit2='0'$relcorrit2 ; fi
    fi

# In difficult convergence cases it may be necessary to check also this relative correction.

    if [[ $it -ge 3 ]]
    then relcorrit3=$(echo "scale=20; ${sigma[itm1]}/${sigma[itm3]}-1" | bc); chk_rc
      if [[ ${relcorrit3:0:1} == "-" ]]; then relcorrit3=${relcorrit3:1}; fi
      if [[ ${relcorrit3:0:1} == "." ]]; then relcorrit3='0'$relcorrit3 ; fi
    fi

# Final decision on the convergence: for normal convergence, for difficult (divergence-)convergence,
# and for (almost) no convergence at all (3 conditions respectively).

    if [[ $relcorrit1 < $relcorrmax || ($relcorrit2 < $relcorrmax && $relcorrit3 < $relcorrmax) ]]
    then 
      if [[ $it -ge 3 ]]; then converged='yes'; fi
    fi

# Write convergence information in a logfile.

    echo ' iter:' $zit ' meanbg:' ${meanbg:0:11} ' sigma:' ${sigma[it]:0:11} ' sigma*'${nsigmacut:0:7}':' ${sigmas:0:11} \
         ' rcorr:' ${relcorrit1:0:7} ${relcorrit2:0:7} ${relcorrit3:0:7} ' accel:' ${corrfact:0:4} >> $logit

    'COMPARE_NUMBERS' ${sigma[it]:0:15} '=' ${sigma[itm1]:0:15}; rslt1=$?
    'COMPARE_NUMBERS' ${sigma[it]:0:15} '>' ${sigma[itm1]:0:15}; rslt2=$?

    if [[ (${relcorrit1:0:7} == ${relcorrit2:0:7} && $relcorrit3 == "0") || $relcorrit1 != "0" ]]
    then
      if [[ $rslt1 -eq 1 ]]
      then
        if [[ $verb != "-verb0" ]]
        then echo
          echo ' '$script': '$fun': WARNING: No convergence...'
        fi
        echo >> $logit; echo ' WARNING: No convergence...' >> $logit; fun=$funo; return 111
      fi
      if [[ (${relcorrit1:0:7} == ${relcorrit2:0:7} && $relcorrit3 == "0") && $rslt2 -eq 1 ]]
      then 
        if [[ $verb != "-verb0" ]]
        then echo
          echo ' '$script': '$fun': WARNING: Almost converged (from below), accepting...'
        fi
        echo >> $logit; echo ' WARNING: Almost converged (from below), accepting...' >> $logit
        converged='yes'
      fi
    fi

    'COMPARE_NUMBERS' $nsigmacut '=' '0'; rslt=$?
    if [[ $rslt -eq 1 ]]
    then sigmas=$(echo "scale=20; 0.00001" | bc); chk_rc
    fi

# Take minimum cut-off level of the two last iterations.
          
    'COMPARE_NUMBERS' ${sigma[it]} '>' ${sigma[itm1]}; rslt=$?; if [[ $rslt -eq 1 ]]; then sigma[it]=${sigma[itm1]}; fi

# Create a mask from the original image with the cut-off level obtained at current iteration.

    'CREATE_MASKS' $sigmas $imagein $imagein'.msks.'$zit; chk_rc

# Convolve the masks to expand them to a ~zero level.

    $path'/fftconv' ${sbeam[jscale]} 0 $imagein'.msks.'$zit scalepeak -o $imagein'.msks.'$zit $verb; chk_rc
    $path'/modfits' minimum 0.01 y $imagein'.msks.'$zit -o $imagein'.msks.'$zit $verb; chk_rc
    $path'/modfits' maximum 0.01 n $imagein'.msks.'$zit -o $imagein'.msks.'$zit $verb; chk_rc
    $path'/modfits' divide  0.01 $imagein'.msks.'$zit -o $imagein'.msks.'$zit $verb; chk_rc

# Create a mask from a negated image with the cut-off level obtained at current iteration.

    $path'/modfits' negate $imagein -o $imagein'.mask.neg.'$zit $verb; chk_rc

    'CREATE_MASKS' $sigmas $imagein'.mask.neg.'$zit $imagein'.mask.neg.'$zit; chk_rc

# Convolve the masks to expand them to a ~zero level.

    $path'/fftconv' ${sbeam[jscale]} 0 $imagein'.mask.neg.'$zit scalepeak -o $imagein'.mask.neg.'$zit $verb; chk_rc
    $path'/modfits' minimum 0.01 y $imagein'.mask.neg.'$zit -o $imagein'.mask.neg.'$zit $verb; chk_rc
    $path'/modfits' maximum 0.01 n $imagein'.mask.neg.'$zit -o $imagein'.mask.neg.'$zit $verb; chk_rc
    $path'/modfits' divide  0.01 $imagein'.mask.neg.'$zit -o $imagein'.mask.neg.'$zit $verb; chk_rc

# Accumulate masks at this scale.

    $path'/operate' $imagein'.msks.'$zit + $imagein'.mask.neg.'$zit -o $imagein'.mask.'$zitp1 $verb; chk_rc
    $path'/modfits' maximum 1 n $imagein'.mask.'$zitp1 -o $imagein'.mask.'$zitp1 $verb; chk_rc

    if [[ $filaments == "yes" ]]
    then
      xsigma=$(echo "scale=20; $fdp*($sigmas/$nsigmacut)" | bc); chk_rc
      if [[ ${xsigma:0:1} == "." ]]; then xsigma='0'$xsigma; fi

# Here the beam is defined to smoothly (and relatively rapidly) change between the two beam regimes.

      effbeam=$(echo "scale=20; e(1/6*l((1.15*${beam[iwave]})^6+(${sbeam[jscale]})^6))" | bc -l); chk_rc
      cleanpx=$(echo "scale=20; $fbm*3.14159*($effbeam)^2/$sqpixas" | bc); chk_rc; cleanpx=${cleanpx%.*}
      
      'CREATE_MASKS' $xsigma $imagein $imagein'.fm.'$zit; chk_rc

      $path'/modfits' clean4 $cleanpx $ffi $imagein'.fm.'$zit -o $imagein'.fm.'$zit $verb; chk_rc

# Check if at least one filament has been found.

      $path'/imgstat' savein -nomed $imagein'.fm.'$zit $obsmask $verb; chk_rc
      read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
      'CHECK_IMGSTAT' $min $max '' $script $fun $funo '9'
      'COMPARE_NUMBERS' $max '>' $min; rcmaxmin=$?

# Convolve the masks to expand them to a ~zero level.

      if [[ $rcmaxmin -eq 1 ]]
      then 
        $path'/fftconv' ${sbeam[jscale]} 0 $imagein'.fm.'$zit scalepeak -o $imagein'.fm.'$zit $verb; chk_rc
        $path'/modfits' minimum 0.01 y $imagein'.fm.'$zit -o $imagein'.fm.'$zit $verb; chk_rc
        $path'/modfits' maximum 0.01 n $imagein'.fm.'$zit -o $imagein'.fm.'$zit $verb; chk_rc
        $path'/modfits' divide  0.01 $imagein'.fm.'$zit -o $imagein'.fm.'$zit $verb; chk_rc
      
        $path'/operate' $imagein'.fm.'$zit + $imagein'.mask.'$zitp1 -o $imagein'.mask.'$zitp1 $verb; chk_rc
        $path'/modfits' maximum 1 n $imagein'.mask.'$zitp1 -o $imagein'.mask.'$zitp1 $verb; chk_rc
      fi
    fi

# Rename and remove some files when converged or reached maximum number of iterations.
      
    if [[ $converged == "yes" || $it -eq $itmax ]]
    then
      \mv $imagein'.mask.'$zit'.fits' $imagein'.msk.fits'  2>&1; chk_rc 
      \mv $imagein'.msks.'$zit'.fits' $imagein'.msks.fits' 2>&1; chk_rc 

      \rm $imagein'.mask.'$zitp1'.fits' 2>&1; chk_rc
      \rm $imagein'.mask.01.fits' 2>&1; chk_rc
      \rm $imagein'.mask.neg.'$zit'.fits' 2>&1; chk_rc 
      if [[ $filaments == "yes" ]]
      then
        \rm $imagein'.fm.'$zit'.fits' 2>&1; chk_rc 
      fi
      if [[ $verb != "-verb0" ]]
      then
        if [[ $converged != "yes" && $it -eq $itmax ]]
        then echo
          echo '------------------------------------------------------------------'
          echo ' No convergence: giving up, sorry; taking cut-off level at '$sigmas
          echo '------------------------------------------------------------------'; sleep 1
        fi
        if [[ $converged == "yes" ]]
        then echo 
          echo '-------------------------------------------------------------------------'
          if [[ $jscale == "0" ]]
          then echo ' Image converged in '$it' iterations with a cut-off level of '$sigmas
          else echo ' Scale '$jscale' converged in '$it' iterations with a cut-off level of '$sigmas; fi
          echo '-------------------------------------------------------------------------'; sleep 1
        fi
      fi
      break  
    fi

# Clean up.

   if [[ $it -gt 1 ]]
   then
     \rm $imagein'.mask.'$zit'.fits' 2>&1; chk_rc
   fi
   \rm $imagein'.msks.'$zit'.fits' 2>&1; chk_rc
   \rm $imagein'.mask.neg.'$zit'.fits' 2>&1; chk_rc
   if [[ $filaments == "yes" ]]
   then
     \rm $imagein'.fm.'$zit'.fits' 2>&1; chk_rc 
   fi
  done

  fun=$funo

  'COMPARE_NUMBERS' $sigmas '=' $sigmas1; rslt=$?
  if [[ $rslt -eq 1 ]]; then return 222; fi
}
#___________________________________________________________________________________________________________________________________

DEFINE_SKELETON_LEVELS ()
{
  local funo=$fun; fun='DEFINE_SKELETON_LEVELS'; title=$script': => '\'$fun\'
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$title; fi

# Find number of scales covering the range of scales described by the ratio FACT^N, given the scale factor SFACTOR.

  nsbeamsm1=$(( nsbeams - 1 )); local fact='1.414213562'; nsklevs=3
  nsklev[0]='1.9'; zsklev[0]='01'
  for (( k=1; k <= $nsklevs; k++ ))
  do
    nsklev[k]=$(echo "scale=20; 1+l($fact^$k)/l($sfactor)" | bc -l); chk_rc; nsklev[k]=${nsklev[k]:0:4}; nsklev[k]=${nsklev[k]%.*}
    'LEADZEROS' 1 ${nsklev[k]} zsklev[k]
  done

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

DEFINE_FILAMENTS_SCALES ()
{
  local funo=$fun; fun='DEFINE_FILAMENTS_SCALES'; title=$script': => '\'$fun\'
  if [[ $1 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local sfirst=$1; local fact='2'; nsfils=10
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$title; fi

  for (( k=0; k <= $nsfils; k++ ))
  do
    filscale[k]=$(echo "scale=10; $sfirst*$fact^$k" | bc); chk_rc; filscale[k]=${filscale[k]:0:6}
    if [[ ${filscale[k]:0:1} != '.' ]]
    then 
      filscale[k]=${filscale[k]%.*}
      'LEADZEROS' 3 ${filscale[k]} zfilscale[k]
    else
      zfilscale[k]='0'${filscale[k]}
    fi
  done
  nsskel=4

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

VISUALIZE_SKELETONS ()
{
  local funo=$fun; fun='VISUALIZE_SKELETONS'; title=$script': => '\'$fun\'
  if [[ $2 == "" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Too few parameters: "'$1'" "'$2'"'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  local filamentssk=$1; local imobsmask=$2
  local min; local max; local mea; local med; local totsum; local sig; local skew; local kurt; local edgemean
  if [[ $verb != "-verb0" ]]; then echo; echo ' '$title; fi

  'DEFINE_SKELETON_LEVELS'

  if [[ ! -e $filamentssk'.fits' ]]; then fun=$funo; return 0; fi

  skebeam=$(echo "scale=20; 2*$skeletonpixwidth*$dxas" | bc); chk_rc
  clepix=20

# Restrict skeletons by the observational mask image and convolve full accumulated skeletons.

  $path'/operate' $imobsmask x $filamentssk -o $filamentssk $verb; chk_rc
  $path'/fftconv' $skebeam 0 $filamentssk scalepeak -o $filamentssk'.c' $verb; chk_rc

# Produce images of smoother skeletons with increasing significance.
  
  for (( k=0; k <= $nsklevs; k++ ))
  do
    $path'/modfits' minimum ${zsklev[k]} y $filamentssk'.c' -o $filamentssk'.c'${zsklev[k]} $verb; chk_rc
###    $path'/imgstat' savein -nomed $filamentssk'.c'${zsklev[k]} ${imageomask[i]} $verb; chk_rc
    $path'/modfits' skeleton 1 $filamentssk'.c'${zsklev[k]} -o $filamentssk'.c'${zsklev[k]} $verb; chk_rc
    $path'/modfits' clean8sk $clepix 0 $filamentssk'.c'${zsklev[k]} -o $filamentssk'.c'${zsklev[k]} $verb; chk_rc
    $path'/modfits' segment8 $filamentssk'.c'${zsklev[k]} -o $filamentssk'.c'${zsklev[k]} $verb; chk_rc

    $path'/imgstat' savein -nomed $filamentssk'.c'${zsklev[k]} ${imageomask[i]} $verb; chk_rc
    read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
    'COMPARE_NUMBERS' $max '>' '0.0'; rcmaxsk=$?
    if [[ $rcmaxsk -eq 0 ]]
    then
      \rm $filamentssk'.c'${zsklev[k]}'.fits' 2>&1; chk_rc
      \rm '.+imgstat2' 2>&1; chk_rc
    fi
  done

  fun=$funo
}
#___________________________________________________________________________________________________________________________________

CLEAN_SINGLE_SCALES ()
{                          
  local funo=$fun; fun='CLEAN_SINGLE_SCALES'; funn=$fun; title=$script': => (2) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $cleaning == "no" ]]; then echo ' ~~> skipping...'; fun=$funo; return 0; else echo; fi
  clean_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  for (( v=1; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}" >> $logit; done
  echo '#' >> $logit; echo '#' $cdate >> $logit
  local nsbeams; local nsbeg; local nsbeglimit; local image; local sscimagej; local i; local j; local v; local trymax=20
  local rslt1; local rslt2; local ftune; local ftunemin='1.01'; local ssglobalmaximum  ###; local lastgoodscalemin=999
  local skewfact=''; local flower='1.01'; nprogress=0
  
  for (( i=$nwc1; i <= $nwaves; i++ ))
  do                        
    lastgoodscale[i]=999; lastbrightscale[i]=999; foundgoodscales='no'; thresh=1; threshold='9999999999.999999999'
    skewinitialjm1=0; kurtinitialjm1=0; skewinitialj=0; kurtinitialj=0; ssglobalmaximum=0; sslowerlimit=0; rsltnslow=0
    skewkurtstat='none'; try=0

    if [[ ! -e ${filedecomposing[i]} ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File not found:'
      echo '       '\'${filedecomposing[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
    
    nsbeg=0; nsbeams=0; sfxx=''
    {
    while read filename alltherest
    do
      if [[ ${filename:0:1} == '#' ]]
      then
        if [[ $alltherest != "" ]]
        then
          'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
          if [[ $sfpos -gt 0 ]]
          then
            sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
            sfactor=${alltherest:n1:22}
          fi
        fi
      else
        'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
        if [[ $wavdet -gt 0 ]]
        then
          waveixx=".${wave[i]}.det."
          length=${#waveixx}; n1=$(( wavdet + length - 1 ))
          nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
          if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
          nscbeam[nsca]=${filename:n1:12}
          sbeam[nsca]=${nscbeam[nsca]:4:6}
        fi
      fi
    done
    } < ${filedecomposing[i]}
    
    if [[ $sfxx == "" ]]
    then
      echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Scale factor not found in:'
      echo '       '\'${filedecomposing[i]}\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
    
    if [[ ${nsbeg:0:1} == '0' ]]; then nsbeg=${nsbeg:1}; fi
    nsbegp1=$(( nsbeg + 1 ))

    sbeam[0]=${sbeam[1]}
    
    image[i]=${detectionclone[i]}

    \cp 'z0.fits' ${image[i]}'.nn.fits' 2>&1; chk_rc
    \cp 'z0.fits' ${image[i]}'.re.fits' 2>&1; chk_rc

    if [[ $filaments == "yes" ]]
    then
      if [[ ! -e ${dirmono[i]}'/+filaments' ]]; then \mkdir -p ${dirmono[i]}'/+filaments' 2>&1; chk_rc; fi
      imagefb[i]=${dirmono[i]}'/+filaments/'${image[i]}'.fb'
      imagefn[i]=${dirmono[i]}'/+filaments/'${image[i]}'.fn'
      imagefp[i]=${dirmono[i]}'/+filaments/'${image[i]}'.fp'
      imagefx[i]=${dirmono[i]}'/+filaments/'${image[i]}'.fx'
      imagefm[i]=${dirmono[i]}'/+filaments/'${image[i]}'.fm'
      \cp 'z0.fits' ${imagefb[i]}'.fits' 2>&1; chk_rc
      \cp 'z0.fits' ${imagefn[i]}'.fits' 2>&1; chk_rc
      \cp 'z0.fits' ${imagefp[i]}'.fits' 2>&1; chk_rc
      \cp 'z0.fits' ${imagefx[i]}'.fits' 2>&1; chk_rc
      \cp 'z0.fits' ${imagefm[i]}'.fits' 2>&1; chk_rc
    fi

    if [[ $savespace -le 1 ]]
    then
      if [[ $originpath != ${dirmono[i]} ]]
      then
        \cp ${dirmono[i]}'/'${image[i]}'.c'${sbeam[nsbeams]}'as.fits' '.' 2>&1; chk_rc
      fi
    fi
    if [[ -e ${filecleaning[i]} ]]
    then
      if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
      if [[ -e $subdirbackups'/'${detectionclone[i]}'.cleaning' ]]
      then
        backtimestamp=`date +%y%m%d.%H%M%S`
        existingfile=$subdirbackups'/'${detectionclone[i]}'.cleaning'
        \mv $existingfile $existingfile'.'$backtimestamp 2>&1; chk_rc
      fi
      \cp ${filecleaning[i]} $subdirbackups 2>&1; chk_rc
    else
      if [[ $nsc1 -gt $nsbeg ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' HINT: It appears that you made an attempt to restart cleaning from an'
        echo '       intermediate scale before having cleaned previous scales. You need to'
        echo '       set the restart scale from '$nsc1' back to 1 in the file '\'$configfile\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
    fi
    if [[ -e ${image[i]}'.lastbright' ]]
    then 
      if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
      if [[ -e $subdirbackups'/'${image[i]}'.lastbright' ]]
      then
        backtimestamp=`date +%y%m%d.%H%M%S`
        existingfile=$subdirbackups'/'${image[i]}'.lastbright'
        \mv $existingfile $existingfile'.'$backtimestamp 2>&1; chk_rc
      fi
      \cp ${image[i]}'.lastbright' $subdirbackups 2>&1; chk_rc
    fi

    nsigmavar=$nsigmacutss
    skewinitialjm1='0'; kurtinitialjm1='0'; ssglobalmaximum='0'
    sslowerlimit='-9999999999.99999999'
    rsltbratoko=1; nsbegood=999; rsltnslow=0
    toofewbgpixels=0; toofewbgpixscale=0

    if [[ $nsc1 -le $nsbeams ]]
    then
      echo '#'"${headerinfo[1]:3}" > ${filecleaning[i]}
      for (( v=2; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}" >> ${filecleaning[i]}; done
      echo '#' >> ${filecleaning[i]}
      echo '#' $cdate >> ${filecleaning[i]}
      echo '#' >> ${filecleaning[i]}
      echo '# List of the clean detection images, onesigma, nsigmavar, thresh, imagemax, and restart data:' \
           'scale factor = '$sfactor >> ${filecleaning[i]}
      echo '#' >> ${filecleaning[i]}
    fi
    
# If restart from an intermediate scale is requested, read some quantities from the file.

    if [[ $nsc1 -gt $nsbeg ]]
    then
      nsc1m1=$(( nsc1 - 1 ))
      if [[ ! -e $subdirbackups'/'${image[i]}'.cleaning' ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'$subdirbackups'/'${image[i]}'.cleaning'\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      nsca=0
      {
      while read logfileline
      do
        if [[ ${logfileline:0:1} != '#' && $logfileline != '' ]]
        then
          read -r filename onesigma nsigmavar thresh imgmax restartdata lastgoodscale[i] lastbrightscale[i] \
                  foundgoodscales threshold skewinitialjm1 kurtinitialjm1 skewinitialj kurtinitialj ssglobalmaximum \
                  sslowerlimit nsbegood rsltnslow nsigmacutfloor nsigmacutmin nsigmavaro skewmax[i] kurtmax[i] \
                  toofewbgpixels skewkurtstat <<< "$logfileline"

          if [[ $nsc1 -le $nsbeams ]]
          then
            echo $filename $onesigma $nsigmavar $thresh $imgmax $restartdata ${lastgoodscale[i]} ${lastbrightscale[i]} \
                 $foundgoodscales $threshold $skewinitialjm1 $kurtinitialjm1 $skewinitialj $kurtinitialj $ssglobalmaximum \
                 $sslowerlimit $nsbegood $rsltnslow $nsigmacutfloor $nsigmacutmin $nsigmavaro ${skewmax[i]} ${kurtmax[i]} \
                 $toofewbgpixels $skewkurtstat >> ${filecleaning[i]}
          fi
               
          'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
          if [[ $wavdet -gt 0 ]]
          then
            waveixx=".${wave[i]}.det."
            length=${#waveixx}; n1=$(( wavdet + length - 1 ))
            nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
            threshxo[nsca]=$thresh
            imgmaxxo[nsca]=$imgmax
            onesigxo[nsca]=$onesigma
            xsigma[nsca]=$(echo "scale=20; $fdp*$onesigma" | bc); chk_rc
            xsigma0[nsca]=$(echo "scale=20; (1/10)*${xsigma[nsca]}" | bc); chk_rc
            xsigma00[nsca]=$(echo "scale=20; (1/100)*${xsigma[nsca]}" | bc); chk_rc
            if [[ ${xsigma[nsca]:0:1} == "." ]]; then xsigma[nsca]='0'${xsigma[nsca]}; fi
            if [[ ${xsigma0[nsca]:0:1} == "." ]]; then xsigma0[nsca]='0'${xsigma0[nsca]}; fi
            if [[ ${xsigma00[nsca]:0:1} == "." ]]; then xsigma00[nsca]='0'${xsigma00[nsca]}; fi
            if [[ $toofewbgpixels -gt 0 && $toofewbgpixscale == "0" ]]; then toofewbgpixscale=${sbeam[nsca]}; fi
            if [[ $nsca -eq $nsc1m1 ]]
            then 
              break
            fi
          fi
        fi
      done
      } < $subdirbackups'/'${image[i]}'.cleaning'
            
      if [[ $logfileline == '' && $nsca -eq 0 ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Trouble finding saved information to restart from the scale #'$nsc1m1
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      nsc1=$(( nsca + 1 ))
      nsc1m1=$(( nsc1 - 1 ))
    fi

###    echo '# 1nscale 2scale 3imgmax 4slope1 5slope2 6thresh 7slope2' > '+'$prefix'.cleaning.dat'

    sum1sigma=0
    threshsum=0
    filmaxsize[i]=0
    filamentsfound='no'

# Loop over all scales.

    for (( j=$nsbeg; j <= $nsbeams; j++ ))
    do
      if [[ $verb == "-verb0" ]]
      then 
        if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
        'PROGRESS_BAR' "$script: CLEANING$iw" $j $nsbeg $nsbeams 79 "-"
      fi
      'LEADZEROS' 1 $j zj
      jm1=$(( j - 1 )); if [[ $jm1 -eq 0 ]]; then jm1=1; fi
      jm2=$(( j - 2 )); if [[ $jm2 -le 0 ]]; then jm2=1; fi
      jp1=$(( j + 1 ))
      
      imgmax=${imgmaxxo[j]}
      thresh=${threshxo[j]}

      if [[ ${enforcedthresh[i]} == '(+)' ]]
      then
        {
        while read filename onesigma nsigmavar thresh imgmax restartdata lastgoodscale[i] lastbrightscale[i] \
                   foundgoodscales threshold skewinitialjm1 kurtinitialjm1 skewinitialj kurtinitialj ssglobalmaximum \
                   sslowerlimit nsbegood rsltnslow nsigmacutfloor nsigmacutmin nsigmavaro skewmax[i] kurtmax[i] \
                   toofewbgpixels skewkurtstat
        do
          if [[ ${filename:0:1} != '#' ]]
          then
            'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
            if [[ $wavdet -gt 0 ]]
            then
              waveixx=".${wave[i]}.det."
              length=${#waveixx}; n1=$(( wavdet + length - 1 ))
              nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
              if [[ $nsca -eq $j ]]
              then 
                break
              fi
            fi
          fi
        done
        } < ${image[i]}'.cleaning.(+)'
            
        if [[ $filename == '' || $nsca -ne $j ]]
        then echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Trouble finding enforced thresholds...'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; fun=$funo; return 99
        fi
      fi

      beamsratio1=$(echo "scale=9; 1.0001*${sbeam[1]}/${beam[i]}" | bc); chk_rc
      if [[ ${beamsratio1:0:1} == "." ]]; then beamsratio1='0'$beamsratio1; fi
      beamsratioj=$(echo "scale=9; 1.0001*${sbeam[j]}/${beam[i]}" | bc); chk_rc
      if [[ ${beamsratioj:0:1} == "." ]]; then beamsratioj='0'$beamsratioj; fi
      beamsratok=$fsbelowbeam
      if [[ ${beamsratok:0:1} == "." ]]; then beamsratok='0'$beamsratok; fi
      'COMPARE_NUMBERS' $beamsratio1 '>' $beamsratok; rsltbratok1=$?
      if [[ $rsltbratok1 -eq 1 ]]; then beamsratok=$beamsratio1; fi
      'COMPARE_NUMBERS' $beamsratioj '>=' $beamsratok; rsltbratok=$?

# Effective beam changes smoothly (and relatively rapidly) between the two regimes.

      effbeams[j]=$(echo "scale=20; e(1/6*l((1.2*${beam[i]})^6+(${sbeam[j]})^6))" | bc -l); chk_rc
      cleanpix[j]=$(echo "scale=20; $fbm*3.14159*(${effbeams[j]})^2/$sqpixas" | bc); chk_rc; cleanpix[j]=${cleanpix[j]%.*}

# Parameters for cleaning positives and negatives.
      
      clpixpos[j]=$(echo "scale=20; (1/120)*${cleanpix[j]}" | bc); chk_rc; clpixpos[j]=${clpixpos[j]%.*}
      clpixneg[j]=$(echo "scale=20; (1/120)*${cleanpix[j]}" | bc); chk_rc; clpixneg[j]=${clpixneg[j]%.*}

# Parameters for filament reconstruction.

      effbmrec=$(echo "scale=20; 3*${beam[i]}" | bc -l); chk_rc
      clpixbeg=$(echo "scale=20; (1/$flower)*${cleanpix[j]}" | bc); chk_rc; clpixbeg=${clpixbeg%.*}
      clpixend=$(echo "scale=20; $fbm*3.14159*(${effbmrec})^2/$sqpixas" | bc); chk_rc; clpixend=${clpixend%.*}
      if [[ $clpixbeg -lt $clpixend ]]
      then cleanrec[j]=$clpixbeg
      else cleanrec[j]=$clpixend
      fi

# Parameters for additional smoothing.

      csbeam0[j]=$(echo "scale=20; (1/10)*${effbeams[j]}" | bc); chk_rc
      'COMPARE_NUMBERS' ${csbeam0[j]} '<' $dxas; rsltcsb=$?
      if [[ $rsltcsb -eq 1 ]]; then csbeam0[j]=$dxas; fi
      addpix0[j]=$(echo "scale=20; ${csbeam0[j]}/$dxas" | bc); chk_rc

# Define file names of single-scale images.

      sscimagej=${image[i]}'.'${nscbeam[j]}
      usmimagej=${image[i]}'.~'${nscbeam[j]}
      conimagej=${image[i]}'.'$zj'~.c'${sbeam[j]}'as'
      if [[ $filaments == "yes" ]]
      then
        sscimagejfb=${dirmono[i]}'/+filaments/'$sscimagej'.fb'
        sscimagejfn=${dirmono[i]}'/+filaments/'$sscimagej'.fn'
        sscimagejfp=${dirmono[i]}'/+filaments/'$sscimagej'.fp'
        sscimagejfx=${dirmono[i]}'/+filaments/'$sscimagej'.fx'
        sscimagejfm=${dirmono[i]}'/+filaments/'$sscimagej'.fm'
        sscimagejm1=${image[i]}'.'${nscbeam[jm1]}
      fi
      ftune='1.05'
      if [[ $originpath != ${dirmono[i]} ]]
      then
        \cp ${dirmono[i]}'/'$sscimagej'.fits' '.' 2>&1; chk_rc
      fi
      
# When restarting from an intermediate scale, skip the scales that are not to be re-cleaned.    

      if [[ $j -ge $nsbeg && $j -ge $nsc1 ]]
      then
        if [[ $rsltbratok -eq 0 ]]
        then
          if [[ $j -eq $nsbeg ]]
          then
            accuscales=${image[i]}'.accu'
            \cp 'z0.fits' $accuscales'.fits' 2>&1; chk_rc
          fi
          $path'/operate' $accuscales + $sscimagej -o $accuscales $verb; chk_rc
        else
          if [[ $rsltbratoko -eq 0 ]]
          then
            if [[ $savespace -le 1 ]]
            then \cp $accuscales'.fits' $sscimagej'.fits' 2>&1; chk_rc
            else \mv $accuscales'.fits' $sscimagej'.fits' 2>&1; chk_rc
            fi
          fi
        fi
        rsltbratoko=$rsltbratok

# Determine the maximum intensity in the image under the masks.

        $path'/imgstat' savein -nomed $sscimagej ${imageomask[i]} $verb; chk_rc

        read min imgmax mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc

        'CHECK_IMGSTAT' $min $imgmax $sig $script $fun $funo '10'
    
# Take `nsigmavar`=$nsigmacutss as an initial value for iterations. There may be no convergence in some cases (for some images),
# so the iterations will be repeated if necessary, with an increased value of nsigmavar, up to the maximum `trymax` of retries.
         
        if [[ ${enforcedthresh[i]} == '' && ${lastbrightscale[i]} -eq 999 && $rsltbratok -eq 1 && $toofewbgpixels -eq 0 ]]
        then
          skewfact=$(echo "scale=20; $nsigmavar/$nsigmacutss" | bc); chk_rc
          firstsig=''
          if [[ $nsbegood -eq 999 ]]
          then
            nsbegood=$j
          fi
      
          'COMPARE_NUMBERS' $imgmax '>' $ssglobalmaximum; rslt=$?
          if [[ $rslt -eq 1 && $j -gt $nsbegood ]]
          then
            ssglobalmaximum=$imgmax
            if [[ ${ssglobalmaximum:0:1} == "." ]]; then ssglobalmaximum='0'$ssglobalmaximum; fi
            sslowerlimit=$(echo "scale=20; $ssglobalmaximum*$ffaintestscale" | bc); chk_rc
            if [[ ${sslowerlimit:0:1} == "." ]]; then sslowerlimit='0'$sslowerlimit; fi
          fi
        
          for (( try=1; try <= $trymax; try++ ))
          do
            tryp1=$(( try + 1 ))
      
            'ITERATE_CUT-OFFS' $i $j $sscimagej $nsigmavar ${imageomask[i]} $firstsig; rciterate=$?
      
            if [[ $rciterate == "0" || $rciterate == "222" || $rciterate == "200" || $toofewbgpixels -gt 0 ]]
            then 

# Check the return code to see whether there was no convergence at all in the above iterations.            
            
              if [[ $rciterate == "222" || $rciterate == "200" || $toofewbgpixels -gt 0 ]]
              then 

# Determine the maximum intensity in the single-scale image.

                $path'/imgstat' savein -nomed $sscimagej ${imageomask[i]} $verb; chk_rc
         
                read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
                if [[ ${min:0:1} == "*" || ${max:0:1} == "*" || ${sig:0:1} == "*" ]]
                then echo; echo ' '$script': '$fun': ERROR:'
                  echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                  echo '  Bad results from IMGSTAT (7): '$min $max $sig
                  echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                  echo; fun=$funo; return 99
                else \rm '.+imgstat2' 2>&1; chk_rc
                fi
         
                if [[ $toofewbgpixels -gt 0 ]]
                then
                  break
                fi
              fi
            
              $path'/modfits' minimum $sigmas y $sscimagej -o $sscimagej'.an' $verb; chk_rc
         
              $path'/modfits' layer $sigmas $sscimagej -o $sscimagej'.nn' $verb; chk_rc
         
              $path'/operate' $sscimagej - $sscimagej'.nn' -o $sscimagej'.it.re' $verb; chk_rc
         
              'CREATE_MASKS' $sigmas $sscimagej'.an' $sscimagej'.mso'; chk_rc
              'CREATE_BG_MASKS' $sscimagej'.mso' $sscimagej'.mbg' ${imageomask[i]}; chk_rc
         
# Determine higher-order statistical moments in the residuals image.

              $path'/imgstat' savein -nomed $sscimagej'.it.re' $sscimagej'.mbg' $verb; chk_rc
          
              read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc

              'CHECK_IMGSTAT' $min $max '' $script $fun $funo '11'

              \rm $sscimagej'.nn.fits' 2>&1; chk_rc
              \rm $sscimagej'.it.re.fits' 2>&1; chk_rc
              \rm $sscimagej'.mbg.fits' 2>&1; chk_rc
          
              if [[ $try -eq 1 ]]
              then 
                skewinitialj=$skew
                kurtinitialj=$kurt
              fi
          
              'COMPARE_NUMBERS' $kurt '>' $kurtinitialj; rslt=$?
              if [[ $rslt -eq 1 ]]
              then 
                echo >> $logit; echo ' INFO: KURTOSIS suspiciously increases, resetting NSIGMACUTMIN...' >> $logit
                nsigmacutfloor=$nsigmavar
                nsigmacutmin=$nsigmacutfloor
                break
              fi
                
              nsigmacutmin=$nsigmacutfloor
          
              echo >> $logit
              echo '     attempt:' $try ' skewness:' ${skew:0:9} ' skewmax'$i':' ${skewmax[i]:0:9} \
                   ' kurtosis:' ${kurt:0:9} ' kurtmax'$i':' ${kurtmax[i]:0:9} ' nsigmacutmin:' ${nsigmacutmin:0:9} >> $logit
              echo '                 skewinitialjm1:' ${skewinitialjm1:0:9} \
                   ' kurtinitialjm1:' ${kurtinitialjm1:0:9} ' ssglobalmax:' ${ssglobalmaximum:0:9} \
                   ' imgmax:' ${imgmax:0:9} >> $logit
          
              'COMPARE_NUMBERS' $nsigmavar '<' $nsigmacutmin; rslt=$?
              if [[ $rslt -eq 1 ]]
              then 
                echo >> $logit; echo ' INFO: NSIGMAVAR decreased below NSIGMACUTMIN, breaking out...' >> $logit
                break
              fi
              
# Implementation of my formulas for (empirical) automatic definition of SKEWMAX and KURTMAX for each wavelength.

              if [[ $j -eq $nsbegood ]]
              then 
                echo >> $logit; echo ' image:' $sscimagej'.it.re' ' mask:' $sscimagej'.mbg' >> $logit
                echo ' min:' ${min:0:11} ' max:' ${max:0:11} ' mea:' ${mea:0:11} ' med:' ${med:0:11} ' stde:' ${sig:0:11} \
                     ' skew:' ${skew:0:11} ' kurt:' ${kurt:0:11} >> $logit
          
                $path'/imgstat' savein -nomed $sscimagej'.an' $sscimagej'.mso' $verb; chk_rc
          
                read min1 max1 mea1 med1 totsum1 sig1 skew1 kurt1 edgemean1 < '.+imgstat2'; chk_rc

                'CHECK_IMGSTAT' $min1 $max1 '' $script $fun $funo '12'

                echo >> $logit; echo ' image:' $sscimagej'.an' ' mask:' $sscimagej'.mso' >> $logit
                echo ' min:' ${min1:0:11} ' max:' ${max1:0:11} ' mea:' ${mea1:0:11} ' med:' ${med1:0:11} ' stde:' ${sig1:0:11} \
                     ' skew:' ${skew1:0:11} ' kurt:' ${kurt1:0:11} >> $logit
          
                $path'/imgstat' savein -nomed $sscimagej $sscimagej $verb; chk_rc
          
                read min2 max2 mea2 med2 totsum2 sig2 skew2 kurt2 edgemean2 < '.+imgstat2'; chk_rc

                'CHECK_IMGSTAT' $min2 $max2 '' $script $fun $funo '13'

                echo >> $logit; echo ' image:' $sscimagej ' mask:' $sscimagej >> $logit
                echo ' min:' ${min2:0:11} ' max:' ${max2:0:11} ' mea:' ${mea2:0:11} ' med:' ${med2:0:11} ' stde:' ${sig2:0:11} \
                     ' skew:' ${skew2:0:11} ' kurt:' ${kurt2:0:11} >> $logit 
          
                $path'/imgstat' savein -nomed $sscimagej ${imageomask[i]} $verb; chk_rc
          
                read min3 max3 mea3 med3 totsum3 sig3 skew3 kurt3 edgemean2 < '.+imgstat2'; chk_rc

                'CHECK_IMGSTAT' $min3 $max3 '' $script $fun $funo '14'

                echo >> $logit; echo ' image:' $sscimagej ' mask:' ${imageomask[i]} >> $logit
                echo ' min:' ${min3:0:11} ' max:' ${max3:0:11} ' mea:' ${mea3:0:11} ' med:' ${med3:0:11} ' stde:' ${sig3:0:11} \
                     ' skew:' ${skew3:0:11} ' kurt:' ${kurt3:0:11} >> $logit 
          
                onesigma=$(echo "scale=20; $sigmas/$nsigmavar" | bc); chk_rc
          
                echo >> $logit; echo $(echo "scale=20; $sig3/$onesigma-0.6" | bc -l) >> $logit
                echo >> $logit; echo $(echo "scale=20; $mea2/$onesigma" | bc -l) >> $logit
                echo >> $logit; echo $(echo "scale=20; $mea1/$sigmas" | bc -l) >> $logit
          
                if [[ ${skewmax[i]} == "0" || ${skewmax[i]} == "0.0" || ${skewmax[i]} == "0.00" ]]
                then
                  skewmax[i]=$(echo "scale=20; 2.14*l($imgmax/$onesigma+220)-11.3" | bc -l); chk_rc
                  if [[ ${skewmax[i]:0:1} == "." ]]; then skewmax[i]='0'${skewmax[i]}; fi
                  'COMPARE_NUMBERS' ${skewmax[i]} '<' $skewmaxfloor; rslt=$?
                  if [[ $rslt -eq 1 ]]; then skewmax[i]=$skewmaxfloor; fi
                fi
                if [[ ${kurtmax[i]} == "0" || ${kurtmax[i]} == "0.0" || ${kurtmax[i]} == "0.00" ]]
                then
                  kurtmax[i]=$(echo "scale=20; 2.14*l($imgmax/$onesigma+220)-11.3" | bc -l); chk_rc
                  if [[ ${kurtmax[i]:0:1} == "." ]]; then kurtmax[i]='0'${kurtmax[i]}; fi
                  'COMPARE_NUMBERS' ${kurtmax[i]} '<' $kurtmaxfloor; rslt=$?
                  if [[ $rslt -eq 1 ]]; then kurtmax[i]=$kurtmaxfloor; fi
                fi
                nsigmavaro=$nsigmavar
                echo >> $logit; echo ' INFO: This is the first scale, ignoring controls, breaking out...' >> $logit
                break
              fi
              
              \rm $sscimagej'.an.fits' 2>&1; chk_rc; \rm $sscimagej'.mso.fits' 2>&1; chk_rc
            
# Check values of skewness and kurtosis and if they are too large, cut down nsigmavar.

              if [[ ${skew:0:1} == "-" ]]
              then
                'COMPARE_NUMBERS' $skew '<' -${skewmax[i]}; rsltskew1=$?
              else
                'COMPARE_NUMBERS' $skew '>' ${skewmax[i]}; rsltskew1=$?
              fi
              'COMPARE_NUMBERS' $kurt '>' ${kurtmax[i]}; rsltkurt1=$?
             
              if [[ $rsltskew1 -eq 1 || $rsltkurt1 -eq 1 ]]
              then 
                if [[ $verb != "-verb0" ]]
                then echo; echo ' INFO: SKEWNESS or KURTOSIS too large, reducing NSIGMAVAR, trying again...'
                fi
                echo >> $logit; echo ' INFO: SKEWNESS or KURTOSIS too large, reducing NSIGMAVAR, trying again...' >> $logit
                skewkurtstat='toolarge'
                nsigmavaro=$nsigmavar
                nsigmavar=$(echo "scale=20; $nsigmavar/$ftune" | bc); chk_rc
                if [[ ${nsigmavar:0:1} == "." ]]; then nsigmavar='0'$nsigmavar; fi
              else
                skewkurtstat='normal'
              fi
              
              'COMPARE_NUMBERS' $nsigmavar '<' $nsigmacutmin; rslt=$?
              if [[ $rslt -eq 1 ]]; then nsigmavar=$nsigmacutmin; fi

# Break out of the iterations loop if nsigma has reached its low limit at previous iteration.

              if [[ $rsltnslow -eq 1 ]]
              then 
                echo >> $logit; echo ' INFO: NSIGMAVAR has reached a lower limit at previous iteration, breaking out...' >> $logit
                break
              fi

# Check if skewness and kurtosis have decreased below the maxima allowed and if so, exit the loop of iterations.
                             
              if [[ $skewkurtstat == 'normal' ]]
              then 
                'COMPARE_NUMBERS' $ftune '=' $ftunemin; rslt=$?
                if [[ $rslt -eq 1 || $try -eq 1 ]]
                then 
                  echo >> $logit; echo ' INFO: SKEWNESS & KURTOSIS decreased below the maxima allowed, breaking out...' >> $logit
                  break
                else
                  ftune=$ftunemin
                  nsigmavar=$nsigmavaro
                  echo >> $logit; echo ' INFO: (1) FTUNE set to minimum; trying to fine-tune the cut-off...' >> $logit
                fi
              fi

# Enter at the 1st iteration. If kurtosis at 1st try is lower than that at the previous scale, we should not iterate over nsigmavar.
            
              if [[ $try -eq 1 ]]
              then 
                'COMPARE_NUMBERS' $kurt '<' $kurtinitialjm1; rslt=$?
##                if [[ $rslt -eq 1 && $rsltkurt1 -eq 0 && $rsltskew -eq 1 ]]
                if [[ $rslt -eq 1 && $skewkurtstat == 'normal' ]]
                then 
                  'COMPARE_NUMBERS' $ftune '>' $ftunemin; rslt1=$?
                  'COMPARE_NUMBERS' $nsigmavar '<' $nsigmavaro; rslt2=$?
                  if [[ $rslt1 -eq 1 && $rslt2 -eq 1 ]]
                  then 
                    ftune=$ftunemin
                    nsigmavar=$nsigmavaro
                    echo >> $logit; echo ' INFO: (2) FTUNE set to minimum; trying to fine-tune the cut-off...' >> $logit
                  else  
###                    skewmax=$skewinitialjm1
                    echo >> $logit; echo ' INFO: KURTOSIS at first try is lower than at the previous scale, breaking out...' >> $logit
                    break
                  fi
                else
                  nsigmavarinitial=$nsigmavar
         
                  'COMPARE_NUMBERS' $nsigmavar '=' $nsigmacutmin; rslt=$?
                  if [[ $rslt -eq 1 ]]
                  then 
                    echo >> $logit; echo ' INFO: NSIGMAVAR reached its minimum allowed, breaking out...' >> $logit
                    break
                  fi
                fi
              fi

# Attempt to decrease current variable nsigma for cut-offs to lower the skewness below maximum allowed.

              if [[ $tryp1 -lt $trymax ]]
              then 
                if [[ $skewkurtstat == 'normal' ]]
                then
                  nsigmavaro=$nsigmavar
                  nsigmavar=$(echo "scale=20; $nsigmavar/$ftune" | bc); chk_rc
                  if [[ ${nsigmavar:0:1} == "." ]]; then nsigmavar='0'$nsigmavar; fi
                fi
                
                'COMPARE_NUMBERS' $nsigmavar '<=' $nsigmacutmin; rsltnslow=$?
                if [[ $rsltnslow -eq 1 ]]
                then
                  nsigmavar=$nsigmacutmin
                fi
##              else 
##                nsigmavar=$nsigmavarinitial
              fi 
            fi
      
            if [[ "$rciterate" == "111" ]]
            then
              if [[ $try -eq $trymax &&  $verb != "-verb0" ]]
              then echo; echo ' '$script': '$funn': ERROR:'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo ' INFO: Giving up iterating after '$try' retries'
                echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                echo; fun=$funo; return 99
              fi
              nsigmavar=$(echo "scale=20; 1.1*$nsigmavar" | bc); chk_rc
              if [[ $verb != "-verb0" ]]
              then
                echo ' '$script': '$funn': Retrying with nsigmacut='$nsigmavar
              fi
            fi
          done
      
          skewinitialjm1=$skewinitialj
          kurtinitialjm1=$kurtinitialj
          
          if [[ $rciterate != "200" && $toofewbgpixels -eq 0 ]]
          then \rm $sscimagej'.msk.fits' 2>&1; chk_rc; \rm $sscimagej'.msks.fits' 2>&1; chk_rc
          fi
      
          'COMPARE_NUMBERS' $nsigmavar '!=' '0'; rslt=$?
          if [[ $rslt -eq 1 ]]
          then 
            thresh1=$(echo "scale=20; ($nsigmacutss/$nsigmavar)*$sigmas" | bc); chk_rc
            thresh=$sigmas
          else 
            thresh1=$(echo "scale=20; $imgmax*0.00001" | bc); chk_rc
            thresh=$thresh1
          fi
          if [[ ${thresh:0:1} == "." ]]; then thresh='0'$thresh; fi
      
          thresho=''
        else
          if [[ ${enforcedhresh[i]} == '' ]]
          then
            skewfact='0'
            if [[ $thresho == "" ]]; then thresho=$threshold; echo >> $logit; fi
          fi
          if [[ $toofewbgpixels -eq 0 ]]
          then 
            thresh=$threshold
          else
            thresh=$(echo "scale=20; $threshold/$sfactor" | bc); chk_rc
          fi
          if [[ ${thresh:0:1} == "." ]]; then thresh='0'$thresh; fi
        fi

        if [[ $thresh == '' ]]
        then echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Abnormal condition: cut-off is empty: thresh = '\'$thresh\'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: It this happens after a restart of cleaning from an intermediate scale,'
          echo '       you probably have to restart with one of the previous smaller scales;'
          echo '       look in the file '\''+log.GETSOURCES.iter'\'' to find the scale.'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; fun=$funo; return 99
        fi
  
        if [[ $toofewbgpixels -eq 0 ]]
        then 
          thresh=$(echo "scale=20; $cleantuning*$thresh" | bc); chk_rc
          if [[ ${thresh:0:1} == "." ]]; then thresh='0'$thresh; fi
        fi
        threshold=$thresh
        
        onesigma=$(echo "scale=20; $thresh/$nsigmavar" | bc); chk_rc
        if [[ ${onesigma:0:1} == "." ]]; then onesigma='0'$onesigma; fi
  
# Create image above noise (above the threshold).

        'COMPARE_NUMBERS' $thresh '>' '100000000'; rcthnogood=$?
        if [[ $rcthnogood -eq 1 ]]
        then
          $path'/modfits' minimum 0 y $sscimagej -o $sscimagej'.an' $verb; chk_rc
        else
          $path'/modfits' minimum $thresh y $sscimagej -o $sscimagej'.an' $verb; chk_rc
        fi

# Determine maximum intensity in the single-scale image.

        $path'/imgstat' savein -nomed $sscimagej'.an' ${imageomask[i]} $verb; chk_rc
        read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
        'CHECK_IMGSTAT' $min $max '' $script $fun $funo '15'
        maxallowed=$(echo "scale=20; $max/1.000001" | bc); chk_rc

# Check if the iterated threshold happened to be higher than the maximum allowed threshold.

        'COMPARE_NUMBERS' $thresh '>=' $maxallowed; rcthreshmax=$?
        if [[ $rcthreshmax -eq 0 && $j -ge $nsbegood ]]
        then foundgoodscales='yes'
        fi

# Do the following only if the threshold is lower than the maximum value in the image, i.e. if the mask image is not empty.

###        if [[ $rcthreshmax -eq 1 || $j -gt ${lastgoodscale[i]} || $j -gt ${lastbrightscale[i]} ]]
   
        if [[ $j -gt ${lastgoodscale[i]} || $j -gt ${lastbrightscale[i]} ]]
        then
          if [[ $j -gt ${lastgoodscale[i]} ]]
          then  
            if [[ -e $sscimagej'.an.fits' ]]; then \rm $sscimagej'.an.fits' 2>&1; chk_rc; fi
          fi
          
          if [[ $foundgoodscales == 'yes' ]]; then echo >> $logit; fi
          
          echo ' scale:' $j ' cut-off:' ${thresh:0:11} ' bratio:' ${beamsratioj:0:6} \
               ' ssglobalmax:' ${ssglobalmaximum:0:9} ' imgmax:' ${imgmax:0:9} >> $logit
        else

# Create "no-noise" images.
      
          $path'/modfits' layer $thresh $sscimagej -o $sscimagej'.nn' $verb; chk_rc

# Single-scale residuals image.

          $path'/operate' $sscimagej - $sscimagej'.nn' -o $sscimagej'.re' $verb; chk_rc

# Reconstruct single-scale filaments and accumulate them.

          if [[ $filaments == "yes" ]]
          then
            xsigma[j]=$(echo "scale=20; $fdp*$onesigma" | bc); chk_rc
            xsigma0[j]=$(echo "scale=20; (1/10)*${xsigma[j]}" | bc); chk_rc
            xsigma00[j]=$(echo "scale=20; (1/100)*${xsigma[j]}" | bc); chk_rc
            if [[ ${xsigma[j]:0:1} == "." ]]; then xsigma[j]='0'${xsigma[j]}; fi
            if [[ ${xsigma0[j]:0:1} == "." ]]; then xsigma0[j]='0'${xsigma0[j]}; fi
            if [[ ${xsigma00[j]:0:1} == "." ]]; then xsigma00[j]='0'${xsigma00[j]}; fi
            sscimagejn=$sscimagej'.n'

# Check whether filaments exist at this scale.

            $path'/modfits' minimum ${xsigma[j]} y $sscimagej   -o $sscimagejfm $verb; chk_rc
            $path'/modfits' maximum ${xsigma[j]} n $sscimagejfm -o $sscimagejfm $verb; chk_rc
            $path'/modfits' divide  ${xsigma[j]}   $sscimagejfm -o $sscimagejfm $verb; chk_rc
            $path'/modfits' clean4 ${cleanpix[j]} $ffi $sscimagejfm -o $sscimagejfm $verb; chk_rc

            $path'/operate' ${imagefm[i]} + $sscimagejfm -o ${imagefm[i]} $verb; chk_rc

            if [[ $filamentsfound == 'no' ]]
            then 
              $path'/imgstat' savein -nomed $sscimagejfm ${imageomask[i]} $verb; chk_rc
              read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
              'CHECK_IMGSTAT' $min $max '' $script $fun $funo '16'
              'COMPARE_NUMBERS' $max '>' $min; rcpositivesfound=$?
              if [[ $rcpositivesfound -eq 1 ]]
              then filamentsfound='yes'
              fi
            fi

            if [[ $filamentsfound == 'yes' ]]
            then 
              $path'/operate' ${imagefx[i]} + $sscimagejfm -o ${imagefx[i]}'.m' $verb; chk_rc
              $path'/modfits' maximum 1 n ${imagefx[i]}'.m' -o ${imagefx[i]}'.m' $verb; chk_rc
              $path'/operate' ${imagefx[i]}'.m' x $sscimagej -o $sscimagejfp $verb; chk_rc
              $path'/modfits' minimum ${xsigma[j]} y $sscimagejfp -o $sscimagejfp $verb; chk_rc
              $path'/modfits' clean4 ${clpixpos[j]} $ffi $sscimagejfp -o $sscimagejfp $verb; chk_rc

              $path'/imgstat' savein -nomed $sscimagejfp ${imageomask[i]} $verb; chk_rc
              read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
              'CHECK_IMGSTAT' $min $max '' $script $fun $funo '17'
              'COMPARE_NUMBERS' $max '>' $min; rcfilamentsfine=$?
              
# Reconstruct single-scale filaments free of sources and isotropic backrounds.

              if [[ $rcfilamentsfine -eq 1 ]]
              then
                $path'/modfits' negate $sscimagej -o $sscimagejn $verb; chk_rc
                $path'/modfits' minimum ${xsigma[j]} y $sscimagejn -o $sscimagejfn $verb; chk_rc
                $path'/modfits' clean4 ${clpixneg[j]} $ffi $sscimagejfn -o $sscimagejfn $verb; chk_rc

                $path'/modfits' recon4 ${cleanrec[j]} ${xsigma[j]} $sscimagejfp -o $sscimagejfp $verb; chk_rc
                $path'/modfits' recon4 ${cleanrec[j]} ${xsigma[j]} $sscimagejfn -o $sscimagejfn $verb; chk_rc

# Additional smoothing of the cleaned positives to reduce jumps to zero below XSIGMA.

                $path'/expanda' 1 $sscimagejfp ${imageomask[i]} -o $sscimagejfp $verb; chk_rc
                $path'/modfits' expand  ${addpix0[j]} $sscimagejfp -o $sscimagejfp $verb; chk_rc
                $path'/fftconv' ${csbeam0[j]} 0       $sscimagejfp -o $sscimagejfp $verb; chk_rc
                $path'/modfits' border -${addpix0[j]} $sscimagejfp -o $sscimagejfp $verb; chk_rc
                $path'/modfits' minimum ${xsigma00[j]} y $sscimagejfp -o $sscimagejfp $verb; chk_rc

# Additional smoothing of the cleaned negatives to reduce jumps to zero below XSIGMA.

                $path'/expanda' 1 $sscimagejfn ${imageomask[i]} -o $sscimagejfn $verb; chk_rc
                $path'/modfits' expand  ${addpix0[j]} $sscimagejfn -o $sscimagejfn $verb; chk_rc
                $path'/fftconv' ${csbeam0[j]} 0       $sscimagejfn -o $sscimagejfn $verb; chk_rc
                $path'/modfits' border -${addpix0[j]} $sscimagejfn -o $sscimagejfn $verb; chk_rc
                $path'/modfits' minimum ${xsigma00[j]} y $sscimagejfn -o $sscimagejfn $verb; chk_rc

# Accumulate positives and negatives (the latter is a temporary "o" image).

                $path'/operate' ${imagefp[i]} + $sscimagejfp -o ${imagefp[i]} $verb; chk_rc
                $path'/operate' ${imagefn[i]} + $sscimagejfn -o ${imagefn[i]}'.o' $verb; chk_rc

# Difference of the accumulated positives and negatives is the full accumulated filament image (a temporary "o" image).

                $path'/operate' ${imagefp[i]} - ${imagefn[i]}'.o' -o ${imagefb[i]}'.o' $verb; chk_rc

# Remove small positive features in the accumulated filaments image (they may appear after the subtraction of negatives).

                $path'/modfits' clean4 ${clpixpos[j]} $ffi ${imagefb[i]}'.o' -o ${imagefb[i]}'.o' $verb; chk_rc

# Recompute the accumulated negatives from the positives and full filaments after the above additional cleaning.

                $path'/operate' ${imagefp[i]} - ${imagefb[i]}'.o' -o ${imagefn[i]}'.o' $verb; chk_rc

# Recompute the corresponding final single-scale images of filaments and of their negative parts.
  
                $path'/operate' ${imagefb[i]}'.o' - ${imagefb[i]} -o $sscimagejfb $verb; chk_rc
                $path'/operate' ${imagefn[i]}'.o' - ${imagefn[i]} -o $sscimagejfn $verb; chk_rc

# Final accumulation of the additionally cleaned images.

                $path'/operate' ${imagefb[i]} + $sscimagejfb -o ${imagefb[i]} $verb; chk_rc
                $path'/operate' ${imagefn[i]} + $sscimagejfn -o ${imagefn[i]} $verb; chk_rc

# Expand filament masks using convolved positive filament intensity distribution.
# Using a Moffat (p=3) kernel to make the mask expansion for power-law filaments far enough.

                $path'/modfits' maximum 1 n ${imagefm[i]} -o ${imagefm[i]}'.m' $verb; chk_rc
                $path'/operate' ${imagefm[i]}'.m' x ${imagefp[i]} -o ${imagefp[i]}'.m' $verb; chk_rc
                $path'/expanda' 1 ${imagefp[i]}'.m' ${imageomask[i]} -o $sscimagejfx $verb; chk_rc
                $path'/modfits' expand  ${addpix0[j]} $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/fftconv' ${csbeam0[j]} 3       $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/modfits' border -${addpix0[j]} $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/modfits' minimum ${xsigma0[j]} y $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/modfits' maximum ${xsigma0[j]} n $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/modfits' divide  ${xsigma0[j]}   $sscimagejfx -o $sscimagejfx $verb; chk_rc
                $path'/operate' ${imagefx[i]} + $sscimagejfx -o ${imagefx[i]} $verb; chk_rc

                \rm $sscimagejn'.fits' 2>&1; chk_rc
                filmaxsize[i]=${sbeam[j]%.*}
                sum1sigma=$(echo "scale=20; $sum1sigma+$onesigma" | bc)
              fi
            else
              rcfilamentsfine=0
            fi

            if [[ $rcfilamentsfine -eq 0 ]]
            then 
              if [[ -e $sscimagejfm'.fits' ]]; then \rm $sscimagejfm'.fits' 2>&1; chk_rc; fi
              if [[ -e $sscimagejfx'.fits' ]]; then \rm $sscimagejfx'.fits' 2>&1; chk_rc; fi
              if [[ -e $sscimagejfb'.fits' ]]; then \rm $sscimagejfb'.fits' 2>&1; chk_rc; fi
              if [[ -e $sscimagejfn'.fits' ]]; then \rm $sscimagejfn'.fits' 2>&1; chk_rc; fi
              if [[ -e $sscimagejfp'.fits' ]]; then \rm $sscimagejfp'.fits' 2>&1; chk_rc; fi
            fi
          fi

# Multiply by observational mask image to clean outside the mask.

          $path'/operate' ${imageomask[i]} x $sscimagej'.an' -o $sscimagej'.an' $verb; chk_rc
          $path'/operate' ${imageomask[i]} x $sscimagej'.nn' -o $sscimagej'.nn' $verb; chk_rc
          $path'/operate' ${imageomask[i]} x $sscimagej'.re' -o $sscimagej'.re' $verb; chk_rc
   
# Reassemble the single-scale clean images into a full clean no-noise image and a full residuals image.
      
          $path'/operate' ${image[i]}'.nn' + $sscimagej'.nn' -o ${image[i]}'.nn' $verb; chk_rc
          $path'/operate' ${image[i]}'.re' + $sscimagej'.re' -o ${image[i]}'.re' $verb; chk_rc

# Create a background mask and make sure that it is not empty.
# Determine higher-order statistical moments in the residual noise image.

          if [[ $skewfact == "0" ]]
          then
            'CREATE_MASKS' $thresh $sscimagej'.an' $sscimagej'.mbg'; chk_rc
            'CREATE_BG_MASKS' $sscimagej'.mbg' $sscimagej'.mbg' ${imageomask[i]}; chk_rc
        
            $path'/imgstat' savein -nomed $sscimagej'.re' $sscimagej'.mbg' $verb; chk_rc
    
            read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc

            'CHECK_IMGSTAT' $min $max '' $script $fun $funo '18'
    
            echo >> $logit
            echo '     attempt:' $try ' skewness:' ${skew:0:9} ' skewmax'$i':' ${skewmax[i]:0:9} \
                 ' kurtosis:' ${kurt:0:9} ' kurtmax'$i':' ${kurtmax[i]:0:9} >> $logit
            echo '                          ' \
                 ' lastbright:' ${lastbrightscale[i]:0:6} ' ssglobalmax:' ${ssglobalmaximum:0:9} ' imgmax:' ${imgmax:0:9} \
                 >> $logit
            echo '                          ' \
                 ' effbeams:' ${effbeams[j]:0:9} ' cleanpix:' ${cleanpix[j]} ' effbmrec:' $effbmrec ' clpixbeg:' $clpixbeg \
                 ' clpixend:' $clpixend ' cleanrec:' ${cleanrec[j]} ' clpixpos:' ${clpixpos[j]} >> $logit
    
            \rm $sscimagej'.mbg.fits' 2>&1; chk_rc
          fi
          
          echo >> $logit
          echo ' scale:' $j ' cut-off:' ${thresh:0:11} ' bratio:' ${beamsratioj:0:6} \
               ' lastgood:' ${lastgoodscale[i]:0:6} ' lastbright:' ${lastbrightscale[i]:0:6} \
               ' ssglobalmax:' ${ssglobalmaximum:0:9} ' imgmax:' ${imgmax:0:9} >> $logit
          echo '         ' \
               ' effbeams:' ${effbeams[j]:0:9} ' cleanpix:' ${cleanpix[j]} ' effbmrec:' $effbmrec ' clpixbeg:' $clpixbeg \
               ' clpixend:' $clpixend ' cleanrec:' ${cleanrec[j]} ' clpixpos:' ${clpixpos[j]} >> $logit
    
          usmimagejm1=$usmimagej
        fi
    
###        'COMPARE_NUMBERS' $imgmax '<' $sslowerlimit; rslt=$?
        rslt=0
    
        if [[ ($rslt -eq 1 || ($foundgoodscales == 'yes' && ${lastgoodscale[i]} -lt 999)) && ${lastbrightscale[i]} -eq 999 ]]
        then
          if [[ $foundgoodscales == 'yes' && ${lastgoodscale[i]} -lt 999 ]]
          then lastbrightscale[i]=${lastgoodscale[i]}
          else lastbrightscale[i]=$j
          fi
          echo >> $logit; echo ' INFO: THE LAST BRIGHT SCALE FOUND at scale '${lastbrightscale[i]}':' \
                               $imgmax $sslowerlimit ${lastgoodscale[i]} $foundgoodscales >> $logit
        fi
    
        echo \'${dirmono[i]}'/'$sscimagej'.an.fits'\' $onesigma $nsigmavar $thresh $imgmax \''restart-data:'\' \
               ${lastgoodscale[i]} ${lastbrightscale[i]} $foundgoodscales $threshold $skewinitialjm1 $kurtinitialjm1 \
               $skewinitialj $kurtinitialj $ssglobalmaximum $sslowerlimit $nsbegood $rsltnslow $nsigmacutfloor $nsigmacutmin \
               $nsigmavaro ${skewmax[i]} ${kurtmax[i]} $toofewbgpixels $skewkurtstat >> ${filecleaning[i]}
        
      else  #<-- when j < nsc1, skip here (when restarting from an intermediate scale)

# Accumulated images of filaments.

        if [[ $filaments == "yes" ]]
        then
          if [[ -e $sscimagejfb'.fits' ]]
          then
            filamentsfound='yes'
            filmaxsize[i]=${sbeam[j]%.*}
            sum1sigma=$(echo "scale=20; $sum1sigma+${onesigxo[j]}" | bc)

            $path'/operate' ${imagefm[i]} + $sscimagejfm -o ${imagefm[i]} $verb; chk_rc
            $path'/operate' ${imagefx[i]} + $sscimagejfx -o ${imagefx[i]} $verb; chk_rc
            $path'/operate' ${imagefb[i]} + $sscimagejfb -o ${imagefb[i]} $verb; chk_rc
            $path'/operate' ${imagefn[i]} + $sscimagejfn -o ${imagefn[i]} $verb; chk_rc  
            $path'/operate' ${imagefp[i]} + $sscimagejfp -o ${imagefp[i]} $verb; chk_rc
          else
            if [[ -e $sscimagejfm'.fits' ]]; then \rm $sscimagejfm'.fits' 2>&1; chk_rc; fi
            if [[ -e $sscimagejfx'.fits' ]]; then \rm $sscimagejfx'.fits' 2>&1; chk_rc; fi
            if [[ -e $sscimagejfb'.fits' ]]; then \rm $sscimagejfb'.fits' 2>&1; chk_rc; fi
            if [[ -e $sscimagejfn'.fits' ]]; then \rm $sscimagejfn'.fits' 2>&1; chk_rc; fi
            if [[ -e $sscimagejfp'.fits' ]]; then \rm $sscimagejfp'.fits' 2>&1; chk_rc; fi
          fi
        fi

# Reassemble the single-scale clean images into a full clean no-noise image and a full residuals image.
      
        $path'/modfits' layer ${threshxo[nsca]} $sscimagej -o $sscimagej'.nn' $verb; chk_rc
        $path'/operate' $sscimagej - $sscimagej'.nn' -o $sscimagej'.re' $verb; chk_rc
        $path'/operate' ${image[i]}'.nn' + $sscimagej'.nn' -o ${image[i]}'.nn' $verb; chk_rc
        $path'/operate' ${image[i]}'.re' + $sscimagej'.re' -o ${image[i]}'.re' $verb; chk_rc
      fi

      if [[ $savespace -ge 1 ]]
      then
        \rm $sscimagej'.nn.fits' 2>&1; chk_rc
        \rm $sscimagej'.re.fits' 2>&1; chk_rc
      fi

      if [[ $originpath != ${dirmono[i]} ]]
      then
        if [[ -e $sscimagej'.fits' ]]; then \rm $sscimagej'.fits' 2>&1; chk_rc; fi
        if [[ -e $sscimagej'.an.fits' ]]; then \mv $sscimagej'.an.fits' ${dirmono[i]} 2>&1; chk_rc; fi
        if [[ -e $sscimagej'.nn.fits' ]]; then \mv $sscimagej'.nn.fits' ${dirmono[i]} 2>&1; chk_rc; fi
        if [[ -e $sscimagej'.re.fits' ]]; then \mv $sscimagej'.re.fits' ${dirmono[i]} 2>&1; chk_rc; fi
        \cp $logit ${dirmono[i]} 2>&1; chk_rc
      fi

      if [[ -e '+stopitnow!' ]]
      then 
        \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
        echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE'; echo; exit 99
      fi
    done               

    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' 'complete' $nsbeams $nsbeg $nsbeams 79 "-"
    fi

    echo >> $logit; echo ' Sum of one-sigma values over all filamentary scales: '$sum1sigma >> $logit

    if [[ ! -e ${dirmono[i]}'/+interface' ]]; then \mkdir -p ${dirmono[i]}'/+interface' 2>&1; chk_rc; fi
    if [[ $fproima == "yes" && ! -e ${dirmono[i]}'/+filaments/+skeletons' ]]
    then \mkdir -p ${dirmono[i]}'/+filaments/+skeletons' 2>&1; chk_rc; fi

    echo ${lastbrightscale[i]} > ${image[i]}'.lastbright'
    echo ${filmaxsize[i]} > ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize'

# Finally add the largest smoothed image to the reassembled images.
# Restrict residual noise image by the observational mask image.
    
    $path'/operate' ${image[i]}'.c'${sbeam[nsbeams]}'as' + ${image[i]}'.nn' -o ${image[i]}'.nn+' $verb; chk_rc
    $path'/operate' ${image[i]}'.c'${sbeam[nsbeams]}'as' + ${image[i]}'.re' -o ${image[i]}'.re+' $verb; chk_rc
    $path'/operate' ${imageomask[i]} x ${image[i]}'.re+' -o ${image[i]}'.re+' $verb; chk_rc
    $path'/operate' $coaddedomask x ${image[i]}'.nn+' -o ${image[i]}'.nn+' $verb; chk_rc
    $path'/operate' ${imageomask[i]} x ${image[i]}'.re' -o ${image[i]}'.re' $verb; chk_rc
    $path'/operate' $coaddedomask x ${image[i]}'.nn' -o ${image[i]}'.nn' $verb; chk_rc

    if [[ $originpath != ${dirmono[i]} ]]
    then
      \cp ${image[i]}'.nn+.fits' ${dirmono[i]} 2>&1; chk_rc
      \cp ${image[i]}'.re+.fits' ${dirmono[i]} 2>&1; chk_rc
      \cp ${image[i]}'.nn.fits'  ${dirmono[i]} 2>&1; chk_rc
      \cp ${image[i]}'.re.fits'  ${dirmono[i]} 2>&1; chk_rc
      \cp ${image[i]}'.lastbright' ${dirmono[i]} 2>&1; chk_rc
    fi
    
# To properly accumulate reconstructed filaments, one needs a loop backwards, otherwise some faint 
# small-scale filaments may be "eaten" by the negative areas around bright large-scale features.

    'DEFINE_FILAMENTS_SCALES' ${beam[i]}

    detfilaments=${dirmono[i]}'/+interface/'${image[i]}'.filaments'
    detfilamentsm=${dirmono[i]}'/+interface/'${image[i]}'.filaments.masks'
    detskeletons=${dirmono[i]}'/+interface/'${image[i]}'.skeletons'
    for (( k=0; k <= $nsfils; k++ ))
    do
      detfilamentsx[k]=$detfilaments'.'${zfilscale[k]}'as'
    done
    for (( l=0; l <= $nsskel; l++ ))
    do
      detskeletonsx[l]=$detskeletons'.'${zfilscale[l]}'as'
    done
    for (( k=0; k <= $nsfils; k++ ))
    do
      if [[ ${filscale[k]} -le ${filmaxsize[i]} ]]
      then 
        \cp 'z0.fits' ${detfilamentsx[k]}'.fits' 2>&1; chk_rc
      fi
    done
    if [[ $fproima == "yes" ]]
    then
      for (( l=0; l <= $nsskel; l++ ))
      do
        if [[ ${filscale[l]} -le ${filmaxsize[i]} ]]
        then 
          \cp 'z0.fits' ${detskeletonsx[l]}'.fits' 2>&1; chk_rc
        fi
      done
    fi
    \cp 'z0.fits' $detfilaments'.fits' 2>&1; chk_rc
    \cp 'z0.fits' $detfilamentsm'.fits' 2>&1; chk_rc
    cleapix=$(echo "scale=20; 25*$skeletonpixwidth" | bc); chk_rc; cleapix=${cleapix%.*}
    xsigma00min='9999999999.99'

    for (( j=$nsbeams; j >= $nsbeg; j-- ))
    do
      if [[ $verb == "-verb0" ]]
      then 
        if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
        'PROGRESS_BAR' "$script: COMPLETING$iw" $(( nsbeams - j + nsbeg )) $nsbeg $nsbeams 79 "-"
      fi
      sbeamint=${sbeam[j]%.*}
      sscimagej=${image[i]}'.'${nscbeam[j]}
      sscimagejfb=${dirmono[i]}'/+filaments/'$sscimagej'.fb'
      sscimagejsk=${dirmono[i]}'/+filaments/+skeletons/'$sscimagej'.skeletons'
      
      if [[ -e $sscimagejfb'.fits' ]]
      then
        $path'/operate' $detfilaments + $sscimagejfb -o $detfilaments $verb; chk_rc
        $path'/modfits' minimum ${xsigma00[j]} y $detfilaments -o $detfilaments $verb; chk_rc

# Accumulate images of filaments in several limited ranges of scales.

        for (( k=0; k <= $nsfils; k++ ))
        do
          if [[ $sbeamint -le ${filscale[k]} && ${filscale[k]} -le ${filmaxsize[i]} ]]
          then
            $path'/operate' ${detfilamentsx[k]} + $sscimagejfb -o ${detfilamentsx[k]} $verb; chk_rc
            $path'/modfits' minimum ${xsigma00[j]} y ${detfilamentsx[k]} -o ${detfilamentsx[k]} $verb; chk_rc
          fi
        done

# Derive single-scale skeletons from an additionally smoothed image.

        if [[ $fproima == "yes" ]]
        then
          for (( l=0; l <= $nsskel; l++ ))
          do
            lm1=$(( l - 1 ))
            if [[ l -eq 0 ]]
            then filscal0='0'            
            else filscal0=${filscale[lm1]}
            fi
            zl=${zfilscale[l]}'as'
            if [[ $sbeamint -gt $filscal0 && $sbeamint -le ${filscale[l]} && ${filscale[l]} -le ${filmaxsize[i]} ]]
            then
              cosbeam=$(echo "scale=20; 1*${sbeam[j]}" | bc); chk_rc
              addpixsb=$(echo "scale=20; 1.5*$cosbeam/$dxas" | bc); chk_rc
              
              $path'/expanda' 1 $sscimagejfb ${imageomask[i]} -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' minimum ${xsigma0[j]} y $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' expand  $addpixsb $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/fftconv' $cosbeam 0 $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' border -$addpixsb $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' minimum ${xsigma0[j]} y $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' skeleton $skeletonpixwidth $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/operate' ${imageomask[i]} x $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/modfits' clean8 $cleapix 0 $sscimagejsk'.'$zl -o $sscimagejsk'.'$zl $verb; chk_rc
              $path'/operate' ${detskeletonsx[l]} + $sscimagejsk'.'$zl -o ${detskeletonsx[l]} $verb; chk_rc
            fi
          done
        fi

        'COMPARE_NUMBERS' ${xsigma00[j]} '<' $xsigma00min; rslt=$?
        if [[ $rslt -eq 1 ]]; then xsigma00min=${xsigma00[j]}; fi
      fi

# Some cleaning (removal of irrelevant single-scale images) would not hurt.

      if [[ $j -gt ${lastgoodscale[i]} && $foundgoodscales == 'yes' && $savespace -eq 2 ]]
      then
        if [[ -e $sscimagej'.an.fits' ]]; then \rm $sscimagej'.an.fits' 2>&1; chk_rc; fi
        if [[ -e $sscimagej'.nn.fits' ]]; then \rm $sscimagej'.nn.fits' 2>&1; chk_rc; fi
        if [[ -e $sscimagej'.re.fits' ]]; then \rm $sscimagej'.re.fits' 2>&1; chk_rc; fi
      fi
    done

    $path'/modfits' minimum $xsigma00min y $detfilaments  -o $detfilamentsm $verb; chk_rc
    $path'/modfits' maximum $xsigma00min n $detfilamentsm -o $detfilamentsm $verb; chk_rc
    $path'/modfits' divide  $xsigma00min   $detfilamentsm -o $detfilamentsm $verb; chk_rc
    $path'/operate' ${imageomask[i]} x     $detfilamentsm -o $detfilamentsm $verb; chk_rc

# Finalize filaments and subtract their contribution from the detection and measurement images.

    if [[ $filaments == "yes" ]]
    then
      if [[ ! -e ${dirmono[i]}'/+interface' ]]; then \mkdir -p ${dirmono[i]}'/+interface' 2>&1; chk_rc; fi
      if [[ $fproima == "yes" && ! -e ${dirmono[i]}'/+filaments/+profiles' ]]
      then \mkdir -p ${dirmono[i]}'/+filaments/+profiles' 2>&1; chk_rc; fi

# Note that the *initial* detected and observed filaments are the same (no flattening done yet).

      inifilaments=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.filaments'
      obsfilaments=${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments'
      for (( k=0; k <= $nsfils; k++ ))
      do
        inifilamentsx[k]=$inifilaments'.'${zfilscale[k]}'as'
        obsfilamentsx[k]=$obsfilaments'.'${zfilscale[k]}'as'
      done
      inifilamentsm=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.filaments.masks'
      inifilamentsfb=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.fb'
      inifilamentsfn=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.fn'
      inifilamentsfp=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.fp'
      inifilamentsfm=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.fm'
      iniskeletons=$pathinitial'/'${dirmon[i]}'/+interface/'${image[i]}'.skeletons'
      obsfilamentsfb=${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.fb'
      obsfilamentsfp=${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.fp'
      detfilaments=${dirmono[i]}'/+interface/'${image[i]}'.filaments'
      detfilamentsm=${dirmono[i]}'/+interface/'${image[i]}'.filaments.masks'
      detfilamentsfb=${dirmono[i]}'/+interface/'${image[i]}'.fb'
      detfilamentsfn=${dirmono[i]}'/+interface/'${image[i]}'.fn'
      detfilamentsfp=${dirmono[i]}'/+interface/'${image[i]}'.fp'
      detfilamentsfm=${dirmono[i]}'/+interface/'${image[i]}'.fm'
      detskeletons=${dirmono[i]}'/+interface/'${image[i]}'.skeletons'

      \cp ${imagefb[i]}'.fits' ${dirmono[i]}'/+interface' 2>&1; chk_rc
      \cp ${imagefn[i]}'.fits' ${dirmono[i]}'/+interface' 2>&1; chk_rc
      \cp ${imagefp[i]}'.fits' ${dirmono[i]}'/+interface' 2>&1; chk_rc
      \cp ${imagefx[i]}'.fits' ${dirmono[i]}'/+interface' 2>&1; chk_rc
      \cp ${imagefm[i]}'.fits' ${dirmono[i]}'/+interface' 2>&1; chk_rc

      if [[ ${filmaxsize[i]} -ge ${filmaxsizeo[i]} ]]
      then filmaxsizefin=${filmaxsize[i]}
      else filmaxsizefin=${filmaxsizeo[i]}
      fi

      if [[ $flattening != "yes" && $flattening != "done" ]]
      then
        for (( k=0; k <= $nsfils; k++ ))
        do
          if [[ -e ${detfilamentsx[k]}'.fits' && ${filscale[k]} -le ${filmaxsize[i]} ]]
          then 
            $path'/operate' ${imageomask[i]} x ${detfilamentsx[k]} -o ${detfilamentsx[k]} $verb; chk_rc
            \cp ${detfilamentsx[k]}'.fits' ${obsfilamentsx[k]}'.fits' 2>&1; chk_rc
          fi
        done
        \cp ${image[i]}'.re.fits'  $prefix'.'${wave[i]}'.obs.re.fits'  2>&1; chk_rc
        \cp ${image[i]}'.re+.fits' $prefix'.'${wave[i]}'.obs.re+.fits' 2>&1; chk_rc
        \cp $detfilaments'.fits' $obsfilaments'.fits' 2>&1; chk_rc
        \cp $detfilaments'.fits' $detfilaments'.n.fits' 2>&1; chk_rc
      else
        flatfactorimage=${dirmono[i]}'/+flattening/'${detectionclone[i]}'.flatfactor'

        if [[ -e $inifilamentsm'.fits' ]]
        then
          \cp $detfilamentsm'.fits' $detfilamentsm'.n.fits' 2>&1; chk_rc
          $path'/operate' $inifilamentsm + $detfilamentsm'.n' -o $detfilamentsm $verb; chk_rc
          $path'/modfits' maximum 1 n $detfilamentsm -o $detfilamentsm $verb; chk_rc
        fi
        if [[ $fproima == "yes" ]]
        then
          for (( l=0; l <= $nsskel; l++ ))
          do
            zl=${zfilscale[l]}'as'
            if [[ -e $iniskeletons'.'$zl'.fits' && ${filscale[l]} -le ${filmaxsize[i]} ]]
            then
              $path'/operate' $iniskeletons'.'$zl + $detskeletons'.'$zl -o $detskeletons'.'$zl $verb; chk_rc
            fi
          done
        fi

# Original images of the new (flattened) cleaned filaments that will not be modified.

        for (( k=0; k <= $nsfils; k++ ))
        do
          if [[ ${filscale[k]} -le ${filmaxsize[i]} && -e ${detfilamentsx[k]}'.fits' ]]
          then 
            \cp ${detfilamentsx[k]}'.fits' ${detfilamentsx[k]}'.n.fits' 2>&1; chk_rc
          fi
        done
        \cp $detfilaments'.fits' $detfilaments'.n.fits' 2>&1; chk_rc

        $path'/operate' ${image[i]}'.re'  x $flatfactorimage -o $prefix'.'${wave[i]}'.obs.re'  $verb; chk_rc
        $path'/operate' ${image[i]}'.re+' x $flatfactorimage -o $prefix'.'${wave[i]}'.obs.re+' $verb; chk_rc
 
# Unflatten the filaments from the final extraction and add them with the initial filaments.

        $path'/operate' $detfilaments'.n' x $flatfactorimage -o $obsfilaments $verb; chk_rc
        $path'/operate' $inifilaments + $obsfilaments -o $obsfilaments $verb; chk_rc

# Flatten the filaments from the initial extraction and add them with those from the final extraction.

        $path'/operate' $inifilaments % $flatfactorimage -o $detfilaments $verb; chk_rc
        $path'/operate' $detfilaments + $detfilaments'.n' -o $detfilaments $verb; chk_rc

# Accumulate images of filaments in several limited ranges of scales.

        for (( k=0; k <= $nsfils; k++ ))
        do
          if [[ ${filscale[k]} -le $filmaxsizefin ]]
          then
            if [[ -e ${detfilamentsx[k]}'.n.fits' ]]
            then
              $path'/operate' ${detfilamentsx[k]}'.n' x $flatfactorimage -o ${obsfilamentsx[k]} $verb; chk_rc
            else
              \cp 'z0.fits' ${obsfilamentsx[k]}'.fits' 2>&1; chk_rc
            fi
            if [[ -e ${inifilamentsx[k]}'.fits' ]]
            then
              $path'/operate' ${inifilamentsx[k]} + ${obsfilamentsx[k]} -o ${obsfilamentsx[k]} $verb; chk_rc
              $path'/operate' ${imageomask[i]} x ${obsfilamentsx[k]} -o ${obsfilamentsx[k]} $verb; chk_rc
            fi
            if [[ -e ${inifilamentsx[k]}'.fits' ]]
            then
              $path'/operate' ${inifilamentsx[k]} % $flatfactorimage -o ${detfilamentsx[k]} $verb; chk_rc
            else
              \cp 'z0.fits' ${detfilamentsx[k]}'.fits' 2>&1; chk_rc
            fi
            if [[ -e ${detfilamentsx[k]}'.n.fits' ]]
            then
              $path'/operate' ${detfilamentsx[k]} + ${detfilamentsx[k]}'.n' -o ${detfilamentsx[k]} $verb; chk_rc
              $path'/operate' ${imageomask[i]} x ${detfilamentsx[k]} -o ${detfilamentsx[k]} $verb; chk_rc
            fi
          fi
        done
      fi

# Estimate the largest-scale image that is always ignored in the reconstructed filament images.
# Convolve incrementally to save time and memory (especially when 'sfactor' is close to 1).

      $path'/expanda' 1 $detfilaments'.n' ${imageomask[i]} -o $detfilaments'.n.con' $verb; chk_rc
      $path'/expanda' 1 $obsfilaments ${imageomask[i]} -o $obsfilaments'.con' $verb; chk_rc
                                                                                           
      for (( j=$nsbeg; j <= $nsbeams; j++ ))
      do
        if [[ $verb == "-verb0" ]]
        then 
          if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
          'PROGRESS_BAR' "$script: COMPLETING$iw" $j $nsbeg $nsbeams 79 "~"
        fi
        jm1=$(( j - 1 ))
        if [[ $j -eq $nsbeg ]]
        then addbeamcon=${sbeam[j]}
        else addbeamcon=$(echo "scale=20; sqrt(${sbeam[j]}^2-${sbeam[jm1]}^2)" | bc); chk_rc
        fi
        addpixcon=$(echo "scale=20; 1.5*$addbeamcon/$dxas" | bc); chk_rc

        'CONVOLVE_IMAGE' expand border $addpixcon $addbeamcon $detfilaments'.n.con' $detfilaments'.n.con'; chk_rc
        'CONVOLVE_IMAGE' expand border $addpixcon $addbeamcon $obsfilaments'.con' $obsfilaments'.con'; chk_rc
      done                               

      \mv $detfilaments'.n.con.fits' $detfilaments'.n.c'${sbeam[nsbeams]}'as.fits' 2>&1; chk_rc
      \mv $obsfilaments'.con.fits' $obsfilaments'.c'${sbeam[nsbeams]}'as.fits' 2>&1; chk_rc

# Add the largest-scale image to the clean filaments to ensure correct intensity distribution on largest scales.

      $path'/operate' $detfilaments'.n' + $detfilaments'.n.c'${sbeam[nsbeams]}'as' -o $detfilaments'.n+' $verb; chk_rc
      $path'/operate' $detfilamentsm x $detfilaments'.n+' -o $detfilaments'.n+.m' $verb; chk_rc

      $path'/operate' $obsfilaments + $obsfilaments'.c'${sbeam[nsbeams]}'as' -o $obsfilaments'+' $verb; chk_rc
      $path'/operate' $detfilamentsm x $obsfilaments'+' -o $obsfilaments'+.m' $verb; chk_rc

# Subtract the sum of the filaments images from the original observed (measurement) image.

      $path'/operate' ${detectionclone[i]} - $detfilaments'.n+' -o ${detectionclone[i]}'.fs+' $verb; chk_rc
      $path'/operate' ${detectionclone[i]} - $detfilaments'.n' -o ${detectionclone[i]}'.fs' $verb; chk_rc

      $path'/operate' ${measuremtclone[i]} - $obsfilaments'+' -o ${measuremtclone[i]}'.fs+' $verb; chk_rc
      $path'/operate' ${measuremtclone[i]} - $obsfilaments -o ${measuremtclone[i]}'.fs' $verb; chk_rc

      $path'/operate' ${imageomask[i]} x $obsfilaments -o $obsfilaments $verb; chk_rc
      $path'/operate' ${imageomask[i]} x ${detectionclone[i]}'.fs+' -o ${detectionclone[i]}'.fs+' $verb; chk_rc
      $path'/operate' ${imageomask[i]} x ${detectionclone[i]}'.fs'  -o ${detectionclone[i]}'.fs'  $verb; chk_rc
      $path'/operate' ${imageomask[i]} x ${measuremtclone[i]}'.fs+' -o ${measuremtclone[i]}'.fs+' $verb; chk_rc
      $path'/operate' ${imageomask[i]} x ${measuremtclone[i]}'.fs'  -o ${measuremtclone[i]}'.fs'  $verb; chk_rc

      if [[ $verb == "-verb0" ]]
      then 
        'PROGRESS_BAR' 'complete' $nsbeams $nsbeg $nsbeams 79 "-"
      fi

      if [[ $fproima == "yes" ]]
      then
        for (( l=0; l <= $nsskel; l++ ))
        do
          'VISUALIZE_SKELETONS' $detskeletons'.'${zfilscale[l]}'as' ${imageomask[i]}
        done
      fi
    else
      \cp ${detectionclone[i]}'.fits' ${detectionclone[i]}'.fs.fits'  2>&1; chk_rc
      \cp ${detectionclone[i]}'.fits' ${detectionclone[i]}'.fs+.fits' 2>&1; chk_rc
      \cp ${measuremtclone[i]}'.fits' ${measuremtclone[i]}'.fs.fits'  2>&1; chk_rc
      \cp ${measuremtclone[i]}'.fits' ${measuremtclone[i]}'.fs+.fits' 2>&1; chk_rc
    fi
  
    if [[ `echo ${dirmono[i]}'/+interface/'$prefix.*.det.f[bmnpx].fits` \
             != ${dirmono[i]}'/+interface/'$prefix'.*.det.f[bmnpx].fits' ]]
    then 
      \rm ${dirmono[i]}'/+interface/'$prefix.*.det.f[bmnpx].fits 2>&1; chk_rc
    fi
    if [[ `echo ${dirmono[i]}'/+interface/'$prefix.*.det.*.n*.fits` \
             != ${dirmono[i]}'/+interface/'$prefix'.*.det.*.n*.fits' ]]
    then 
      \rm ${dirmono[i]}'/+interface/'$prefix.*.det.*.n*.fits 2>&1; chk_rc
    fi
    if [[ $flattening == "yes" || $flattening == "done" ]]
    then
      if [[ `echo ${dirmono[i]}'/+interface/'$prefix.*.det.filaments.????as.fits` \
               != ${dirmono[i]}'/+interface/'$prefix'.*.det.filaments.????as.fits' ]]
      then 
        \rm ${dirmono[i]}'/+interface/'$prefix.*.det.filaments.????as.fits 2>&1; chk_rc
      fi
    fi
  done
  
  clean_end=`date +%s`; clean_time=$((clean_end - clean_beg))
  echo; echo ' GETSOURCES: '$clean_time' SECONDS'
  fun=$funo
} 
#___________________________________________________________________________________________________________________________________

COMBINE_OVER_WAVES ()
{                          
  local funo=$fun; fun='COMBINE_OVER_WAVES'; title=$script': => (3) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $combining == "no" ]]; then echo ' ~~~> skipping...'; fun=$funo; return 0; else echo; fi
  combine_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  local nsbeams; local nsbeg; local image; local sscimagej; local fact; local i; local j; local iw
  nprogress=0

  if [[ `echo $prefix.sw.det.??.c??????as.*.fits` != $prefix'.sw.det.??.c??????as.*.fits' ]]
  then 
    \rm $prefix'.sw.det.'??'.c'??????'as.'*'.fits' 2>&1; chk_rc
  fi
  maskscaleswavesfinalsumx=$maskscaleswavesfinalsum'.hi'
  \cp 'z0.fits' $maskscaleswavesfinalsumx'.fits' 2>&1; chk_rc

  if [[ $savespace -eq 0 ]]
  then
    imagesw=$prefix'.sw.det.an'; imageswno=$prefix'.sw.det.re'
    \cp 'z0.fits' $imagesw'.fits' 2>&1; chk_rc; \cp 'z0.fits' $imageswno'.fits' 2>&1; chk_rc
  fi
  
  lastbrightscalemax='0'; nwavescombo=0
  
  for (( j=1; j <= 99; j++ ))
  do                        
    threshmax[j]='0.0'; nsigmasmean[j]='0.0'; nsigmasmax[j]='0.0'; wavescombined[j]=''
  done
    
# Find contrast ratios for each scale and their maxima across all wavelengths.

  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ ${usewaveincombining[i]} == "yes" ]]
    then
      nwavescombo=$(( nwavescombo + 1 ))
      image=${detectionclone[i]}
 
      if [[ ! -e ${filecleaning[i]} ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
 
      nsbeg=0; nsbeams=0; sfxx=''
      {
      while read filename q1 nsigmaj cutoffj imgmax alltherest
      do
        if [[ ${filename:0:1} == '#' ]]
        then
          if [[ $alltherest != "" ]]
          then
            'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
            if [[ $sfpos -gt 0 ]]
            then
              sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
              sfactor=${alltherest:n1:22}
            fi
          fi
        else
          'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
          if [[ $wavdet -gt 0 ]]
          then
            waveixx=".${wave[i]}.det."
            length=${#waveixx}
            n1=$(( wavdet + length - 1 ))
            nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
            if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
            nscbeam[nsca]=${filename:n1:12}
            sbeam[nsca]=${nscbeam[nsca]:4:6}
            ssimagemax[nsca]=$imgmax
            nsigmas[nsca]=$nsigmaj
            cutoffs[nsca]=$cutoffj
          fi
        fi
      done
      } < ${filecleaning[i]}

      if [[ $sfxx == "" ]]
      then
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Scale factor not found in:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi

      if [[ ${nsbeg:0:1} == '0' ]]; then nsbeg=${nsbeg:1}; fi

      for (( j=$nsbeg; j <= $nsbeams; j++ ))
      do                        
        if [[ $verb == "-verb0" ]]
        then
          if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
          'PROGRESS_BAR' "$script: PREPARING$iw" $j $nsbeg $nsbeams 79 "-"
        fi
        nsigma=${nsigmas[j]}
        thresh=${cutoffs[j]}
    
        nsigmasmean[j]=$(echo "scale=20; ${nsigmasmean[j]}+$nsigma" | bc); chk_rc        
    
        'COMPARE_NUMBERS' $nsigma '>' ${nsigmasmax[j]}; rsltns=$?
        if [[ $rsltns -eq 1 ]]
        then nsigmasmax[j]=$nsigma
        fi
        
        sscimagejan=${dirmono[i]}'/'$image'.'${nscbeam[j]}'.an'
        
        if [[ -e $sscimagejan'.fits' ]]
        then
          'COMPARE_NUMBERS' $thresh '>' ${threshmax[j]}; rslt=$?
          'COMPARE_NUMBERS' $thresh '<' '9999999999.99'; rslt9=$?
          if [[ $rslt -eq 1 && $rslt9 -eq 1 ]]
          then threshmax[j]=$thresh
          fi
        fi
    
        if [[ -e '+stopitnow!' ]]
        then 
          \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
          echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE.'; echo; exit 99
        fi
      done
      
      if [[ $verb == "-verb0" ]]
      then 
        'PROGRESS_BAR' 'complete' $nsbeams $nsbeg $nsbeams 79 "-"
      fi
    
      if [[ -e ${dirmono[i]}'/'$image'.lastbright' ]]
      then read lastbrightscale[i] < ${dirmono[i]}'/'$image'.lastbright'
      else echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${dirmono[i]}'/'$image'.lastbright'\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      nsrcmaxsize=999
      for (( j=$nsbeg; j <= $nsbeams; j++ ))
      do
        scalemaxsize=$(echo "scale=20; 3.0*$srcmaxsizemax" | bc); chk_rc
        'COMPARE_NUMBERS' ${sbeam[j]} '>' $scalemaxsize; rslt=$?
        if [[ $rslt -eq 1 || $j -gt ${lastbrightscale[i]} ]]; then break; fi
        nsrcmaxsize=$j
      done
      if [[ ${lastbrightscale[i]} -gt $nsrcmaxsize ]]
      then
        lastbrightscale[i]=$nsrcmaxsize
      fi
      if [[ ${lastbrightscale[i]} -gt 0 && ${lastbrightscale[i]} -gt $lastbrightscalemax ]]
      then
        lastbrightscalemax=${lastbrightscale[i]}
      fi
      if [[ $verb != "-verb0" ]]; then echo; echo ' lastbrightscale: '${lastbrightscale[i]}; fi
    fi
  done
  
  if [[ -e $prefix'.sw.det.lastbright' ]]
  then 
    if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
    if [[ -e $subdirbackups'/'$prefix'.sw.det.lastbright' ]]
    then
      backtimestamp=`date +%y%m%d.%H%M%S`
      \mv $subdirbackups'/'$prefix'.sw.det.lastbright' $subdirbackups'/'$prefix'.sw.det.lastbright.'$backtimestamp 2>&1; chk_rc
    fi
    \cp $prefix'.sw.det.lastbright' $subdirbackups 2>&1; chk_rc
  fi

  if [[ $verb != "-verb0" ]]; then echo; echo ' lastbrightscalemax: '$lastbrightscalemax; fi
  echo $lastbrightscalemax > $prefix'.sw.det.lastbright'
  
  if [[ $lastbrightscalemax -eq 0 ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Trouble identifying the last bright scale'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  
  for (( j=1; j <= 99; j++ ))
  do                        
    if [[ ${nscbeam[j]} != '' ]]
    then
      comweightsum[j]='0.0'
      newthreshsum[j]='0.0'
      sscimagecoman[j]=$prefix'.sw.det.'${nscbeam[j]}'.an'
      sscimagecomas[j]=$prefix'.sw.det.'${nscbeam[j]}'.as'
      nsigmasmean[j]=$(echo "scale=20; ${nsigmasmean[j]}/$nwavescombo" | bc); chk_rc
  
      if [[ $j -le $lastbrightscalemax ]]
      then
        \cp 'z0.fits' ${sscimagecoman[j]}'.fits' 2>&1; chk_rc
        \cp 'z0.fits' ${sscimagecomas[j]}'.fits' 2>&1; chk_rc
        if [[ $savespace -eq 0 ]]
        then
          sscimagecomnn[j]=$prefix'.sw.det.'${nscbeam[j]}'.nn'
          sscimagecomre[j]=$prefix'.sw.det.'${nscbeam[j]}'.re'
          \cp 'z0.fits' ${sscimagecomnn[j]}'.fits' 2>&1; chk_rc
          \cp 'z0.fits' ${sscimagecomre[j]}'.fits' 2>&1; chk_rc
        fi
      fi
    fi
  done                           

# Combine single scales over all wavelengths.
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    im1=$(( i - 1 ))     
         
    if [[ ${usewaveincombining[i]} == "yes" ]]
    then
      image=${detectionclone[i]}
      echo >> $logit
    
      if [[ ! -e ${filecleaning[i]} ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
    
      nsbeg=0; nsbeams=0; sfxx=''
      {
      while read filename q1 nsigmaj cutoffj imgmax alltherest
      do
        if [[ ${filename:0:1} == '#' ]]
        then
          if [[ $alltherest != "" ]]
          then
            'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
            if [[ $sfpos -gt 0 ]]
            then
              sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
              sfactor=${alltherest:n1:22}
            fi
          fi
        else
          'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
          if [[ $wavdet -gt 0 ]]
          then
            waveixx=".${wave[i]}.det."
            length=${#waveixx}
            n1=$(( wavdet + length - 1 ))
            nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
            if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
            nscbeam[nsca]=${filename:n1:12}
            sbeam[nsca]=${nscbeam[nsca]:4:6}
            ssimagemax[nsca]=$imgmax
            nsigmas[nsca]=$nsigmaj
            cutoffs[nsca]=$cutoffj
          fi
        fi
      done
      } < ${filecleaning[i]}
      
      if [[ $sfxx == "" ]]
      then
        echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: Scale factor not found in:'
        echo '       '\'${filecleaning[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi

      if [[ ${nsbeg:0:1} == '0' ]]; then nsbeg=${nsbeg:1}; fi
    
      maskscalesfinalsumx=${maskscalesfinalsum[i]}'.hi'
      \cp 'z0.fits' $maskscalesfinalsumx'.fits' 2>&1; chk_rc
      rsltbratoko=0; nsbegoodcom[i]=0

# Co-add images for each scale over waves.

      for (( j=$nsbeg; j <= $nsbeams; j++ ))
      do
        if [[ $verb == "-verb0" ]]
        then 
          if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
          'PROGRESS_BAR' "$script: COMBINING$iw" $j $nsbeg $nsbeams 79 "-"
        fi 
        nsigma=${nsigmas[j]}
        thresh=${cutoffs[j]}
    
        sscimagej=${dirmono[i]}'/'${detectionclone[i]}'.'${nscbeam[j]}
        sscimagejan=${dirmono[i]}'/'${detectionclone[i]}'.'${nscbeam[j]}'.an'
        locsscimagejan=${detectionclone[i]}'.'${nscbeam[j]}'.an'
        if [[ $savespace -eq 0 ]]
        then
          sscimagejnn=$sscimagej'.nn'
          sscimagejre=$sscimagej'.re'
          locsscimagejnn=${detectionclone[i]}'.'${nscbeam[j]}'.nn'
          locsscimagejre=${detectionclone[i]}'.'${nscbeam[j]}'.re'
          if [[ -e $sscimagejnn'.fits' ]]
          then \cp $sscimagejnn'.fits' $locsscimagejnn'.m.fits' 2>&1; chk_rc
          fi
          if [[ -e $sscimagejre'.fits' ]]
          then \cp $sscimagejre'.fits' $locsscimagejre'.m.fits' 2>&1; chk_rc
          fi
        fi
        if [[ $filaments == "yes" ]]
        then
          sscimagejfp=${dirmono[i]}'/+filaments/'${detectionclone[i]}'.'${nscbeam[j]}'.fp'
        fi
                
        beamsratio1=$(echo "scale=9; 1.0001*${sbeam[1]}/${beam[i]}" | bc); chk_rc
        if [[ ${beamsratio1:0:1} == "." ]]; then beamsratio1='0'$beamsratio1; fi
        beamsratioj=$(echo "scale=9; 1.0001*${sbeam[j]}/${beam[i]}" | bc); chk_rc
        if [[ ${beamsratioj:0:1} == "." ]]; then beamsratioj='0'$beamsratioj; fi
        beamsratok=$fsbelowbeam
        if [[ ${beamsratok:0:1} == "." ]]; then beamsratok='0'$beamsratok; fi
        'COMPARE_NUMBERS' $beamsratio1 '>' $beamsratok; rsltbratok1=$?
        if [[ $rsltbratok1 -eq 1 ]]; then beamsratok=$beamsratio1; fi
        'COMPARE_NUMBERS' $beamsratioj '>=' $beamsratok; rsltbratok=$?

# Do the scale if there is no gap, i.e. 'an' ("above-noise") image exists.
      
        if [[ $j -le ${lastbrightscale[i]} && -e $sscimagejan'.fits' && $rsltbratok -eq 1 && $rsltbratoko -eq 1 ]]
        then
          if [[ ${nsbegoodcom[i]} -eq 0 ]]
          then 
            nsbegoodcom[i]=$j
          fi
          wavescombined[j]=${wavescombined[j]}' '${wave[i]}
          
          \cp $sscimagejan'.fits' $locsscimagejan'.m.fits' 2>&1; chk_rc

# Clean faint peaks to make sure that the combined images are really good and contain only sources.

          thresh=$(echo "scale=20; 1.001*$thresh" | bc); chk_rc

          $path'/modfits' minimum $thresh y $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc

# Clean small isolated clusters of pixels to reduce numbers of spurious sources.

          if [[ $minpixfloor -gt 0 ]]
          then
            $path'/modfits' clean4 ${minpix[i]} 0 $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          fi
           
          'CREATE_MASKS' $thresh $locsscimagejan'.m' $locsscimagejan'.msk'; chk_rc
        
          $path'/operate' $coaddedomask x $locsscimagejan'.msk' -o $locsscimagejan'.msk' $verb; chk_rc

# Sum up the sources in a mask image, only in a limited range of scales!
   
          $path'/operate' $maskscalesfinalsumx + $locsscimagejan'.msk' -o $maskscalesfinalsumx $verb; chk_rc

          $path'/operate' $locsscimagejan'.msk' x $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          $path'/operate' ${imageomask[i]} x $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
        
# Combining omask can be used to exclude some images or their areas from combining.

          if [[ ($flattening != 'yes' && $flattening != 'done' && $nwaves -eq 1) || \
                ($flattening == 'yes' || $flattening == 'done') ]]
          then
            $path'/operate' ${combiningomask[i]} x $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          fi
       
          \cp $locsscimagejan'.m.fits' $locsscimagejan'.s.fits' 2>&1; chk_rc

# Subtract the filaments from the single-scale images to improve the latter.

          if [[ $filaments == "yes" ]]
          then
            if [[ -e $sscimagejfp'.fits' ]]
            then 
              $path'/operate' $locsscimagejan'.m' - $sscimagejfp -o $locsscimagejan'.m' $verb; chk_rc
              $path'/modfits' minimum $thresh y $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
              \cp $locsscimagejan'.m.fits' ${sscimagejan/.an/.fs}'.fits' 2>&1; chk_rc

              if [[ $minpixfloor -gt 0 ]]
              then
                $path'/modfits' clean4 ${minpix[i]} 0 $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
              fi
            fi
          fi
          
          contrastss=$(echo "scale=20; ${ssimagemax[j]}/$thresh" | bc); chk_rc
          if [[ ${contrastss:0:1} == "." ]]; then contrastss='0'$contrastss; fi
        
# Compute scaling factors for all waves to normalize thresholds.

          if [[ $j -eq ${nsbegoodcom[i]} ]]
          then 
            'COMPARE_NUMBERS' ${ssimagemax[1]} '>' '0.0'; rslt=$?
            if [[ $rslt -eq 1 ]]
            then denominator=${ssimagemax[1]}
            else echo; echo ' '$script': '$fun': ERROR:'
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo ' INFO: Denominator <= 0.0:' ${ssimagemax[1]}
              echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
              echo; fun=$funo; return 99
            fi
          fi
        
          if [[ $nwaves -gt 1 ]]
          then
            aaa=$(echo "scale=20; ($comboexpomax-$comboexpomin)/($beammaxcombo-$beammincombo+0.0001)" | bc); chk_rc
            bbb=$(echo "scale=20; $comboexpomin+$aaa*$beammaxcombo" | bc); chk_rc
            comboexponent[i]=$(echo "scale=20; $bbb-$aaa*${beam[i]}" | bc); chk_rc
            if [[ ${comboexponent[i]:0:1} == "." ]]; then comboexponent[i]='0'${comboexponent[i]}; fi
            comboweight[i]=$(echo "scale=20; e(l($beamavcombo/${beam[i]})*${comboexponent[i]})" | bc -l); chk_rc
          else                
            comboexponent[i]='0.0'   
            comboweight[i]='1.0'
          fi                         
                                   
# It is important to have the new maximum slightly below 1.0 to avoid problems in detecting sources using the tint fill algorithm.
# This avoids any possibility of a pixel value becoming equal to the source number and cures the problems.
                                   
          newimagemax='0.99' #<-- IMPORTANT!!!
                                     
          factnormcombo=$(echo "scale=20; ($newimagemax/$denominator)*${comboweight[i]}" | bc); chk_rc
          if [[ ${factnormcombo:0:1} == "." ]]; then factnormcombo='0'$factnormcombo; fi
          newssimagemax=$(echo "scale=20; $factnormcombo*${ssimagemax[j]}" | bc); chk_rc
          if [[ ${newssimagemax:0:1} == "." ]]; then newssimagemax='0'$newssimagemax; fi
        
          turnonfact=$(echo "scale=9; (${sbeam[j]}/${beam[i]})^3" | bc); chk_rc

          'COMPARE_NUMBERS' $turnonfact '>' '1.0'; rsltgt1=$?
          if [[ $rsltgt1 -eq 1 ]]; then turnonfact='1.0'; fi

# This factnormthresh normalizes images such that the thresholds are 1.0 at each scale and wavelength.

          newthreshval='1.00'
          factnormthresh=$(echo "scale=20; $turnonfact*($newthreshval/$thresh)" | bc); chk_rc
          if [[ ${factnormthresh:0:1} == "." ]]; then factnormthresh='0'$factnormthresh; fi

          $path'/modfits' addconst -$thresh $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          $path'/modfits' multiply ${weight[i]} $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          $path'/modfits' addconst $thresh $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          $path'/modfits' minimum $thresh n $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc

          $path'/modfits' multiply $factnormthresh $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc

          $path'/modfits' multiply $factnormcombo  $locsscimagejan'.s' -o $locsscimagejan'.s' $verb; chk_rc
          
          newthreshsum[j]=$(echo "scale=20; ${newthreshsum[j]}+$newthreshval" | bc); chk_rc

          echo \'$sscimagejan\'': ssmax: '${ssimagemax[j]:0:11} 'newssmax: '${newssimagemax:0:11} 'thresh: '${thresh:0:11}\
                               'newthresh: '${newthreshval:0:11} 'comboexp: '${comboexponent[i]:0:6} 'minpix: '${minpix[i]}  >> $logit
          echo \'$sscimagejan\'': contrast: '${contrastss:0:11} 'threshmax: '${threshmax[j]:0:11}\
                               'factnormcombo: '${factnormcombo:0:11} 'factnormthresh: '${factnormthresh:0:11}\
                               'comboweight: '${comboweight[i]:0:11} >> $logit
        
# Add the current contribution to the sum of weights over all waves.

          comweight[j]='1.0'
          comweightsum[j]=$(echo "scale=20; ${comweightsum[j]}+${comweight[j]}" | bc); chk_rc

# Multiply the image by the weight.

          'COMPARE_NUMBERS' ${comweight[j]} '<' '0.9999'; rslt1=$?
          'COMPARE_NUMBERS' ${comweight[j]} '>' '1.0001'; rslt2=$?
          if [[ $rslt1 -eq 1 || $rslt2 -eq 1 ]]
          then
            if [[ $savespace -eq 0 ]]
            then
              if [[ -e $locsscimagejnn'.m.fits' ]]
              then $path'/modfits' multiply ${comweight[j]} $locsscimagejnn'.m' -o $locsscimagejnn'.m' $verb; chk_rc
              fi
              if [[ -e $locsscimagejre'.m.fits' ]]
              then $path'/modfits' multiply ${comweight[j]} $locsscimagejre'.m' -o $locsscimagejre'.m' $verb; chk_rc
              fi
            fi
            $path'/modfits' multiply ${comweight[j]} $locsscimagejan'.m' -o $locsscimagejan'.m' $verb; chk_rc
          fi

# Add the current contribution to the sum over all waves.

          if [[ $savespace -eq 0 ]]
          then
            if [[ -e $locsscimagejnn'.m.fits' ]]
            then $path'/operate' $locsscimagejnn'.m' + ${sscimagecomnn[j]} -o ${sscimagecomnn[j]} $verb; chk_rc
            fi
            if [[ -e $locsscimagejre'.m.fits' ]]
            then $path'/operate' $locsscimagejre'.m' + ${sscimagecomre[j]} -o ${sscimagecomre[j]} $verb; chk_rc
            fi
          fi

          $path'/operate' $locsscimagejan'.m' + ${sscimagecoman[j]} -o ${sscimagecoman[j]} $verb; chk_rc
          $path'/operate' $locsscimagejan'.s' + ${sscimagecomas[j]} -o ${sscimagecomas[j]} $verb; chk_rc

          if [[ $savespace -eq 0 ]]
          then
            \rm $locsscimagejnn'.m.fits' 2>&1; chk_rc
            \rm $locsscimagejre'.m.fits' 2>&1; chk_rc
          fi
          \rm $locsscimagejan'.m.fits' 2>&1; chk_rc
          \rm $locsscimagejan'.msk.fits' 2>&1; chk_rc
          jlastexist=$j
        fi

# Avoid abrupt changes in the ".as" combined images when a poorer-resolution image switches on and starts adding 
# single scales to the combined images. Now all poorer-resolution images will have non-zero small-scale images that
# are just copies of their first good single-scale image. This eliminates jumps in the ".as" images used to determine
# the characteristic scales and detection footprints.

        if [[ $j -eq ${nsbegoodcom[i]} && $nsbeg -lt ${nsbegoodcom[i]} ]]
        then 
          jm1=$(( j - 1 ))
          for (( jj=$jm1; jj >= $nsbeg; jj-- ))
          do
            $path'/operate' $locsscimagejan'.s' + ${sscimagecomas[jj]} -o ${sscimagecomas[jj]} $verb; chk_rc
          done
        fi

        if [[ -e $locsscimagejan'.s.fits' ]]
        then \rm $locsscimagejan'.s.fits' 2>&1; chk_rc
        fi
          
        rsltbratoko=$rsltbratok
    
        if [[ -e '+stopitnow!' ]]
        then 
          \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
          echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE.'; echo; exit 99
        fi
      done
    
      if [[ $verb == "-verb0" ]]
      then 
        'PROGRESS_BAR' 'complete' $nsbeams $nsbeg $nsbeams 79 "-"
      fi
    
      $path'/operate' $maskscaleswavesfinalsumx + $maskscalesfinalsumx -o $maskscaleswavesfinalsumx $verb; chk_rc
    fi
  done

  if [[ -e $filecombining ]]
  then 
    if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
    if [[ -e $subdirbackups'/'$filecombining ]]
    then
      backtimestamp=`date +%y%m%d.%H%M%S`
      \mv $subdirbackups'/'$filecombining $subdirbackups'/'$filecombining'.'$backtimestamp 2>&1; chk_rc
    fi
    \cp $filecombining $subdirbackups 2>&1; chk_rc
  fi
  
# Accumulate filaments.

  if [[ $filaments == "yes" && $nwaves -gt 1 ]]
  then
    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' "$script: COMPLETING" 0 0 $nsbeams 79 "-"
    fi
    if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi
    detimswfb=$subdirinterface'/'$prefix'.sw.det.filaments'; \cp 'z0.fits' $detimswfb'.fits' 2>&1; chk_rc
    detimswfm=$subdirinterface'/'$prefix'.sw.det.filaments.masks'; \cp 'z0.fits' $detimswfm'.fits' 2>&1; chk_rc

    if [[ $combinedinitialextraction == "no" ]]
    then 
      obsimswfb=$subdirinterface'/'$prefix'.sw.obs.filaments'; \cp 'z0.fits' $obsimswfb'.fits' 2>&1; chk_rc
      obsallwfb=$subdirinterface'/'$prefix'.sw.obs.allw.filaments'; \cp 'z0.fits' $obsallwfb'.fits' 2>&1; chk_rc
    fi

    for (( i=1; i <= $nwaves; i++ ))
    do
      obsfilaments=${dirmono[i]}'/+interface/'${measuremtclone[i]}'.filaments'

      if [[ $combinedinitialextraction == "no" ]]
      then
        if [[ -e $obsfilaments'.fits' ]]
        then 
          $path'/operate' ${imageomask[i]} x $obsfilaments -o $obsfilaments $verb; chk_rc
          $path'/operate' $obsallwfb + $obsfilaments -o $obsallwfb $verb; chk_rc
        fi
      fi

      if [[ ${usewaveincombining[i]} == "yes" ]]
      then
        detfilaments=${dirmono[i]}'/+interface/'${detectionclone[i]}'.filaments'
        detfilamentsm=${dirmono[i]}'/+interface/'${detectionclone[i]}'.filaments.masks'

        $path'/operate' ${imageomask[i]} x $detfilaments -o $detfilaments $verb; chk_rc
        $path'/operate' $detimswfb + $detfilaments -o $detimswfb $verb; chk_rc

        $path'/operate' ${imageomask[i]} x $detfilamentsm -o $detfilamentsm $verb; chk_rc
        $path'/operate' $detimswfm + $detfilamentsm -o $detimswfm $verb; chk_rc

        if [[ $combinedinitialextraction == "no" ]]
        then
          if [[ -e $obsfilaments'.fits' ]]
          then 
            $path'/operate' ${imageomask[i]} x $obsfilaments -o $obsfilaments $verb; chk_rc
            $path'/operate' $obsimswfb + $obsfilaments -o $obsimswfb $verb; chk_rc
          fi
        fi
      fi
    done               
  fi
  
  echo '#'"${headerinfo[1]:3}" > $filecombining
  for (( v=2; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}" >> $filecombining; done
  echo '#' >> $filecombining
  echo '#' $cdate >> $filecombining
  echo '#' >> $filecombining
  echo '# List of the combined clean detection images, onesigmamean, nsigmasmax, nsigmasmean, etc.:' \
       'scale factor = '$sfactor >> $filecombining
  echo '#' >> $filecombining

# Divide the weighted sum by the sum of the weights to normalize.

  if [[ $savespace -eq 0 ]]
  then
    usmimagejm1=$prefix'.sw.det.~00'
    \cp 'z0.fits' $usmimagejm1'.fits' 2>&1; chk_rc
  fi
  nsbegood=0
  
  for (( j=$nsbeg; j <= $nsbeams; j++ ))
  do                        
    if [[ $verb == "-verb0" ]]
    then 
      if [[ $filaments == "yes" && $nwaves -gt 1 ]]
      then
        'PROGRESS_BAR' "$script: COMPLETING" $j 0 $nsbeams 79 "-"
      else
        'PROGRESS_BAR' "$script: COMPLETING" $j $nsbeg $nsbeams 79 "-"
      fi
    fi
    if [[ -e ${sscimagecoman[j]}'.fits' ]]
    then
      slightlyhigher=$(echo "scale=20; 1.00001*${newthreshsum[j]}" | bc); chk_rc

      $path'/modfits' minimum $slightlyhigher y ${sscimagecoman[j]} -o ${sscimagecoman[j]} $verb; chk_rc
  
      'COMPARE_NUMBERS' ${comweightsum[j]} '<' '0.999'; rslt1=$?
      'COMPARE_NUMBERS' ${comweightsum[j]} '>' '1.001'; rslt2=$?
      if [[ ($rslt1 -eq 1 || $rslt2 -eq 1) && \
            ${comweightsum[j]} != "0" && ${comweightsum[j]} != "0." && ${comweightsum[j]} != "0.0" ]]
      then
        if [[ $savespace -eq 0 ]]
        then
          $path'/modfits' divide ${comweightsum[j]} ${sscimagecomnn[j]} -o ${sscimagecomnn[j]} $verb; chk_rc
          $path'/modfits' divide ${comweightsum[j]} ${sscimagecomre[j]} -o ${sscimagecomre[j]} $verb; chk_rc
        fi
        $path'/modfits' divide ${comweightsum[j]} ${sscimagecoman[j]} -o ${sscimagecoman[j]} $verb; chk_rc
      fi

      $path'/imgstat' savein -nomed ${sscimagecoman[j]} ${sscimagecoman[j]} $verb; chk_rc
      
      read mino maxo mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
      if [[ ${mino:0:1} == "*" || ${maxo:0:1} == "*" || ${sig:0:1} == "*" || $sig == "0.000000000" ]]
      then 
        if [[ $verb != "-verb0" ]]
        then
          echo; echo ' '$script': '$fun': WARNING:'
          echo; echo '   Bad results from IMGSTAT (17):'
          echo ' '$mino $maxo $sig ###; fun=$funo; return 99
          \rm '.+imgstat2' 2>&1; chk_rc
        fi
      else \rm '.+imgstat2' 2>&1; chk_rc
      fi

# Finally normalize each and every single-scale detection image to NEWIMAGEMAX (just below 1).

      factnorm1='0.0'

      if [[ $maxo != "0.000000000" ]]
      then
        factnorm1=$(echo "scale=20; $newimagemax/$maxo" | bc); chk_rc
        if [[ ${factnorm1:0:1} == "." ]]; then factnorm1='0'$factnorm1; fi

        $path'/modfits' multiply $factnorm1 ${sscimagecoman[j]} -o ${sscimagecoman[j]} $verb; chk_rc
      fi

      onesigma=$(echo "scale=20; $factnorm1*$slightlyhigher/${nsigmasmean[j]}" | bc); chk_rc

      if [[ ${comweightsum[j]} != "0" && ${comweightsum[j]} != "0." && ${comweightsum[j]} != "0.0" ]]
      then
        onesigma=$(echo "scale=20; $onesigma/${comweightsum[j]}" | bc); chk_rc
      fi
      if [[ ${onesigma:0:1} == "." ]]; then onesigma='0'$onesigma; fi
      
      echo \'$originpath'/'${sscimagecoman[j]}'.fits'\' $onesigma ${nsigmasmax[j]} ${nsigmasmean[j]} $factnorm1 $slightlyhigher \
                                                        ${newthreshsum[j]} ${comweightsum[j]} ${wavescombined[j]} >> $filecombining
           
      if [[ $maxo != "0.000000000" && $nsbegood -eq 0 ]]
      then
        nsbegood=$j
      fi

      'COMPARE_NUMBERS' ${sbeam[j]} '>' $beammaxcombo; rsltbm=$?
      if [[ $rsltbm -eq 1 && $nsbegood -gt 0 && $j -le $lastbrightscalemax && $maxo == "0.000000000" ]]
      then
        lastbrightscalemax=$(( j - 1 ))
        echo $lastbrightscalemax > $prefix'.sw.det.lastbright'
      fi
    fi

# Create wave-combined clean usm images.

    if [[ $savespace -eq 0 ]]
    then
      if [[ -e ${sscimagecoman[j]}'.fits' ]]
      then
        usmimagej=$prefix'.sw.det.~'${nscbeam[j]}'.an'

        $path'/operate' $usmimagejm1 + ${sscimagecoman[j]} -o $usmimagej $verb; chk_rc

# The usm images themselves are not used, just to produce the final clean image $imagesw; so remove them.

        \rm $usmimagejm1'.fits' 2>&1; chk_rc

        usmimagejm1=$usmimagej
      fi
 
# Create wave-combined noise image.

      if [[ -e ${sscimagecomre[j]}'.fits' ]]
      then
        $path'/operate' $imageswno + ${sscimagecomre[j]} -o $imageswno $verb; chk_rc
      fi
    fi
    
    if [[ -e '+stopitnow!' ]]
    then 
      \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
      echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE.'; echo; exit 99
    fi
  done

# Add the last remaining smoothed image $imagesw to the reassembled usm image and restrict it to the total mask image.
    
  if [[ $savespace -eq 0 ]]
  then
    $path'/operate' $usmimagej + $imagesw -o $imagesw $verb; chk_rc
    $path'/operate' $coaddedomask x $imagesw -o $imagesw $verb; chk_rc
    $path'/operate' $coaddedomask x $imageswno -o $imageswno $verb; chk_rc
 
    \rm $usmimagej'.fits' 2>&1; chk_rc
  fi

  if [[ $verb == "-verb0" ]]
  then 
    'PROGRESS_BAR' 'complete' $nsbeams $nsbeg $nsbeams 79 "-"
  fi

# Clean up.

  for (( j=$nsbeg; j <= $nsbeams; j++ ))
  do
    if [[ $savespace -eq 0 && $j -le $lastbrightscalemax ]]
    then 
      \rm ${sscimagecomnn[j]}'.fits' 2>&1; chk_rc
      \rm ${sscimagecomre[j]}'.fits' 2>&1; chk_rc
    fi
  done               

  filecombo=$prefix'.sw.det.combined'
  if [[ -e $filecombo ]]
  then 
    if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
    if [[ -e $subdirbackups'/'$filecombo ]]
    then
      backtimestamp=`date +%y%m%d.%H%M%S`
      \mv $subdirbackups'/'$filecombo $subdirbackups'/'$filecombo'.'$backtimestamp 2>&1; chk_rc
    fi
    \cp $filecombo $subdirbackups 2>&1; chk_rc
  fi

  echo '#'"${headerinfo[1]:3}" > $filecombo
  for (( v=2; v <= 4; v++ )); do echo '#'"${headerinfo[v]:3}" >> $filecombo; done
  echo '#' >> $filecombo
  echo '#' $cdate >> $filecombo
  echo '#' >> $filecombo
  echo '# The combined detection images '\'$prefix'.sw.det.*.an.m.fits'\'' were created as follows:' >> $filecombo
  echo '#' >> $filecombo

  ix=0
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ ${usewaveincombining[i]} == "yes" ]]
    then
      if [[ $ix -eq 0 ]]
      then 
        ix=i
        echo ' combined of '\'$prefix'.'${wave[i]}'.det.*.an.m.fits'\'\
             '(comboexp: '${comboexponent[i]:0:9}', combowei: '${comboweight[i]:0:9}', minpix: '${minpix[i]}')' >> $filecombo
      else 
        echo '      and of '\'$prefix'.'${wave[i]}'.det.*.an.m.fits'\'\
             '(comboexp: '${comboexponent[i]:0:9}', combowei: '${comboweight[i]:0:9}', minpix: '${minpix[i]}')' >> $filecombo
      fi
    fi
  done

  combine_end=`date +%s`; combine_time=$((combine_end - combine_beg))
  echo; echo ' GETSOURCES: '$combine_time' SECONDS'
  fun=$funo
} 
#___________________________________________________________________________________________________________________________________

DETECT_ALL_SOURCES ()
{                          
  local funo=$fun; fun='DETECT_ALL_SOURCES'; title=$script': => (4) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $detecting == "no" ]]; then echo ' ~~~> skipping...'; fun=$funo; return 0; else echo; fi
  detect_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  local idetect; local catalog; local image; local jlastfp=999; local i; local j; local isegment; local jnsbm1
  local detwave; local detbeam; local ns1det; local lastscalecat=''
  nprogress=0

  im1=0; allwaves=''  
  for (( i=1; i <= $nwaves; i++ ))
  do
    detwave[i]=${wave[i]}
    detbeam[i]=${beam[i]}
    if [[ ${usewaveincombining[i]} == "yes" ]]
    then
      allwaves=$allwaves' '${wave[i]}
    fi
  done

  if [[ $lastbrightscalemax -eq 0 ]]
  then 
    if [[ -e $prefix'.sw.det.lastbright' ]]
    then 
      read lastbrightscalemax < $prefix'.sw.det.lastbright'
    else echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Empty LASTBRIGHTSCALEMAX and file not found:'
      echo '       '\'$prefix'.sw.det.lastbright'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
  fi
  
# Find the number of scales from decomposed file names.

  if [[ ! -e $filecombining ]]
  then echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: File not found:'
    echo '       '\'$filecombining\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi

  nsbeg=0; nsbeams=0; sfxx=''
  {
  while read filename alltherest
  do
    if [[ ${filename:0:1} == '#' ]]
    then
      if [[ $alltherest != "" ]]
      then
        'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
        if [[ $sfpos -gt 0 ]]
        then
          sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
          sfactor=${alltherest:n1:22}
        fi
      fi
    else
      'POSITION' '.sw.det.' "$filename"; swdet=$returnposition
      if [[ $swdet -gt 0 ]]
      then
        swdetxx=".sw.det."; length=${#swdetxx}; n1=$(( swdet + length - 1 ))
        nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
        if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
        nscbeam[nsca]=${filename:n1:12}
        sbeam[nsca]=${nscbeam[nsca]:4:6}
      fi
    fi
  done
  } < $filecombining

  if [[ $sfxx == "" ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Scale factor not found in:'
    echo '       '\'$filecombining\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  
  if [[ ${nsbeg:0:1} == '0' ]]; then nsbeg=${nsbeg:1}; fi
  jnsbm1=$(( nsbeg - 1 ))
  
  detwave[jnsbm1]='0'
  detbeam[jnsbm1]=$beammincombo
  nscbeam[jnsbm1]='00.c0.0000as'
  image[jnsbm1]=$prefix'.sw.det'
  accufoots='sm.'${image[jnsbm1]}'.footprints.fits'
  swcatname='sm.'${image[jnsbm1]}'.cat'
  \cp 'z0.fits' $accufoots 2>&1; chk_rc
        
# Define maximum scale up to which new sources are allowed to appear.

  if [[ $srcmaxsizemax == "0" || $srcmaxsizemax == "0." || $srcmaxsizemax == "0.0" || $srcmaxsizemax == "0.00" ]]
  then
    nsrcmaxsizemax=$lastbrightscalemax
  else
    nsrcmaxsizemax=2
  
    for (( j=$nsbeg; j <= $nsbeams; j++ ))
    do
      srcscalemax=$(echo "scale=2; 3.0*$srcmaxsizemax" | bc)
      'COMPARE_NUMBERS' ${sbeam[j]} '>' $srcscalemax; rslt=$?
      if [[ $rslt -eq 1 || $j -gt $lastbrightscalemax ]]
      then 
        break
      fi
      nsrcmaxsizemax=$j
    done
  fi
  
  if [[ $nsrcmaxsizemax -lt 3 ]]
  then
    nsrcmaxsizemax=3
    lastbrightscalemax=$nsrcmaxsizemax
  fi

  if [[ $nsrcmaxsizemax -lt $nsbeams ]]
  then
###    nsfindermax=$nsbeams
##    nsfindermax=$(( nsrcmaxsizemax + 1 ))
    nsfindermax=$nsrcmaxsizemax
  else
    nsfindermax=$nsbeams
  fi
  
  if [[ $verb != "-verb0" && $sfinding == "yes" ]]
  then
    'LEADZEROS' 1 $nsrcmaxsizemax znsrcmaxsizemax

    echo; echo ' '$script': '$fun': Largest scale for new sources: '$znsrcmaxsizemax
  fi

  if [[ $sfinding == "no" ]]
  then
    if [[ `echo 'sm.seg.'$prefix'.sw.det'.*` == 'sm.seg.'$prefix'.sw.det.*' ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: Segmentation images/catalogs not found:'
      echo '       '\''sm.seg.'$prefix'.sw.det.*'\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' HINT: It is impossible *not* to execute SFINDER without those files'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
  fi
  
  nsfindermin=$nsbeg
  
  if [[ $nsd1 -eq 1 ]]
  then
    ns1det=$nsbeg
    jnsbm1=0
    jnsbm2=0
  else

# Restarting detection from an intermediate scale.

    ns1det=$nsd1
    jnsbm1=$(( ns1det - 1 ))
    jnsbm2=$(( ns1det - 2 )); if [[ $jnsbm2 -le 0 ]]; then jnsbm2=1; fi
    detwave[jnsbm1]='0'
    detwave[jnsbm2]='0'
    detbeam[jnsbm1]=$beammincombo
    detbeam[jnsbm2]=$beammincombo
    image[jnsbm1]=$prefix'.sw.det'
    image[jnsbm2]=$prefix'.sw.det'
    accufoots='sm.'${image[jnsbm1]}'.footprints.fits'
    swcatname='sm.'${image[jnsbm1]}'.cat'

    for (( j=1; j <= $jnsbm1; j++ ))
    do
      if [[ $verb == "-verb0" ]]
      then 
        'PROGRESS_BAR' "$script: DETECTING" $j 1 $nsfindermax 79 "-"
      fi

      idetect=${image[jnsbm1]}'.'${nscbeam[j]}'.an'
      isegment='sm.seg.'${image[jnsbm1]}'.'${nscbeam[j]}
      catalog=$isegment'.cat'
      footprint=$isegment'.fp'

      if [[ -e $originpath'/'$footprint'.fits' ]]
      then
        $path'/operate' $originpath'/'$footprint + $accufoots -o $accufoots $verb; chk_rc
        jlastfp=$j
      fi
    done
  fi
  
  zeroimage='no'
  idetecto=${image[jnsbm1]}'.'${nscbeam[jnsbm1]}'.an'
  isegmento='sm.seg.'${image[jnsbm1]}'.'${nscbeam[jnsbm1]}
  idetectoo=${image[jnsbm2]}'.'${nscbeam[jnsbm2]}'.an'
  catalogo=$isegmento'.cat'

  if [[ $sfinding == "yes" ]]
  then
    if [[ -e $originpath'/'$idetecto'.fits' ]]
    then
      \cp $originpath'/'$idetecto'.fits' $idetecto'.m.fits' 2>&1; chk_rc
      \cp $originpath'/'${idetecto/.an/.as}'.fits' ${idetecto/.an/.as}'.m.fits' 2>&1; chk_rc
    fi
    if [[ -e $originpath'/'$idetectoo'.fits' ]]
    then
      \cp $originpath'/'$idetectoo'.fits' $idetectoo'.m.fits' 2>&1; chk_rc
      \cp $originpath'/'${idetectoo/.an/.as}'.fits' ${idetectoo/.an/.as}'.m.fits' 2>&1; chk_rc
    fi
  fi

  for (( j=$ns1det; j <= $nsfindermax; j++ ))
  do
    jm1=$(( j - 1 )); if [[ $jm1 -le $ns1det ]]; then jm1=$ns1det; fi
    jm2=$(( j - 2 )); if [[ $jm2 -le $ns1det ]]; then jm2=$ns1det; fi
    idetect=${image[jnsbm1]}'.'${nscbeam[j]}'.an'
    isegment='sm.seg.'${image[jnsbm1]}'.'${nscbeam[j]}
    catalog=$isegment'.cat'
    footprint=$isegment'.fp'
    rmsannuli=$isegment'.ra'
    
    if [[ $sfinding == "yes" ]]
    then
      \cp $originpath'/'$idetect'.fits' $idetect'.m.fits' 2>&1; chk_rc

      $path'/operate' $detectingomask x $idetect'.m' -o $idetect'.m' $verb; chk_rc
     
      $path'/imgstat' savein -nomed $idetect'.m' $verb; chk_rc  
     
      read min max mea med totsum sig skew kurt edgemean < '.+imgstat1'; chk_rc
      \rm '.+imgstat1' 2>&1; chk_rc
      if [[ $min == "0.000000000" && $max == "0.000000000" && $sig == "0.000000000" ]]
      then 
        if [[ $verb != "-verb0" ]]
        then echo; echo ' '$script': '$fun': WARNING: Zero detection image: skipping...'
        fi
        ns1det=$(( ns1det + 1 ))
        jnsbm1=$(( ns1det - 1 ))
        detwave[jnsbm1]='0'
        detbeam[jnsbm1]=$beammincombo
        nscbeam[jnsbm1]='00.c0.0000as'
        image[jnsbm1]=$prefix'.sw.det'
        zeroimage='yes'
      else
        zeroimage='no'
      fi
    fi
    
    if [[ $verb == "-verb0" ]]
    then
      'PROGRESS_BAR' "$script: DETECTING" $j $nsfindermin $nsfindermax 79 "-"
    fi
    
    if [[ $zeroimage == "no" ]]
    then
      \cp $originpath'/'${idetect/.an/.as}'.fits' ${idetect/.an/.as}'.m.fits' 2>&1; chk_rc

      $path'/operate' $detectingomask x ${idetect/.an/.as}'.m' -o ${idetect/.an/.as}'.m' $verb; chk_rc

      if [[ $verb != "-verb0" ]]
      then
        echo '_______________________________________________________________________________'
        echo
        echo '                                   SFINDER'
        echo
        if [[ $nwaves -eq 1 ]]
        then
          echo ' Extracting sources at wavelength:'$allwaves' microns'
        else
          echo ' Extracting sources at wavelengths:'$allwaves' microns'
        fi
        echo ' Faintest and largest scales to look for new sources: '$lastbrightscalemax $nsrcmaxsizemax
        echo ' Minimum intensity contrast for removing noise peaks: '$contranoise
        echo ' Factor defining total footprint size from FWHM size: '$factortotal
        echo '  Image at ancient scale: '\'$idetectoo'.m.fits'\'
        echo ' Image at previous scale: '\'$idetecto'.m.fits'\'
        echo '  Image at current scale: '\'$idetect'.m.fits'\'
        echo '   Cat at previous scale: '\'$catalogo\'
        echo '    Cat at current scale: '\'$catalog\'
        echo '_______________________________________________________________________________'
      fi
    
      if [[ $sfinding == "yes" ]]
      then

# Delete catalogs and segmentation images left over from previous runs.

        if [[ -e $catalog ]]; then \rm $catalog 2>&1; chk_rc; fi
        if [[ -e $isegment'.fits'  ]]; then \rm $isegment'.fits'  2>&1; chk_rc; fi
        if [[ -e $footprint'.fits' ]]; then \rm $footprint'.fits' 2>&1; chk_rc; fi
  
# Extract sources using my method.

        if [[ $verb != "-verb0" ]]
        then
          $path'/sfinder' ${detwave[jnsbm1]} ${detbeam[jnsbm1]} $contranoise $factortotal $nsrcmaxsizemax $aperturemax \
                          $detectingomask $idetect'.m' $idetecto'.m' $idetectoo'.m' $isegmento -o $isegment $verb
        else
          $path'/sfinder' ${detwave[jnsbm1]} ${detbeam[jnsbm1]} $contranoise $factortotal $nsrcmaxsizemax $aperturemax \
                          $detectingomask $idetect'.m' $idetecto'.m' $idetectoo'.m' $isegmento -o $isegment $verb > $hell 2>&1
        fi
        sfrc=$?
        if [[ $sfrc -eq 89 ]]
        then echo
          echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Number of sources reached a pre-defined maximum NEXTRMAX.'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: Increase the value of NEXTRMAX, recompile SFINDER, and restart the'
          echo '       detection from the current scale # '$j
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        elif [[ $sfrc -eq 73 || $sfrc -eq 74 ]]
        then echo
          echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Trouble allocating memory ('$sfrc').'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: Use a more powerful computer or reduce dimensions of arrays, recompile'
          echo '       SFINDER, and restart the detection from the current scale # '$j
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        fi
        if [[ $sfrc -gt 10 && $sfrc -lt 100 ]]
        then 
          chk_rc $sfrc
        else
          if [[ $j -le $nsrcmaxsizemax ]]
          then sfrc=0
          fi
        fi
      else       
        if [[ $j -le $nsrcmaxsizemax ]]
        then sfrc=0
        else sfrc=9
        fi
      fi                   
   
      if [[ -e '+stopitnow!' ]]
      then 
        \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
        echo; echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW... DONE.'; echo; exit 99
      fi
      
      if [[ $sfrc -ne '0' && $sfrc -ne '9' ]]
      then 
        echo; echo ' '$script': '$fun': ERROR in SFINDER: rc='"$sfrc"; exit "$sfrc"
      fi
      
      if [[ -e $isegment'.fits' ]]
      then
        if [[ -e $footprint'.fits' ]]
        then
          $path'/operate' $footprint + $accufoots -o $accufoots $verb; chk_rc
          jlastfp=$j
        fi
        lastscalecat=$isegment'.cat'

# For scales which do not produce footprints it's not necessary to keep the files.
            
        if [[ $savespace -gt 1 ]]
        then
          if [[ $sfinding == "yes" && ($jm1 -gt $jlastfp || $jlastfp -eq 999) && $j -gt $ns1det ]]
          then 
            if [[ -e $isegmento'.fits' ]]; then \rm $isegmento'.fits' 2>&1; chk_rc; fi
            if [[ -e $footprint'.fits' ]]; then \rm $footprint'.fits' 2>&1; chk_rc; fi
            if [[ -e $catalogo ]]; then \rm $catalogo 2>&1; chk_rc; fi
          fi
        fi
        if [[ -e $idetectoo'.m.fits' ]]; then \rm $idetectoo'.m.fits' 2>&1; chk_rc; fi
        if [[ -e ${idetectoo/.an/.as}'.m.fits' ]]; then \rm ${idetectoo/.an/.as}'.m.fits' 2>&1; chk_rc; fi
        
        idetectoo=$idetecto
        idetecto=$idetect
        isegmento=$isegment
        catalogo=$catalog
      fi
    else
      if [[ -e $idetect'.m.fits' ]]; then \rm $idetect'.m.fits' 2>&1; chk_rc; fi
    fi

    if [[ $j -gt $nsrcmaxsizemax && $sfrc -eq 9 ]]
    then
      if [[ $verb != "-verb0" ]]
      then 
        echo; echo ' '$script': '$fun': All sources extracted.'
      fi
      break
    fi
  done

  if [[ $verb == "-verb0" ]]
  then 
    'PROGRESS_BAR' 'complete' $nsfindermax $nsfindermin $nsfindermax 79 "-"
  fi

  if [[ $lastscalecat == "" ]]
  then
    if [[ $nwaves -eq 1 ]]
    then echo 0 > $subdirinterface'/'$prefix'.'${wave[1]}'.srcmaxsize'
    fi
    echo; echo ' '$script': '$fun': WARNING:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Detection catalog not found. It seems no sources have been detected.'
    echo '       GETSOURCES will create one spurious source to allow further processing.'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    \cp 'z0.fits' $idetect'.m.fits' 2>&1; chk_rc
    \cp 'z0.fits' ${idetect/.an/.as}'.m.fits' 2>&1; chk_rc
    if [[ $verb != "-verb0" ]]
    then
      $path'/sfinder' ${detwave[nsfindermax]} ${detbeam[nsfindermax]} 0.0d0 $factortotal $nsrcmaxsizemax $aperturemax \
                      $detectingomask $idetect'.m' $idetecto'.m' $idetectoo'.m' $isegmento -o $isegment $verb
    else
      $path'/sfinder' ${detwave[nsfindermax]} ${detbeam[nsfindermax]} 0.0d0 $factortotal $nsrcmaxsizemax $aperturemax \
                      $detectingomask $idetect'.m' $idetecto'.m' $idetectoo'.m' $isegmento -o $isegment $verb > $hell 2>&1
    fi
    sfrc=$?
    if [[ $sfrc -ne '0' && $sfrc -ne '9' ]]
    then 
      echo; echo ' '$script': '$fun': ERROR in SFINDER: rc='"$sfrc"; exit "$sfrc"
    fi
    if [[ -e $idetect'.m.fits' ]]; then \rm $idetect'.m.fits' 2>&1; chk_rc; fi
    if [[ -e ${idetect/.an/.as}'.m.fits' ]]; then \rm ${idetect/.an/.as}'.m.fits' 2>&1; chk_rc; fi
    lastscalecat=$isegment'.cat'
  fi

# Copy the last-scale catalog as the detection catalog.

  \cp $lastscalecat $swcatname 2>&1; chk_rc

# Remove remaining temporary images used for sources detection.

  if [[ -e $idetecto'.m.fits' ]]; then \rm $idetecto'.m.fits' 2>&1; chk_rc; fi
  if [[ -e $idetectoo'.m.fits' ]]; then \rm $idetectoo'.m.fits' 2>&1; chk_rc; fi
  if [[ -e ${idetecto/.an/.as}'.m.fits' ]]; then \rm ${idetecto/.an/.as}'.m.fits' 2>&1; chk_rc; fi
  if [[ -e ${idetectoo/.an/.as}'.m.fits' ]]; then \rm ${idetectoo/.an/.as}'.m.fits' 2>&1; chk_rc; fi

# Correct footprints by clearing them from image edges.

  'CLEAR_IMAGE_BORDERS' border 3 $accufoots $accufoots; chk_rc
  
  detect_end=`date +%s`; detect_time=$((detect_end - detect_beg))
  echo; echo ' GETSOURCES: '$detect_time' SECONDS'
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

MEASURE_PROPERTIES ()
{                          
  local funo=$fun; fun='MEASURE_PROPERTIES'; title=$script': => (5) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $measuring == "no" && ($filaments == "no" || $fproima == "no") ]]
  then echo ' ~~~> skipping...'; fun=$funo; return 0; else echo; fi
  measure_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  local i; local j; local k; local kk; local l; local kp1; local sign1=''; local sign2=''; local sign3=''; local signsm=''
  local sign1old=''; local sign2old=''; local sign3old=''; local iterlimit1=0; local iterlimit2=0
  nprogress=0

# Measure filaments.

  if [[ $cleaning == "yes" && $filaments == "yes" && $fproima == "yes" ]]
  then
    for (( i=1; i <= $nwaves; i++ ))
    do
      if [[ ! -e ${filedecomposing[i]} ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File not found:'
        echo '       '\'${filedecomposing[i]}\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      
      nsbeg=0; nsbeams=0; sfxx=''
      {
      while read filename alltherest
      do
        if [[ ${filename:0:1} == '#' ]]
        then
          if [[ $alltherest != "" ]]
          then
            'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
            if [[ $sfpos -gt 0 ]]
            then
              sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
              sfactor=${alltherest:n1:22}
            fi
          fi
        else
          'POSITION' '.'${wave[i]}'.det.' "$filename"; wavdet=$returnposition
          if [[ $wavdet -gt 0 ]]
          then
            waveixx=".${wave[i]}.det."
            length=${#waveixx}; n1=$(( wavdet + length - 1 ))
            nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
            if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
            nscbeam[nsca]=${filename:n1:12}
            sbeam[nsca]=${nscbeam[nsca]:4:6}
          fi
        fi
      done
      } < ${filedecomposing[i]}
    done
  
    'DEFINE_SKELETON_LEVELS'
    
    for (( i=1; i <= $nwaves; i++ ))
    do
      'DEFINE_FILAMENTS_SCALES' ${beam[i]}
  
      if [[ ${filmaxsize[i]} -ge ${filmaxsizeo[i]} ]]
      then filmaxsizefin=${filmaxsize[i]}
      else filmaxsizefin=${filmaxsizeo[i]}
      fi
      image[i]=${detectionclone[i]}
      obsfilaments=${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments'
      for (( k=0; k <= $nsfils; k++ ))
      do
        obsfilamentsx[k]=$obsfilaments'.'${zfilscale[k]}'as'
      done
      detskeletons=${dirmono[i]}'/+interface/'${image[i]}'.skeletons'
      subdirfprofiles=${dirmono[i]}'/+filaments/+profiles'
  
      if [[ $fproima == "yes" ]]
      then
        nsfilsp1=$(( nsfils + 1 ))
        if [[ $verb == "-verb0" ]]
        then 
          if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
          'PROGRESS_BAR' "$script: MEASURING$iw" 0 0 $nsfilsp1 79 "-"
        fi
        for (( kk=0; kk <= $nsklevs; kk++ ))
        do
          zkk=${zsklev[kk]}
          
          for (( l=0; l <= $nsskel; l++ ))
          do
            zl=${zfilscale[l]}'as'
            if [[ ${filscale[kk]} -le $filmaxsizefin && -e $detskeletons'.'$zl'.c'${zsklev[kk]}'.fits' ]]
            then 
              if [[ ! -e $subdirfprofiles'/allscales' ]]
              then 
                \mkdir -p $subdirfprofiles'/allscales' 2>&1; chk_rc
              fi
              $path'/fmeasure' $obsfilaments'+.m' $detskeletons'.'$zl'.c'$zkk $npxstep $subdirfprofiles'/allscales' \
                            -o $obsfilaments'+.m.skeletons.'$zl'.c'$zkk $verb; chk_rc
  
              $path'/modfits' thicken $detskeletons'.'$zl'.c'$zkk \
                                   -o $subdirfprofiles'/'${image[i]}'.skeletons.'$zl'.c'$zkk'.thick' $verb; chk_rc
              $path'/modfits' thicken $subdirfprofiles'/'${image[i]}'.skeletons.'$zl'.c'$zkk'.thick' \
                                   -o $subdirfprofiles'/'${image[i]}'.skeletons.'$zl'.c'$zkk'.thick' $verb; chk_rc
            fi
          done
        done
        kk=0
        zkk=${zsklev[kk]}
        for (( l=0; l <= $nsskel; l++ ))
        do
          zl=${zfilscale[l]}'as'
          if [[ ${filscale[kk]} -le $filmaxsizefin && -e $detskeletons'.'$zl'.c'${zsklev[kk]}'.fits' ]]
          then 
            $path'/modfits' maximum 1 n $subdirfprofiles'/'${image[i]}'.skeletons.'$zl'.c'${zsklev[kk]}'.thick' \
                         -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
            $path'/modfits' multiply 2 $prefix'.det.fi.sk.'$zl'.c'$zkk -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
            $path'/operate' $obsfilaments'+.m' x $prefix'.det.fi.sk.'$zl'.c'$zkk -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
            $path'/operate' $obsfilaments'+.m' + $prefix'.det.fi.sk.'$zl'.c'$zkk \
                         -o $subdirfprofiles'/'${measuremtclone[i]}'.filaments+.m.skeletons.'$zl'.c'$zkk $verb; chk_rc
            \rm $prefix'.det.fi.sk.'$zl'.c'$zkk'.fits' 2>&1; chk_rc
          fi
        done
  
        for (( k=0; k <= $nsfils; k++ ))
        do
          kp1=$(( k + 1 ))
          zk=${zfilscale[k]}'as'
          if [[ $verb == "-verb0" ]]
          then 
            if [[ $nwaves -eq 1 ]]; then iw=''; else iw=$i; fi
            'PROGRESS_BAR' "$script: MEASURING$iw" $kp1 0 $nsfilsp1 79 "~"
          fi
          if [[ ${filscale[k]} -le $filmaxsizefin && -e ${obsfilamentsx[k]}'.fits' ]]
          then 
            for (( kk=0; kk <= $nsklevs; kk++ ))
            do
              zkk=${zsklev[kk]}
              for (( l=0; l <= $nsskel; l++ ))
              do
                zl=${zfilscale[l]}'as'
                if [[ ${filscale[kk]} -le $filmaxsizefin && -e $detskeletons'.'$zl'.c'${zsklev[kk]}'.fits' ]]
                then
                  if [[ ! -e $subdirfprofiles'/upto~'$zk ]]
                  then 
                    \mkdir -p $subdirfprofiles'/upto~'$zk 2>&1; chk_rc
                  fi
                  $path'/fmeasure' ${obsfilamentsx[k]} $detskeletons'.'$zl'.c'$zkk $npxstep $subdirfprofiles'/upto~'$zk \
                                -o ${obsfilamentsx[k]}'.skeletons.'$zl'.c'$zkk $verb; chk_rc
  
                  if [[ $k -eq $l ]]
                  then
                    $path'/modfits' maximum 1 n $subdirfprofiles'/'${image[i]}'.skeletons.'$zl'.c'${zsklev[kk]}'.thick' \
                                 -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
                    $path'/modfits' multiply 2 $prefix'.det.fi.sk.'$zl'.c'$zkk -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
                    $path'/operate' $obsfilaments'.'$zk x $prefix'.det.fi.sk.'$zl'.c'$zkk \
                                 -o $prefix'.det.fi.sk.'$zl'.c'$zkk $verb; chk_rc
                    $path'/operate' $obsfilaments'.'$zk + $prefix'.det.fi.sk.'$zl'.c'$zkk \
                                 -o $subdirfprofiles'/'${measuremtclone[i]}'.filaments.'$zk'.skeletons.'$zl'.c'$zkk $verb; chk_rc
                    \rm $prefix'.det.fi.sk.'$zl'.c'$zkk'.fits' 2>&1; chk_rc
                  fi
                fi
              done
            done
          fi
        done
  
        if [[ $verb == "-verb0" ]]
        then 
          'PROGRESS_BAR' 'complete' $nsfilsp1 0 $nsfilsp1 79 "~"
        fi
      fi
    done
  fi
  
# Measure sources.

  if [[ $measuring == "yes" ]]
  then
    logfootit='+log.FOOTPRINTS.iter'
    logfootnew='+log.FOOTPRINTS.new.iter'
    logfootbak='+log.FOOTPRINTS.bak.iter'
  
    'LEADZEROS' 1 $itermax zitermax
  
    allwaves=''; allsrcmaxsizes=''
    for (( i=1; i <= $nwaves; i++ ))
    do
      if [[ "${imagetype[i]}" == "Herschel" ]]
      then
        allwaves=$allwaves' +'${wave[i]}
      else
        allwaves=$allwaves' '${wave[i]}
      fi
      allsrcmaxsizes=$allsrcmaxsizes' '${srcmaxsize[i]}
      if [[ -e '+wave.'${wave[i]}'.done' ]]
      then
        \rm '+wave.'${wave[i]}'.done' 2>&1; chk_rc
      fi
    done
  
    unrotated='sm.'$prefix'.sw.det.unrotated.fits'
    accufoots='sm.'$prefix'.sw.det.footprints.fits'
    swcatname='sm.'$prefix'.sw.det.cat'
    coordfile='sm.'$prefix'.sw.det.wcs'
    filecombo=$prefix'.sw.det.combined'
  
# Compute real WCS coordinates using the XY2SKY utility from WCSTOOLS.
    
    if [[ $wcstools == "yes" ]]
    then
      'xy2sky' -dj -k 8 -n 5 $unrotated '@'$swcatname > $coordfile; chk_rc
    else
      if [[ -e $coordfile ]]; then \rm $coordfile 2>&1; chk_rc; fi
    fi
    
    if [[ $savespace -eq 0 ]]
    then
      if [[ ! -e "$subdirannuli" ]]
      then
        \mkdir -p $subdirannuli 2>&1; chk_rc
      else
        if [[ `echo $subdirannuli/*'.fits'` != $subdirannuli'/*.fits' ]]
        then
          ppath=`pwd`; \cd $subdirannuli; \rm *'.fits' 2>&1; chk_rc; \cd $ppath     #<-- to shorten the list of arguments for \rm
        fi
      fi
    fi
  
    if [[ $sproima == "yes" ]]
    then
      if [[ ! -e "$subdirsprofiles"  ]]
      then 
        \mkdir -p $subdirsprofiles 2>&1; chk_rc
      else
        if [[ `echo $subdirsprofiles/*'.dat'` != $subdirsprofiles'/*.dat' ]]
        then
          ppath=`pwd`; \cd $subdirsprofiles; \rm *'.dat' 2>&1; chk_rc; \cd $ppath   #<-- to shorten the list of arguments for \rm
        fi
      fi
      if [[ ! -e "$subdirsources" ]]
      then 
        \mkdir -p $subdirsources 2>&1; chk_rc
      else 
        if [[ `echo $subdirsources/*'.fits'` != $subdirsources'/*.fits' ]]
        then
          ppath=`pwd`; \cd $subdirsources; \rm *'.fits' 2>&1; chk_rc; \cd $ppath    #<-- to shorten the list of arguments for \rm
        fi
      fi
    fi
    if [[ ! -e "$subdiriterations" ]]; then \mkdir -p $subdiriterations 2>&1; chk_rc; fi
    
    catsallwaves=''; beamallwaves=''
    for (( i=1; i <= $nwaves; i++ ))
    do
      catsallwaves=$catsallwaves' '${smfcatname[i]}
      beamallwaves=$beamallwaves' '${beam[i]}
  
      'CLEAR_IMAGE_BORDERS' border 2 ${imageomask[i]} ${imagebsomask[i]}; chk_rc
    done
    
    for (( i=1; i <= $nwaves; i++ ))
    do
      if [[ -e $subdirbackups'/'${obsfootprints[i]} ]]
      then
        if [[ $verb != "-verb0" ]]; then echo; echo ' Restoring '\'${obsfootprints[i]}\''...'; fi
        \cp $subdirbackups'/'${obsfootprints[i]} ${obsfootprints[i]} 2>&1; chk_rc
      fi
      if [[ -e $subdirbackups'/'${measuremtclone[i]}'.fits' ]]
      then
        if [[ $verb != "-verb0" ]]; then echo; echo ' Restoring '\'${measuremtclone[i]}'.fits'\''...'; fi
        \cp $subdirbackups'/'${measuremtclone[i]}'.fits' ${measuremtclone[i]}'.fits' 2>&1; chk_rc
      fi
      if [[ -e $subdirbackups'/'${detectionclone[i]}'.fits' ]]
      then
        if [[ $verb != "-verb0" ]]; then echo; echo ' Restoring '\'${detectionclone[i]}'.fits'\''...'; fi
        \cp $subdirbackups'/'${detectionclone[i]}'.fits' ${detectionclone[i]}'.fits' 2>&1; chk_rc
      fi
      if [[ -e $subdirbackups'/'${smfcatname[i]} ]]
      then
        if [[ $verb != "-verb0" ]]; then echo; echo ' Restoring '\'${smfcatname[i]}\''...'; fi
        \cp $subdirbackups'/'${smfcatname[i]} ${smfcatname[i]} 2>&1; chk_rc
      fi
    done
  
# Create background-subtracted image from the measurement image using footprints and compute fluxes and sizes.
# Starting brand new iterations from scratch (iterbeg=1).
  
    reldiffx=$(echo "scale=2; $reldiffmax*2" | bc)
    
    if [[ $iterbeg -eq 1 ]]
    then
      sign1='+'; iter=1; 'LEADZEROS' 1 $iter ziter
  
      if [[ $verb == "-verb0" ]]
      then 
        'PROGRESS_BAR' "$script: MEASURING" $iter 1 $itermax 79 "-"
      fi
      if [[ $verb != "-verb0" ]]
      then
        echo ' _______________________________________________'
        echo
        echo ' '$script': '$fun': ITERATION 01/'$zitermax
        echo ' _______________________________________________'
      fi
      
      for (( i=1; i <= $nwaves; i++ ))
      do
        $path'/operate' ${imagebsomask[i]} x $accufoots -o ${detfootprints[i]} $verb; chk_rc
  
        if [[ $bgfisub == "yes" ]]
        then
          $path'/cleanbg' $navecln ${detectionclone[i]} ${detfootprints[i]} -o ${detectionclone[i]}'.cb' $verb; chk_rc
          $path'/imgstat' med 2 ${detectionclone[i]}'.cb' ${detfootprints[i]} -o ${detectionclone[i]}'.cb' $verb; chk_rc
          \rm ${detectionclone[i]}'.wk.fits' 2>&1; chk_rc
        else
          \cp 'z0.fits' ${detectionclone[i]}'.cb.fits' 2>&1; chk_rc
        fi
        $path'/operate' ${detectionclone[i]} - ${detectionclone[i]}'.cb' -o ${detectionclone[i]}'.bs' $verb; chk_rc
      
        'CLEAR_IMAGE_BORDERS' border 1 ${detectionclone[i]}'.bs' ${detectionclone[i]}'.bs'; chk_rc
      
        if [[ $bgfisub == "yes" ]]
        then
          $path'/cleanbg' $navecln ${measuremtclone[i]} ${detfootprints[i]} -o ${cbobsimage[i]} $verb; chk_rc
          $path'/imgstat' med 2 ${cbobsimage[i]} ${detfootprints[i]} -o ${cbobsimage[i]} $verb; chk_rc
          \rm ${wkobsimage[i]}'.fits' 2>&1; chk_rc
        else
          \cp 'z0.fits' ${cbobsimage[i]}'.fits' 2>&1; chk_rc
        fi
        $path'/operate' ${measuremtclone[i]} - ${cbobsimage[i]} -o ${imeasurebs[i]} $verb; chk_rc
        
        'CLEAR_IMAGE_BORDERS' border 1 ${imeasurebs[i]} ${imeasurebs[i]}; chk_rc
  
# The most accurate measurements are obtained on the filament-subtracted images.
  
        if [[ $bgfisub == "yes" ]]
        then
          $path'/cleanbg' $navecln ${measuremtclone[i]}'.fs' ${detfootprints[i]} -o ${cbobsimage[i]}'.fs' $verb; chk_rc
          $path'/imgstat' med 2 ${cbobsimage[i]}'.fs' ${detfootprints[i]} -o ${cbobsimage[i]}'.fs' $verb; chk_rc
          \rm ${wkobsimage[i]}'.fs.fits' 2>&1; chk_rc
          $path'/operate' ${measuremtclone[i]}'.fs' - ${cbobsimage[i]}'.fs' -o ${imeasurebs[i]}'.fs' $verb; chk_rc
        else
          \cp 'z0.fits' ${cbobsimage[i]}'.fs.fits' 2>&1; chk_rc
          $path'/operate' ${measuremtclone[i]} - ${cbobsimage[i]}'.fs' -o ${imeasurebs[i]}'.fs' $verb; chk_rc
        fi
      
        'CLEAR_IMAGE_BORDERS' border 1 ${imeasurebs[i]}'.fs' ${imeasurebs[i]}'.fs'; chk_rc
  
#### The best image of the clean background plus filaments with sources removed.
###
###      if [[ $filaments == "yes" ]]
###      then
###        $path'/operate' ${cbobsimage[i]}'.fs' + ${dirmono[i]}'/+interface/'${measuremtclone[i]}'.filaments' \
###                     -o ${cbobsimage[i]}'.best' $verb; chk_rc
###      else
###        \cp ${cbobsimage[i]}'.fs.fits' ${cbobsimage[i]}'.best.fits' 2>&1; chk_rc
###      fi
      
        $path'/smeasure' ${dxas:0:9} $smp${wave[i]} ${beam[i]} ${apcorrect[i]} ${aperture[i]} $sign1$stentative $sreliable \
                         $ndetwaves $factortotal $originpath ${dirmono[i]} ${imeasurebs[i]}'.fs' $swcatname \
                         -o ${smfcatname[i]} $verb; chk_rc
      done
    
# Produce semifinal and final source catalogs for all waves and correct footprints.
  
      if [[ $verb != "-verb0" ]]
      then
        $path'/finalcat' $sign1$stentative $sreliable $snratio1min $snratio2min 0 $reldiffx $originpath $catsallwaves $allwaves \
                         $beamallwaves $allsrcmaxsizes $allapertures -o $finalcatalog $verb; rcfinalcat=$?
      else
        $path'/finalcat' $sign1$stentative $sreliable $snratio1min $snratio2min 0 $reldiffx $originpath $catsallwaves $allwaves \
                         $beamallwaves $allsrcmaxsizes $allapertures -o $finalcatalog $verb > $hell 2>&1; rcfinalcat=$?
      fi
      if [[ $rcfinalcat -gt 10 && $rcfinalcat -lt 100 ]]; then chk_rc $rcfinalcat; fi
  
      for (( i=1; i <= $nwaves; i++ ))
      do
        smfcatalogiter=${smfcatname[i]/.cat/.$ziter.cat}
        \cp ${smfcatname[i]} $subdiriterations'/'$smfcatalogiter 2>&1; chk_rc
    
        if [[ -e $finalcatalog ]]
        then 
          finalcatalogiter=${finalcatalog/.cat/.$ziter.cat}
          \cp $finalcatalog $subdiriterations'/'$finalcatalogiter 2>&1; chk_rc
          finalcatalogok=${finalcatalog/.cat/.ok.cat}
          finalcatalogokiter=${finalcatalogok/.cat/.$ziter.cat}
          \cp $finalcatalogok $subdiriterations'/'$finalcatalogokiter 2>&1; chk_rc
        fi 
        if [[ -e ${obsfootprints[i]} ]]
        then 
          obsfootprintsiter=${obsfootprints[i]/.fits/.$ziter.fits}
          \cp ${obsfootprints[i]} $subdiriterations'/'$obsfootprintsiter 2>&1; chk_rc
        fi 
      done
    else
      iterbegx=$(( iterbeg - 1 ))
      l=0
      {
      while read logfootitline
      do
        read -r -a words <<< "$logfootitline"
        footprintsiter=${words[0]}
        literphase=${words[3]}
        l=$(( l + 1 ))
        if [[ ${footprintsiter:0:1} == "#" ]]
        then
          if [[ $l -eq 1 ]]
          then echo "$logfootitline" >  $logfootnew
          else echo "$logfootitline" >> $logfootnew
          fi
        else
          iterbeg=${footprintsiter:0:2}
          if [[ $iterbeg -le 9 ]]
          then echo "   $logfootitline" >> $logfootnew
          else echo  "  $logfootitline" >> $logfootnew
          fi                             
          if [[ $iterbeg -eq $iterbegx ]]
          then 
            read logfootitline
            read -r -a words <<< "$logfootitline"
            literphase=${words[3]}
            if [[ $literphase == "2" && $iterlimit1 -eq 0 ]]
            then iterlimit1=$iterbeg
            fi
            if [[ $literphase == "3" && $iterlimit2 -eq 0 ]]
            then iterlimit2=$iterbeg
            fi
            break
          fi
        fi
      done
      } < $logfootit
      \mv $logfootit $logfootbak 2>&1; chk_rc
      \mv $logfootnew $logfootit 2>&1; chk_rc
      if [[ ! -e "$subdirbackups" ]]; then \mkdir -p $subdirbackups 2>&1; chk_rc; fi
      if [[ -e $subdirbackups'/'$logfootbak ]]
      then
        backtimestamp=`date +%y%m%d.%H%M%S`
        \mv $subdirbackups'/'$logfootbak $subdirbackups'/'$logfootbak'.'$backtimestamp 2>&1; chk_rc
      fi
      \mv $logfootbak $subdirbackups 2>&1; chk_rc
  
# Continue measurements from some intermediate iteration 'iterbeg' > 1. Restore some necessary files.
                         
      for (( iter=1; iter <= $iterbeg; iter++ ))
      do
        if [[ $verb == "-verb0" ]]
        then 
          'PROGRESS_BAR' "$script: MEASURING" $iter 1 $itermax 79 "-"
        fi
      done
      
      iter=$iterbeg
      iterm1=$(( iter - 1 ))
      'LEADZEROS' 1 $iter ziter
      'LEADZEROS' 1 $iterm1 ziterm1
  
      if [[ $verb != "-verb0" ]]; then echo; fi
      for (( i=1; i <= $nwaves; i++ ))
      do
        if [[ ${aperture[i]:0:1} == "+" ]]
        then obsfootprintsiter=${obsfootprinta[i]/.fits/.$ziter.fits}
        else obsfootprintsiter=${obsfootprints[i]/.fits/.$ziter.fits}
        fi
        if [[ ! -e $subdiriterations'/'$obsfootprintsiter ]]
        then echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Restart file for measurements not found:'
          echo '       '\'$subdiriterations'/'$obsfootprintsiter\'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: Verify that the iteration '$iterbeg' has been completed'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; fun=$funo; return 99
        fi
        if [[ ${aperture[i]:0:1} == "+" ]]
        then 
          if [[ $verb != "-verb0" ]]; then echo ' Restoring '\'$obsfootprintsiter\'' => '\'${obsfootprinta[i]}\''...'; fi
          \cp $subdiriterations'/'$obsfootprintsiter ${obsfootprinta[i]} 2>&1; chk_rc
        else 
          if [[ $verb != "-verb0" ]]; then echo ' Restoring '\'$obsfootprintsiter\'' => '\'${obsfootprints[i]}\''...'; fi
          \cp $subdiriterations'/'$obsfootprintsiter ${obsfootprints[i]} 2>&1; chk_rc
        fi
        \rm ${smfcatname[i]/.cat/.previous.cat} 2>$hell
      done
      if [[ $verb != "-verb0" ]]; then echo; fi
      for (( i=1; i <= $nwaves; i++ ))
      do
        smfcatalogiter=${smfcatname[i]/.cat/.$ziter.cat}
        smfcatalogiterm1=${smfcatname[i]/.cat/.$ziterm1.cat}
        if [[ ! -e $subdiriterations'/'$smfcatalogiter ]]
        then echo; echo ' '$script': '$fun': ERROR:'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' INFO: Restart file for measurements not found:'
          echo '       '\'$subdiriterations'/'$smfcatalogiter\'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo ' HINT: Verify that the iteration '$iterbeg' has been completed'
          echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
          echo; fun=$funo; return 99
        fi
        if [[ $verb != "-verb0" ]]
        then echo ' Restoring '\'$smfcatalogiter\'' => '\'${smfcatname[i]}\''...'; fi
        \cp $subdiriterations'/'$smfcatalogiter ${smfcatname[i]} 2>&1; chk_rc
        if [[ $verb != "-verb0" ]]
        then echo ' Restoring '$smfcatalogiterm1' => '${smfcatname[i]/.cat/.previous.cat}'...'
        fi
        \cp -f $subdiriterations'/'$smfcatalogiterm1 ${smfcatname[i]/.cat/.previous} 2>$hell
      done
  
      rcfinalcat=0
    fi
  
    iterbeg=$(( iterbeg + 1 ))
    if [[ $iterlimit1 -eq 0 ]]; then iterlimit1=$(echo "scale=2; (1/3)*$itermax+1" | bc); chk_rc; iterlimit1=${iterlimit1%.*}; fi
    if [[ $iterlimit2 -eq 0 ]]; then iterlimit2=$(echo "scale=2; (2/3)*$itermax+1" | bc); chk_rc; iterlimit2=${iterlimit2%.*}; fi
    iterlimit1p1=$(( iterlimit1 + 1 ))
    iterlimit2p1=$(( iterlimit2 + 1 ))
    reldiffx=$(echo "scale=2; $reldiffmax*2" | bc)
    
    for (( iter=$iterbeg; iter <= $itermax; iter++ ))
    do
      if [[ $verb == "-verb0" ]]
      then
        'PROGRESS_BAR' "$script: MEASURING" $iter 1 $itermax 79 "-"
      fi
      iterm1=$(( iter - 1 ))
      'LEADZEROS' 1 $iter ziter
      'LEADZEROS' 1 $iterm1 ziterm1
  
      if [[ $verb != "-verb0" ]]
      then
        echo ' _______________________________________________'
        echo
        echo ' '$script': '$fun': ITERATION '$ziter'/'$zitermax
        echo ' _______________________________________________'
      fi
    
# Parameter telling FINALCAT what to do.
                             
      if [[ $iter -le $iterlimit1 ]]
      then
        sign1='+'
        if [[ $rcfinalcat -eq 9 ]]
        then sign1='-'; sign2='+'; iterlimit1=$iter
        fi
      else
        if [[ $iter -le $iterlimit2 ]]
        then
          sign1='-'; sign2='+'
          if [[ ($rcfinalcat -eq 9 && $iter -gt $iterlimit1p1) ]]
          then sign2='-'; sign3='+'; iterlimit2=$iter; reldiffx=$reldiffmax
          fi
        else
          sign1='-'; sign2='-'; sign3='+'
          if [[ ($rcfinalcat -eq 9 && $iter -gt $iterlimit2p1) || $iter -eq $itermax ]]
          then sign3='-'
          fi
          reldiffx=$reldiffmax
        fi
      fi
      signsm=$sign2
      if [[ $sign3 == "-" ]]
      then
        if [[ $sproima == "yes" ]]; then sign2='+'; fi
        if [[ $savespace -eq 0 ]]; then signsm='+'; fi        #<-- previously it was development == "yes"
      fi
  
      if [[ ($sign1 == "+" && $sign1old != "+") || ($sign2 == "+" && $sign2old != "+") || ($sign3 == "+" && $sign3old != "+") ]]
      then
        for (( i=1; i <= $nwaves; i++ ))
        do
          if [[ -e '+wave.'${wave[i]}'.done' ]]
          then \rm '+wave.'${wave[i]}'.done' 2>&1; chk_rc
          fi
        done
      fi
      
# Background subtraction (and measurements) under apertures is now possible.
    
      for (( i=1; i <= $nwaves; i++ ))
      do
        if [[ ! -e '+wave.'${wave[i]}'.done' || $sign3 == "-" ]]  #<-- sign3 = '-' means finishing mode (very last pass)
        then
          if [[ $sign3 == "-" && ${aperture[i]:0:1} == "+" ]]
          then obsfoots=${obsfootprinta[i]}
          else obsfoots=${obsfootprints[i]}
          fi
  
          $path'/operate' ${imagebsomask[i]} x $obsfoots -o $obsfoots $verb; chk_rc
  
          if [[ $bgfisub == "yes" ]]
          then
            $path'/cleanbg' $navecln ${detectionclone[i]} $obsfoots -o ${detectionclone[i]}'.cb' $verb; chk_rc
            $path'/imgstat' med 2 ${detectionclone[i]}'.cb' $obsfoots -o ${detectionclone[i]}'.cb' $verb; chk_rc
            \rm ${detectionclone[i]}'.wk.fits' 2>&1; chk_rc
          else
            \cp 'z0.fits' ${detectionclone[i]}'.cb.fits' 2>&1; chk_rc
          fi
          $path'/operate' ${detectionclone[i]} - ${detectionclone[i]}'.cb' -o ${detectionclone[i]}'.bs' $verb; chk_rc
      
          'CLEAR_IMAGE_BORDERS' border 1 ${detectionclone[i]}'.bs' ${detectionclone[i]}'.bs'; chk_rc
      
          if [[ $bgfisub == "yes" ]]
          then
            $path'/cleanbg' $navecln ${measuremtclone[i]} $obsfoots -o ${cbobsimage[i]} $verb; chk_rc
            $path'/imgstat' med 2 ${cbobsimage[i]} $obsfoots -o ${cbobsimage[i]} $verb; chk_rc
###          \rm ${wkobsimage[i]}'.fits' 2>&1; chk_rc
          else
            \cp 'z0.fits' ${cbobsimage[i]}'.fits' 2>&1; chk_rc
          fi
          $path'/operate' ${measuremtclone[i]} - ${cbobsimage[i]} -o ${imeasurebs[i]} $verb; chk_rc
  
          'CLEAR_IMAGE_BORDERS' border 1 ${imeasurebs[i]} ${imeasurebs[i]}; chk_rc
  
# The most accurate measurements are obtained on the filament-subtracted images.
  
          if [[ $bgfisub == "yes" ]]
          then
            $path'/cleanbg' $navecln ${measuremtclone[i]}'.fs' $obsfoots -o ${cbobsimage[i]}'.fs' $verb; chk_rc
            $path'/imgstat' med 2 ${cbobsimage[i]}'.fs' $obsfoots -o ${cbobsimage[i]}'.fs' $verb; chk_rc
            \rm ${wkobsimage[i]}'.fs.fits' 2>&1; chk_rc
            $path'/operate' ${measuremtclone[i]}'.fs' - ${cbobsimage[i]}'.fs' -o ${imeasurebs[i]}'.fs' $verb; chk_rc
          else
            \cp 'z0.fits' ${cbobsimage[i]}'.fs.fits' 2>&1; chk_rc
            $path'/operate' ${measuremtclone[i]} - ${cbobsimage[i]}'.fs' -o ${imeasurebs[i]}'.fs' $verb; chk_rc
          fi
  
          'CLEAR_IMAGE_BORDERS' border 1 ${imeasurebs[i]}'.fs' ${imeasurebs[i]}'.fs'; chk_rc
  
#### The best image of the clean background plus filaments with sources removed.
###
###        if [[ $filaments == "yes" ]]
###        then
###          $path'/operate' ${cbobsimage[i]}'.fs' + ${dirmono[i]}'/+interface/'${measuremtclone[i]}'.filaments' \
###                       -o ${cbobsimage[i]}'.best' $verb; chk_rc
###        else
###          \cp ${cbobsimage[i]}'.fs.fits' ${cbobsimage[i]}'.best.fits' 2>&1; chk_rc
###        fi
      
          $path'/smeasure' ${dxas:0:9} $smp${wave[i]} ${beam[i]} ${apcorrect[i]} ${aperture[i]} $sign1$stentative $signsm$sreliable \
                           $sign3$ndetwaves $factortotal $originpath ${dirmono[i]} ${imeasurebs[i]}'.fs' ${smfcatname[i]} \
                           -o ${smfcatname[i]} $verb; chk_rc
  
          smoobm2=$(echo "scale=20; $beammax*$beammax-${beam[i]}*${beam[i]}" | bc); chk_rc
                                          
          'COMPARE_NUMBERS' $smoobm2 '<=' '0'; rslt=$?
          if [[ $rslt -eq 1 ]]
          then
            if [[ $verb != "-verb0" ]]
            then echo
              echo ' Copying '${cbobsimage[i]}'.fits to '${cbobsimage[i]}'.smo.fits...'
            fi
            \cp ${cbobsimage[i]}'.fits' ${cbobsimage[i]}'.smo.fits'; chk_rc
          else
            smoobm=$(echo "scale=20; sqrt($smoobm2)" | bc); chk_rc
            addpx=$(echo "scale=20; 2.0*$smoobm/$dxas" | bc); chk_rc
          
            $path'/expanda' 1 ${cbobsimage[i]} ${imageomask[i]} -o ${cbobsimage[i]}'.smo' $verb; chk_rc
            $path'/modfits' expand $addpx ${cbobsimage[i]}'.smo' -o ${cbobsimage[i]}'.smo' $verb; chk_rc
            $path'/fftconv' $smoobm 0 ${cbobsimage[i]}'.smo' -o ${cbobsimage[i]}'.smo' $verb; chk_rc
            $path'/modfits' border -$addpx ${cbobsimage[i]}'.smo' -o ${cbobsimage[i]}'.smo' $verb; chk_rc
          fi
          $path'/operate' ${imageomask[i]} x ${cbobsimage[i]}'.smo' -o ${cbobsimage[i]}'.smo' $verb; chk_rc
        fi
      done
  
      if [[ $verb != "-verb0" ]]
      then
        $path'/finalcat' $sign1$stentative $sign2$sreliable $sign3$snratio1min $snratio2min $ndetwaves $reldiffx $originpath \
                         $catsallwaves $allwaves $beamallwaves $allsrcmaxsizes $allapertures -o $finalcatalog $verb
        rcfinalcat=$?
      else 
        $path'/finalcat' $sign1$stentative $sign2$sreliable $sign3$snratio1min $snratio2min $ndetwaves $reldiffx $originpath \
                         $catsallwaves $allwaves $beamallwaves $allsrcmaxsizes $allapertures -o $finalcatalog $verb > $hell 2>&1
        rcfinalcat=$?
      fi
      if [[ $rcfinalcat -gt 10 && $rcfinalcat -lt 100 ]]; then chk_rc $rcfinalcat; fi
  
# Allow stopping the measurement iterations nicely (as if they have converged)
# if there appears a file called '+stopitnow!' in the current directory.
  
      if [[ -e '+stopitnow!' ]]; then rcfinalcat=9; fi
    
# Store iterations.
  
      for (( i=1; i <= $nwaves; i++ ))
      do
        smfcatalogiter=${smfcatname[i]/.cat/.$ziter.cat}
        smfcatalogiterm1=${smfcatname[i]/.cat/.$ziterm1.cat}
        \cp ${smfcatname[i]} $subdiriterations'/'$smfcatalogiter 2>&1; chk_rc
        \cp -f $subdiriterations'/'$smfcatalogiterm1 ${smfcatname[i]/.cat/.previous.cat} 2>&1; chk_rc
    
        if [[ -e $finalcatalog ]]
        then 
          finalcatalogiter=${finalcatalog/.cat/.$ziter.cat}
          \cp $finalcatalog $subdiriterations'/'$finalcatalogiter 2>&1; chk_rc
          finalcatalogok=${finalcatalog/.cat/.ok.cat}
          finalcatalogokiter=${finalcatalogok/.cat/.$ziter.cat}
          \cp $finalcatalogok $subdiriterations'/'$finalcatalogokiter 2>&1; chk_rc
        fi 
        if [[ ${aperture[i]:0:1} == "+" ]]
        then 
          if [[ -e ${obsfootprinta[i]} ]]
          then 
            obsfootprintsiter=${obsfootprinta[i]/.fits/.$ziter.fits}
            \cp ${obsfootprinta[i]} $subdiriterations'/'$obsfootprintsiter 2>&1; chk_rc
          fi
        else 
          if [[ -e ${obsfootprints[i]} ]]
          then 
            obsfootprintsiter=${obsfootprints[i]/.fits/.$ziter.fits}
            \cp ${obsfootprints[i]} $subdiriterations'/'$obsfootprintsiter 2>&1; chk_rc
          fi
        fi 
        if [[ $sign3 == "-" ]]
        then
          if [[ -e ${obsfootprinta[i]} ]]
          then 
            \cp ${obsfootprinta[i]} $subdiriterations'/'${obsfootprinta[i]} 2>&1; chk_rc
          fi 
          if [[ -e ${subsfootprints[i]} ]]
          then 
            \cp ${subsfootprints[i]} $subdiriterations'/'${subsfootprints[i]} 2>&1; chk_rc
          fi 
        fi
      done
  
      if [[ $iter -lt $itermax || $rcfinalcat -eq 9 ]]
      then 
        if [[ $sign3 == "-" ]]
        then 
          if [[ $verb != "-verb0" ]]
          then
            echo ' __________________________________________________________'; echo
            if [[ $iter -eq 1 ]]
            then echo ' '$script': '$fun': CONVERGED IN '$ziter' ITERATION'
            else echo ' '$script': '$fun': CONVERGED IN '$ziter' ITERATIONS'; fi
            echo ' __________________________________________________________'
          fi
          break
        fi
      else
        if [[ $verb != "-verb0" ]]
        then
          echo ' __________________________________________________________________'
          echo
          echo ' '$script': '$fun': NO CONVERGENCE AFTER '$ziter' ITERATIONS'
          echo ' __________________________________________________________________'
        fi
      fi
      sign1old=$sign1
      sign2old=$sign2
      sign3old=$sign3
    done
  
    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' 'complete' $iter 1 $itermax 79 "-"
    fi
  
    if [[ -e '+stopitnow!' ]]
    then 
      \mv '+stopitnow!' '+stopitnow!stopped' 2>&1; chk_rc
      echo; echo ' '$script': '$fun': USER REQUESTED TO STOP NOW AT '$ziter' ITERATIONS...'; echo; exit 99
    fi
  
    \cp sm.*.obs*smf*.cat $subdiriterations 2>&1; chk_rc
  
# Move extraction results in a subdirectory.
  
    if [[ ! -e $subdircatalogs ]]; then \mkdir -p $subdircatalogs 2>&1; chk_rc; fi
  
    if [[ `echo *.'sw'*'final'*'reli'????*.'cat'` != '*.sw*final*reli????*.cat' ]]
    then
      \mv *.sw*final*reli????*.cat $subdircatalogs 2>&1; chk_rc
    fi
    if [[ `echo *.'sw'*'semif'*'relitent'*.'cat'` != '*.sw*semif*relitent*.cat' ]]
    then
      \mv *.sw*semif*relitent*.cat $subdircatalogs 2>&1; chk_rc
    fi
    if [[ `echo 'sm'.*.'dat'` != 'sm.*.dat' ]]
    then
      \mv sm.*.dat $subdircatalogs 2>&1; chk_rc
    fi
  
    if [[ ! -e $subdirvisuals ]]; then \mkdir -p $subdirvisuals 2>&1; chk_rc; fi
  
    if [[ `echo 'sm.'*.'obs'*'bg'*'reli'????*'.fits'` != 'sm.*.obs*bg*reli????*.fits' ]]
    then
      \mv sm.*.obs*bg*reli????*.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo 'sm.'*.'obs'*'mo'*'reli'????*'.fits'` != 'sm.*.obs*mo*reli????*.fits' ]]
    then
      \mv sm.*.obs*mo*reli????*.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo *.[do][eb][ts]'.bs.fits'` != '*.[do][eb][ts].bs.fits' ]]
    then
      \mv *.[do][eb][ts].bs.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo *.[do][eb][ts]'.bs.fs.fits'` != '*.[do][eb][ts].bs.fs.fits' ]]
    then
      \mv *.[do][eb][ts].bs.fs.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo *.[do][eb][ts]'.'cb*'.fits'` != '*.[do][eb][ts].cb*.fits' ]]
    then
      \mv *.[do][eb][ts].cb*.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo *.'flat'*'.fits'` != '*.flat*.fits' ]]
    then
      \mv *.flat*.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo 'sm.'*.[do][eb][ts]'.foots.fits'` != 'sm.*.[do][eb][ts].foots.fits' ]]
    then
      \cp sm.*.[do][eb][ts].foot[sa].fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo 'sm.'*.[do][eb][ts]'.noise.fits'` != 'sm.*.[do][eb][ts].noise.fits' ]]
    then
      \mv sm.*.[do][eb][ts].noise.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ `echo *'.mask.s~max.w'*'.fits'` != '*.mask.s~max.w*.fits' ]]
    then
      \mv *.mask.s~max.w*.fits $subdirvisuals 2>&1; chk_rc
    fi
    if [[ $flattening != 'yes' && $flattening != 'done' ]]
    then
      if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi
      for (( i=1; i <= $nwaves; i++ ))
      do
        \cp 'flatfoot.'${wave[i]}'.fits' $subdirinterface 2>&1; chk_rc
      done
    fi
  fi

  measure_end=`date +%s`; measure_time=$((measure_end - measure_beg))
  echo; echo ' GETSOURCES: '$measure_time' SECONDS'
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

FLATTEN_IMAGES ()
{
  local funo=$fun; fun='FLATTEN_IMAGES'; title=$script': => (0) '\'$fun\'
  echo; echo -n ' '$title  ##; if [[ $verb == "-verb2" ]]; then sleep 1; fi
  if [[ $flattening != "yes" ]]; then echo ' ~~~~~~~~~~~> skipping...'; fun=$funo; return 0; else echo; fi
  flatten_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  local flatiter; local lobound; local hibound
  nprogress=0
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    subdirflattening=${dirmono[i]}'/+flattening'
    if [[ ! -e "$subdirflattening" ]]; then \mkdir -p $subdirflattening 2>&1; chk_rc; fi
    \cp ${detectionclone[i]}'.fits' ${detectionclone[i]}'.originaltmp.fits' 2>&1; chk_rc
    \cp ${detectionclone[i]}'.fs+.fits' ${detectionclone[i]}'.fs+.originaltmp.fits' 2>&1; chk_rc
    \cp ${detectionclone[i]}'.fs+.fits' ${detectionclone[i]}'.fits' 2>&1; chk_rc
    iniobsfoots=$pathinitial'/+interface/flatfoot.'${wave[i]}'.fits'
    inifilamentsmasks=$pathinitial'/+interface/'$prefix'.'${wave[i]}'.det.filaments.masks.fits'
    iniobsfootfm[i]=$pathinitial'/+interface/flatfoot.'${wave[i]}'.sources+filaments.fits'
 
    if [[ ! -e $iniobsfoots ]]
    then echo; echo ' '$script': '$fun': ERROR:'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo ' INFO: File with initial measurement footprints not found:'
      echo '       '\'$iniobsfoots\'
      echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
      echo; fun=$funo; return 99
    fi
    
    if [[ $filaments == "yes" ]]
    then
      if [[ ! -e $inifilamentsmasks ]]
      then echo; echo ' '$script': '$fun': ERROR:'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo ' INFO: File with initial filament masks not found:'
        echo '       '\'$inifilamentsmasks\'
        echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        echo; fun=$funo; return 99
      fi
      $path'/operate' $iniobsfoots + $inifilamentsmasks -o ${iniobsfootfm[i]} $verb; chk_rc
    else
      \cp $iniobsfoots ${iniobsfootfm[i]} 2>&1; chk_rc
    fi
    
    smooma=$(echo "scale=20; 4.0*${beam[i]}" | bc); chk_rc   ###########; smooma=${smooma%.*}   #<-- make the number integer
    smoobsfoots[i]='flatfoot.'${wave[i]}'.c'$smooma'.fits'
 
    'CONVOLVE_MASKS' $smooma ${iniobsfootfm[i]} ${smoobsfoots[i]}; chk_rc
                   
# After the convolution, there may appear small connected clusters of zeros between the masked areas,
# better to remove them to improve interpolation under the masks; this is done here using some image manipulations.

    numcle=$(echo "scale=20; 2.0*(${beam[i]}^2+${srcmaxsize[i]}^2)/$sqpixas" | bc); chk_rc
    numcle=${numcle%.*}   #<-- make the number integer
    
    $path'/modfits' negate           ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' addconst 1.001   ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' maximum 1 n      ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' minimum 0.5 y    ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' clean4 $numcle 0 ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' negate           ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' addconst 1.000   ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc
    $path'/modfits' minimum 0.5 y    ${smoobsfoots[i]} -o ${smoobsfoots[i]} $verb; chk_rc

    $path'/operate' ${smoobsfoots[i]} x ${imageomask[i]} -o ${smoobsfoots[i]} $verb; chk_rc

# Will do the flattening only if the image is large enough compared to the masks of sources and filaments.

    $path'/imgstat' savein -nomed ${smoobsfoots[i]} ${imageomask[i]} $verb; chk_rc  

    read min max mea med totsumfoots sig skew kurt edgemean < '.+imgstat2'; chk_rc; \rm '.+imgstat2' 2>&1; chk_rc

    $path'/imgstat' savein -nomed ${imageomask[i]} ${imageomask[i]} $verb; chk_rc  

    read min max mea med totsumomask sig skew kurt edgemean < '.+imgstat2'; chk_rc; \rm '.+imgstat2' 2>&1; chk_rc

    areasratio=$(echo "scale=20; $totsumomask/$totsumfoots" | bc); chk_rc

    'COMPARE_NUMBERS' $areasratio '>' '2'; areasratiolarge[i]=$?
    'COMPARE_NUMBERS' $totsumomask '>' '250000'; totarealarge[i]=$?  #<-- image pixel area must be large enough (> 500x500 pixels)
  done
  
# Produce the sharpest possible "rms" image of the background.
      
  rmswin=1; winsize=$(( 2 * rmswin + 1 ))
  
# The 2nd iteration does not change the detection image. It is meant to produce the rms image again to control 
# how much the flattening maneged to really flatten the ooriginal background image.

  flatitermax=2

  for (( flatiter=1; flatiter <= $flatitermax; flatiter++ ))
  do
    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' "$script: FLATTENING" $flatiter 1 $flatitermax 79 "-"
    fi
    'LEADZEROS' 1 $flatiter zflatiter
    
    lobound=999999999.9; hibound=0.000000000

    for (( i=1; i <= $nwaves; i++ ))
    do
      smoobm=$(echo "scale=20; 4.0*${srcmaxsize[i]}" | bc); chk_rc; smoobm=${smoobm%.*}  #<-- make the number integer
      smoobw=$(echo "scale=20; 30.0*$winsize*$dxas"  | bc); chk_rc; smoobw=${smoobw%.*}  #<-- make the number integer
      if [[ $smoobm -lt $smoobw ]]; then smoobm=$smoobw; fi
      addpx=$(echo "scale=20; 1.5*$smoobm/$dxas" | bc); chk_rc
      rmsimagename[i]=${detectionclone[i]}'.cb.w'$winsize'.rms'
      wkimagename[i]=${detectionclone[i]}'.wk.w'$winsize'.rms'
      flatfactimage[i]=${detectionclone[i]}'.flatfact.c'$smoobm
      subdirflattening=${dirmono[i]}'/+flattening'

# Flattening is done only if the image is large enough compared to the masks of sources and filaments.

      if [[ ${areasratiolarge[i]} -eq 1 && ${totarealarge[i]} -eq 1 && $doflatten != "no" && $doflatten != "+" ]]
      then
        $path'/cleanbg' $navecln ${detectionclone[i]} ${iniobsfootfm[i]} -o ${detectionclone[i]}'.cb' $verb; chk_rc
        $path'/imgstat' rms $rmswin 1 ${detectionclone[i]}'.cb' ${imageomask[i]} -o ${rmsimagename[i]} $verb; chk_rc
        $path'/imgstat' med 10 ${rmsimagename[i]} ${imageomask[i]} -o ${rmsimagename[i]} $verb; chk_rc
        $path'/expanda' 1 ${rmsimagename[i]} ${imageomask[i]} -o ${rmsimagename[i]} $verb; chk_rc

        'CLEAR_IMAGE_BORDERS' border $bpixmskp2 ${smoobsfoots[i]} ${smoobsfoots[i]}; chk_rc

        $path'/cleanbg' $navecln ${rmsimagename[i]} ${smoobsfoots[i]} -o ${rmsimagename[i]} $verb; chk_rc
        $path'/imgstat' med 10 ${rmsimagename[i]} ${imageomask[i]} -o ${rmsimagename[i]} $verb; chk_rc

        'CLEAR_IMAGE_BORDERS' border $bpixmsk ${rmsimagename[i]} ${rmsimagename[i]}; chk_rc

# Correct rms image's artifacts that may exist by cutting them off (outside the mean +|- 5 x sigma level).

        $path'/imgstat' savein -nomed ${rmsimagename[i]} ${imageomask[i]} $verb; chk_rc  
      
        read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
        \rm '.+imgstat2' 2>&1; chk_rc
        rmsmn=$(echo "scale=20; $mea-5.0*$sig" | bc); chk_rc
        rmsmx=$(echo "scale=20; $mea+5.0*$sig" | bc); chk_rc
      
        $path'/modfits' min $rmsmn n ${rmsimagename[i]} -o ${rmsimagename[i]} $verb; chk_rc
        $path'/modfits' max $rmsmx n ${rmsimagename[i]} -o ${rmsimagename[i]} $verb; chk_rc
     
# Expand the masked area and convolve the rms image.
     
        'CLEAR_IMAGE_BORDERS' border $bpixmskp4 ${imageomask[i]} ${imageomask[i]}'.m'; chk_rc
  
        $path'/expanda' 1 ${rmsimagename[i]} ${imageomask[i]}'.m' -o ${flatfactimage[i]} $verb; chk_rc
  
        'CONVOLVE_IMAGE' expand border $addpx $smoobm ${flatfactimage[i]} ${flatfactimage[i]}; chk_rc
  
        $path'/imgstat' savein -nomed ${flatfactimage[i]} ${imageomask[i]} $verb; chk_rc  
        
        read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc; \rm '.+imgstat2' 2>&1; chk_rc

# Make sure the maximum is close to 1.0, to avoid scaling images by very large or very small factors.

        $path'/modfits' div $max ${flatfactimage[i]} -o ${flatfactimage[i]} $verb; chk_rc

# Flattening images are now limited in dynamic range (max/min < 20).

        rmsmin[i]=$(echo "scale=20; 1/20" | bc); chk_rc

# Finally divide the detection image by the flat-factor image to flatten.

        if [[ $flatiter -eq 1 ]]
        then
          $path'/operate' ${detectionclone[i]} % ${flatfactimage[i]} -o ${detectionclone[i]} $verb; chk_rc
        fi

# Copy some images under different names to preserve them in the iterations.

        $path'/operate' ${rmsimagename[i]} x ${imageomask[i]} -o $subdirflattening'/'${rmsimagename[i]}'.'$zflatiter $verb; chk_rc
  
        $path'/operate' ${flatfactimage[i]} x ${imageomask[i]} -o $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter $verb; chk_rc
        $path'/modfits' min ${rmsmin[i]} n $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter \
                                        -o $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter $verb; chk_rc
        
        $path'/operate' ${detectionclone[i]} x ${imageomask[i]} -o $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter \
                        $verb; chk_rc
        $path'/modfits' min 0 y $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter \
                             -o $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter $verb; chk_rc
        
        \rm ${wkimagename[i]}'.fits' 2>&1; chk_rc
      else
        if [[ $flatiter -eq 1 ]]
        then
          if [[ $doflatten == "+" ]]
          then
            \cp ${detectionclone[i]}'.flatfactor.(+).fits' ${flatfactimage[i]}'.fits' 2>&1; chk_rc
            $path'/operate' ${detectionclone[i]} % ${flatfactimage[i]} -o ${detectionclone[i]} $verb; chk_rc
          else
            $path'/modfits' mul 0 ${imageomask[i]} -o ${flatfactimage[i]} $verb; chk_rc
            $path'/modfits' add 1 ${flatfactimage[i]} -o ${flatfactimage[i]} $verb; chk_rc
          fi
        fi
      fi

# Check convergence of the iterations.
    
      $path'/imgstat' savein -nomed ${flatfactimage[i]} ${imageomask[i]} $verb; chk_rc  
      
      read min max mea med totsum sig skew kurt edgemean < '.+imgstat2'; chk_rc
      \rm '.+imgstat2' 2>&1; chk_rc

      flatfmin[i]=$(echo "scale=20; 1.0-$min" | bc); chk_rc
      flatfmax[i]=$(echo "scale=20; $max-1.0" | bc); chk_rc
      if [[ ${flatfmin:0:1} == "." ]]; then flatfmin[i]='0'${flatfmin[i]}; fi
      if [[ ${flatfmax:0:1} == "." ]]; then flatfmax[i]='0'${flatfmax[i]}; fi
      
      'COMPARE_NUMBERS' ${flatfmin[i]} '<=' $lobound; rsltlo=$?
      'COMPARE_NUMBERS' ${flatfmax[i]} '>=' $hibound; rslthi=$?
      if [[ $rsltlo -eq 1 ]]; then lobound=${flatfmin[i]}; fi
      if [[ $rslthi -eq 1 ]]; then hibound=${flatfmax[i]}; fi
    done

    'COMPARE_NUMBERS' $lobound '<' '0.003'; rsltlo=$?
    'COMPARE_NUMBERS' $hibound '<' '0.003'; rslthi=$?
    if [[ $rsltlo -eq 1 && $rslthi -eq 1 ]]
    then
      break
    fi
  done

  if [[ $verb == "-verb0" ]]
  then 
    'PROGRESS_BAR' 'complete' $flatiter 1 $flatitermax 79 "-"
  fi

  for (( i=1; i <= $nwaves; i++ ))
  do
    subdirflattening=${dirmono[i]}'/+flattening'

    if [[ ${areasratiolarge[i]} -eq 1 && ${totarealarge[i]} -eq 1 && $doflatten != "no" && $doflatten != "+" ]]
    then
      $path'/operate' ${rmsimagename[i]} x ${imageomask[i]} -o $subdirflattening'/'${rmsimagename[i]}'.'$zflatiter $verb; chk_rc

      $path'/operate' ${flatfactimage[i]} x ${imageomask[i]} -o $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter $verb; chk_rc
      $path'/modfits' min ${rmsmin[i]} n $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter \
                                      -o $subdirflattening'/'${flatfactimage[i]}'.'$zflatiter $verb; chk_rc

      $path'/operate' ${detectionclone[i]} x ${imageomask[i]} -o $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter \
                      $verb; chk_rc
      $path'/modfits' min 0 y $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter \
                           -o $subdirflattening'/'${detectionclone[i]}'.flattened.'$zflatiter $verb; chk_rc
        
      \rm ${rmsimagename[i]}'.fits' 2>&1; chk_rc
      \rm ${flatfactimage[i]}'.fits' 2>&1; chk_rc
      \mv ${smoobsfoots[i]} $subdirflattening'/'${smoobsfoots[i]} 2>&1; chk_rc
    fi
    
    $path'/operate' ${detectionclone[i]}'.fs+.originaltmp' % ${detectionclone[i]} \
                 -o $subdirflattening'/'${detectionclone[i]}'.flatfactor' $verb; chk_rc

    $path'/expanda' 1 $subdirflattening'/'${detectionclone[i]}'.flatfactor' ${imageomask[i]} \
                   -o $subdirflattening'/'${detectionclone[i]}'.flatfactor' $verb; chk_rc  

    $path'/operate' ${detectionclone[i]}'.fs+.originaltmp' x ${imageomask[i]} \
                 -o $subdirflattening'/'${detectionclone[i]}'.fs+.original+' $verb; chk_rc

    $path'/modfits' min 0 y $subdirflattening'/'${detectionclone[i]}'.fs+.original+' \
                 -o $subdirflattening'/'${detectionclone[i]}'.fs+.original+' $verb; chk_rc

    \mv ${detectionclone[i]}'.originaltmp.fits' ${detectionclone[i]}'.original.fits' 2>&1; chk_rc
    \mv ${detectionclone[i]}'.fs+.originaltmp.fits' ${detectionclone[i]}'.fs+.original.fits' 2>&1; chk_rc
  done

  flatten_end=`date +%s`; flatten_time=$((flatten_end - flatten_beg))
  echo; echo ' GETSOURCES: '$flatten_time' SECONDS'
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

VISUALIZE_SOURCES ()
{
  local funo=$fun; fun='VISUALIZE_SOURCES'; title=$script': => (6) '\'$fun\'; echo; echo -n ' '$title
  if [[ $visualizing == "no" ]]; then echo ' ~~~~> skipping...'; fun=$funo; return 0; else echo; fi
  visual_beg=`date +%s`; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
  nprogress=0

  nsbeg=0; nsbeams=0; sfxx=''
  {
  while read filename alltherest
  do
    if [[ ${filename:0:1} == '#' ]]
    then
      if [[ $alltherest != "" ]]
      then
        'POSITION' 'scale factor = ' "$alltherest"; sfpos=$returnposition
        if [[ $sfpos -gt 0 ]]
        then
          sfxx="scale factor = "; length=${#sfxx}; n1=$(( sfpos + length - 1 ))
          sfactor=${alltherest:n1:22}
        fi
      fi
    else
      'POSITION' '.sw.det.' "$filename"; swdet=$returnposition
      if [[ $swdet -gt 0 ]]
      then
        swdetxx=".sw.det."; length=${#swdetxx}; n1=$(( swdet + length - 1 ))
        nsca=${filename:n1:2}; if [[ ${nsca:0:1} == '0' ]]; then nsca=${nsca:1}; fi
        if [[ $nsbeg -eq 0 ]]; then nsbeg=$nsca; fi; nsbeams=$nsca
        nscbeam[nsca]=${filename:n1:12}
        sbeam[nsca]=${nscbeam[nsca]:4:6}
      fi
    fi
  done
  } < $filecombining

  if [[ $sfxx == "" ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo ' INFO: Scale factor not found in:'
    echo '       '\'$filecombining\'
    echo ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    echo; fun=$funo; return 99
  fi
  
  if [[ ${nsbeg:0:1} == '0' ]]; then nsbeg=${nsbeg:1}; fi

  catsemifinal=$subdircatalogs'/'$prefix'.sw.semif.relitent.cat'
  catrelitent=$subdircatalogs'/'$prefix'.sw.final.relitent.ok.cat'
  catreliable=$subdircatalogs'/'$prefix'.sw.final.reliable.ok.cat'

  if [[ $filaments == "yes" ]]
  then
    'DEFINE_SKELETON_LEVELS'
  fi
  
  for (( i=1; i <= $nwaves; i++ ))
  do
    if [[ $verb == "-verb0" ]]
    then 
      'PROGRESS_BAR' "$script: ELLIPSING" $i 1 $nwaves 79 "-"
    fi                                                               

# Improve background image by taking maximum of the two different estimates of background images.

    inputbgname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg.reliable'
    inputbgfsname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg.fs.reliable'
    improvedbgname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg2.reliable'
    improvedbgfsname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg2.fs.reliable'
    
    $path'/operate' $inputbgname g $subdirvisuals'/'${cbobsimage[i]} -o $improvedbgname $verb; chk_rc
    $path'/operate' $inputbgfsname g $subdirvisuals'/'${cbobsimage[i]}'.fs' -o $improvedbgfsname $verb; chk_rc

    smoobm=$(echo "scale=20; sqrt($beammax*$beammax-${beam[i]}*${beam[i]})" | bc); chk_rc
                                      
    'COMPARE_NUMBERS' $smoobm '=' '0'; rslt=$?
    if [[ $rslt -eq 1 ]]
    then
      if [[ $verb != "-verb0" ]]; then echo; echo ' Copying '$improvedbgname'.fits to *.smo.fits...'; fi
      \cp $improvedbgname'.fits' $improvedbgname'.smo.fits' 2>&1; chk_rc
    else
      addpx=$(echo "scale=20; 2.0*$smoobm/$dxas" | bc); chk_rc
    
      $path'/expanda' 1 $improvedbgname ${imageomask[i]} -o $improvedbgname'.smo' $verb; chk_rc
      $path'/modfits' expand $addpx $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
      $path'/fftconv' $smoobm 0 $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
      $path'/modfits' border -$addpx $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
    fi

    inputbgname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg.relitent'
    inputbgfsname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg.fs.relitent'
    improvedbgname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg2.relitent'
    improvedbgfsname=$subdirvisuals'/sm.'${measuremtclone[i]}'.bg2.fs.relitent'
    
    $path'/operate' $inputbgname g $subdirvisuals'/'${cbobsimage[i]} -o $improvedbgname $verb; chk_rc
    $path'/operate' $inputbgfsname g $subdirvisuals'/'${cbobsimage[i]}'.fs' -o $improvedbgfsname $verb; chk_rc

    smoobm=$(echo "scale=20; sqrt($beammax*$beammax-${beam[i]}*${beam[i]})" | bc); chk_rc
                                      
    'COMPARE_NUMBERS' $smoobm '=' '0'; rslt=$?
    if [[ $rslt -eq 1 ]]
    then
      if [[ $verb != "-verb0" ]]; then echo; echo ' Copying '$improvedbgname'.fits to *.smo.fits...'; fi
      \cp $improvedbgname'.fits' $improvedbgname'.smo.fits' 2>&1; chk_rc
    else
      addpx=$(echo "scale=20; 2.0*$smoobm/$dxas" | bc); chk_rc
    
      $path'/expanda' 1 $improvedbgname ${imageomask[i]} -o $improvedbgname'.smo' $verb; chk_rc
      $path'/modfits' expand $addpx $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
      $path'/fftconv' $smoobm 0 $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
      $path'/modfits' border -$addpx $improvedbgname'.smo' -o $improvedbgname'.smo' $verb; chk_rc
    fi
    
# Overlay ellipses onto input image in places where the sources were found. Create a sub-directory first.

    partdet=${detectionclone[i]/$prefix./}
    partobs=${measuremtclone[i]/$prefix./}
    partdetfs=${detectionclone[i]/$prefix./}'.fs'
    partobsfs=${measuremtclone[i]/$prefix./}'.fs'
    partmea=${imeasurebs[i]/$prefix./}'.fs'
    partmas=${imaskingbs[i]/$prefix./}'.fs'
    
    thick=$(echo "scale=2; $pixmax/200" | bc); chk_rc

    'COMPARE_NUMBERS' $thick '<' '2.0'; rslt=$?
    if [[ $rslt -eq 1 ]]; then thick='2.0'; fi
    
    $path'/operate' ${imagebsomask[i]} x $subdirvisuals'/'${obsfootprints[i]} -o $subdirvisuals'/'${obsfootprints[i]} $verb; chk_rc
    $path'/operate' ${imagebsomask[i]} x $subdirvisuals'/'${obsfootprinta[i]} -o $subdirvisuals'/'${obsfootprinta[i]} $verb; chk_rc

# Reliable catalogs.

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $sreliable $snratio1min $snratio2min $catreliable \
                     ${measuremtclone[i]} 1.0 1.1 $thick -o $finellreliable'.'$partobs $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $sreliable $snratio1min $snratio2min $catsemifinal \
                     ${measuremtclone[i]} 1.0 1.1 '+'$thick -o $finfooreliable'.'$partobs $verb; chk_rc

# Relitent catalogs.

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                     ${measuremtclone[i]} 1.0 1.1 $thick -o $finellrelitent'.'$partobs $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} 0.0 $stentative 0.01 0.01 $catrelitent \
                     ${measuremtclone[i]}'.fs' 1.0 1.1 $thick -o $finellrelitent'.'$partobsfs'!' $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                     ${measuremtclone[i]}'.fs' 1.0 1.1 $thick -o $finellrelitent'.'$partobsfs $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catsemifinal \
                     ${measuremtclone[i]}'.fs' 1.0 1.1 '+'$thick -o $finfoorelitent'.'$partobsfs $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                     ${detectionclone[i]}'.fs' 1.0 1.1 $thick -o $finellrelitent'.'$partdetfs $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                     $subdirvisuals'/'${imeasurebs[i]}'.fs' 1.0 1.1 $thick -o $finellrelitent'.'$partmea $verb; chk_rc

    $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                     $subdirvisuals'/'${imeasurebs[i]}'.fs' 1.0 1.2 '-'$thick -o $findotrelitent'.'$partmea $verb; chk_rc

    if [[ $filaments == "yes" ]]
    then
      'DEFINE_FILAMENTS_SCALES' ${beam[i]}
      
      for (( kk=0; kk <= $nsklevs; kk++ ))
      do
        zkk=${zsklev[kk]}
        for (( l=0; l <= $nsskel; l++ ))
        do
          zl=${zfilscale[l]}'as'
          if [[ -e ${dirmono[i]}'/+filaments/+profiles/'${detectionclone[i]}'.skeletons.'$zl'.c'$zkk'.thick.fits' ]]
          then
            $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                             ${dirmono[i]}'/+filaments/+profiles/'${detectionclone[i]}'.skeletons.'$zl'.c'$zkk'.thick' \
                             1.0 1.2 -$thick -o $findotrelitent'.'$partobs'.sk.'$zl'.c'$zkk $verb; chk_rc
          fi
          if [[ -e ${dirmono[i]}'/+filaments/+profiles/'${measuremtclone[i]}'.filaments.'$zl'.skeletons.'$zl'.c'$zkk'.fits' ]]
          then
            $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                             ${dirmono[i]}'/+filaments/+profiles/'${measuremtclone[i]}'.filaments.'$zl'.skeletons.'$zl'.c'$zkk \
                             1.0 1.1 $thick -o $finellrelitent'.'$partobs'.fi.'$zl'.sk.'$zl'.c'$zkk $verb; chk_rc
          fi
        done
      done
      kk=0
      zkk=${zsklev[kk]}
      for (( l=0; l <= $nsskel; l++ ))
      do
        zl=${zfilscale[l]}'as'
        if [[ -e ${dirmono[i]}'/+filaments/+profiles/'${measuremtclone[i]}'.filaments+.m.skeletons.'$zl'.c'$zkk'.fits' ]]
        then
          $path'/ellipses' getsources $i ${beam[i]} $goodmin $stentative $snratio1min $snratio2min $catrelitent \
                           ${dirmono[i]}'/+filaments/+profiles/'${measuremtclone[i]}'.filaments+.m.skeletons.'$zl'.c'$zkk \
                           1.0 1.1 $thick -o $finellrelitent'.'$partobs'.fi+.m.sk.'$zl'.c'$zkk $verb; chk_rc
        fi
      done
    fi
  done

  if [[ $verb == "-verb0" ]]
  then 
    'PROGRESS_BAR' 'complete' $nwaves 1 $nwaves 79 "-"
  fi

  visual_end=`date +%s`; visual_time=$((visual_end - visual_beg))
  echo; echo ' GETSOURCES: '$visual_time' SECONDS'
  fun=$funo
}
#___________________________________________________________________________________________________________________________________

FINISH ()
{                                         
  local funo=$fun; fun='FINISH'; title=$script': => (7) '\'$fun\'
  echo; echo ' '$title; if [[ $verb == '-verb2' ]]; then echo; echo '   Removing temporary files...' ; fi
  finish_beg=`date +%s`; finish_wait=0
  local i; local j; local noisebgr=0; local position=0; local notdetec=0; local spurious=0; local substruc=0
  local totalbad=0; local totalgod=0; local finish_wait0; local finish_wait1
                  
  if [[ -e 'z0.fits' ]]; then \rm 'z0.fits' 2>&1; chk_rc; fi

# Make sure all the files are readable by all (sometimes on some systems they are not).

  chmod a+r *

  if [[ $toofewbgpixels -gt 0 && ($flattening == 'yes' || $flattening == 'done') ]]
  then
    echo
    echo ' GETSOURCES:   INFO: An abnormal condition TOO FEW BACKGROUND PIXELS was '
    echo ' GETSOURCES:         encountered when cleaning the single-scale detection'
    echo ' GETSOURCES:         image #'$toofewbgpixels' (scale '$toofewbgpixscale' arcsec). Most likely, images'
    echo ' GETSOURCES:         are too small for the largest sources or structures.'
    echo ' GETSOURCES:                                                             '
    echo ' GETSOURCES: ADVICE: Make sure that prepared images are large enough:'
    echo ' GETSOURCES:         ~ 20 times the maximum source size and ~ 4 times the'
    echo ' GETSOURCES:         maximum filament length in all images. Never cut out'
    echo ' GETSOURCES:         very small areas for source or filament extractions.'
  fi

# Produce statistics for sources in the semifinal catalog; the summary file should have been created by FINALCAT.

  if [[ -e '+log.SUMMARY' ]]
  then
    {
    read name totalbad; read name noisebgr; read name notdetec; read name spurious
    read name position; read name toolarge; read name totalgod; read name substruc
    for (( i=1; i <= $nwaves; i++ )); do read name foomax[i]; done
    } < '+log.SUMMARY'
    
    lenbad=${#totalbad}; lennoi=${#noisebgr}; lenpos=${#position}
    lenbig=${#toolarge}; lendet=${#notdetec}; lenspu=${#spurious}
    lensub=${#substruc}; lentot=${#totalgod}
    if [[ $lentot -gt $lenbad ]]; then lenmax=$lentot; else lenmax=$lenbad; fi
    lenbx=$(( lenmax - lenbad )); if [[ $lenbx -gt 0 ]]; then for (( i=1; i <= lenbx; i++ )); do totalbad=' '"$totalbad"; done; fi
    lennx=$(( lenmax - lennoi )); if [[ $lennx -gt 0 ]]; then for (( i=1; i <= lennx; i++ )); do noisebgr=' '"$noisebgr"; done; fi
    lendx=$(( lenmax - lendet )); if [[ $lendx -gt 0 ]]; then for (( i=1; i <= lendx; i++ )); do notdetec=' '"$notdetec"; done; fi
    lensx=$(( lenmax - lenspu )); if [[ $lensx -gt 0 ]]; then for (( i=1; i <= lensx; i++ )); do spurious=' '"$spurious"; done; fi
    lenpx=$(( lenmax - lenpos )); if [[ $lenpx -gt 0 ]]; then for (( i=1; i <= lenpx; i++ )); do position=' '"$position"; done; fi
    lenlx=$(( lenmax - lenbig )); if [[ $lenlx -gt 0 ]]; then for (( i=1; i <= lenlx; i++ )); do toolarge=' '"$toolarge"; done; fi
    lentx=$(( lenmax - lentot )); if [[ $lentx -gt 0 ]]; then for (( i=1; i <= lentx; i++ )); do totalgod=' '"$totalgod"; done; fi
    lenux=$(( lenmax - lensub )); if [[ $lenux -gt 0 ]]; then for (( i=1; i <= lenux; i++ )); do substruc=' '"$substruc"; done; fi
    chorline=''; for (( i=1; i <= lenmax; i++ )); do chorline='_'"$chorline"; done
    cverline=''; for (( i=1; i <= lenmax; i++ )); do cverline=' '"$cverline"; done
    echo
    echo ' GETSOURCES:  Extraction prefix: '$prefix
    echo ' GETSOURCES:  ____________________________'"$chorline"'__ '
    echo ' GETSOURCES: |                            '"$cverline"'  |'
    echo ' GETSOURCES: |   BAD DETECTIONS EXCLUDED: '"$totalbad"'  |'
    echo ' GETSOURCES: |                            '"$cverline"'  |'
    echo ' GETSOURCES: |       Background or noise: '"$noisebgr"'  |'
    echo ' GETSOURCES: |  Too few detectable waves: '"$notdetec"'  |'
    echo ' GETSOURCES: |    Likely spurious source: '"$spurious"'  |'
    echo ' GETSOURCES: |      Position is occupied: '"$position"'  |'
    echo ' GETSOURCES: |       Larger than desired: '"$toolarge"'  |'
    echo ' GETSOURCES: |                            '"$cverline"'  |'
    echo ' GETSOURCES: |    NUMBER OF GOOD SOURCES: '"$totalgod"'  |'
    echo ' GETSOURCES: |                            '"$cverline"'  |'
    echo ' GETSOURCES: |  Source is sub-structured: '"$substruc"'  |'
    echo ' GETSOURCES: |____________________________'"$chorline"'__|'
    echo ' GETSOURCES:'
    
    lenfoomax=0
    lenfilmax=0
    for (( i=1; i <= $nwaves; i++ ))
    do
      echo ${foomax[i]} > $prefix'.'${wave[i]}'.srcmaxsize'
      lenfoo=${#foomax[i]}; if [[ $lenfoo -gt $lenfoomax ]]; then lenfoomax=$lenfoo; fi
      if [[ ${filmaxsize[i]} -ge ${filmaxsizeo[i]} ]]
      then filmaxx[i]=${filmaxsize[i]}
      else filmaxx[i]=${filmaxsizeo[i]}
      fi
      lenfil=${#filmaxx[i]}; if [[ $lenfil -gt $lenfilmax ]]; then lenfilmax=$lenfil; fi
    done
    
    for (( i=1; i <= $nwaves; i++ ))
    do
      filmax=${filmaxx[i]}
      lenfoo=${#foomax[i]}; len=$(( lenfoomax - lenfoo ))
      if [[ $len -gt 0 ]]; then for (( l=1; l <= len; l++ )); do foomax[i]=' '"${foomax[i]}"; done; fi
      lenfil=${#filmaxx[i]}; len=$(( lenfilmax - lenfil ))
      if [[ $len -gt 0 ]]; then for (( l=1; l <= len; l++ )); do filmaxx[i]=' '"${filmaxx[i]}"; done; fi

      echo ' GETSOURCES:  Largest source and filament at '${wave[i]}' um (FWHM): '"${foomax[i]}"' and '"${filmaxx[i]}"' arcsec' 
    done
  fi
  
  if [[ $flattening != 'yes' && $flattening != 'done' ]]
  then
    if [[ ! -e $subdirinterface ]]; then \mkdir -p $subdirinterface 2>&1; chk_rc; fi
    for (( i=1; i <= $nwaves; i++ ))
    do                        
      if [[ -e $prefix'.'${wave[i]}'.srcmaxsize' ]]
      then \mv $prefix'.'${wave[i]}'.srcmaxsize' $subdirinterface 2>&1; chk_rc
      fi
      if [[ $filaments == "yes" && -e ${dirmono[i]} && $originpath != ${dirmono[i]} ]]
      then 
        \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.filmaxsize' $subdirinterface 2>&1; chk_rc
##        \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.fits' $subdirinterface 2>&1; chk_rc
##        \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.masks.fits' $subdirinterface 2>&1; chk_rc
        \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.fits' $subdirinterface 2>&1; chk_rc

        'DEFINE_FILAMENTS_SCALES' ${beam[i]}

        for (( l=0; l <= $nsskel; l++ ))
        do
          zl=${zfilscale[l]}'as'
          if [[ -e ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.skeletons.'$zl'.fits' ]]
          then \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.skeletons.'$zl'.fits' $subdirinterface 2>&1; chk_rc
          fi
        done
##        if [[ `echo ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.'????'as.fits'` != \
##              ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.????as.fits' ]]
##        then 
##          \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.det.filaments.'????'as.fits' $subdirinterface 2>&1; chk_rc
##        fi
        if [[ `echo ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.'????'as.fits'` != \
              ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.????as.fits' ]]
        then 
          \cp ${dirmono[i]}'/+interface/'$prefix'.'${wave[i]}'.obs.filaments.'????'as.fits' $subdirinterface 2>&1; chk_rc
        fi
      fi
    done

    if [[ $measuring == "yes" ]]
    then
      if [[ $nwaves -eq 1 && $combinedinitialextraction == 'no' ]]
      then
        echo ' GETSOURCES:  _________________________________________________________________ '
        echo ' GETSOURCES: |                                                                 |'
        echo ' GETSOURCES: |  Note that this was just an INITIAL monochromatic extraction.   |'
        echo ' GETSOURCES: |  One should do the same for images in other wavebands (if any), |'
        echo ' GETSOURCES: |  and then perform a combined multi-wavelength extraction to     |'
        echo ' GETSOURCES: |  complete the INITIAL extraction.                               |'
        echo ' GETSOURCES: |                                                                 |'
        echo ' GETSOURCES: |  ONE SHOULD PROPERLY COMPLETE THE INITIAL EXTRACTION AND THEN   |'
        echo ' GETSOURCES: |  PERFORM THE FINAL EXTRACTION WITH FLATTENED DETECTION IMAGES.  |'
        echo ' GETSOURCES: |_________________________________________________________________|'
      else
        echo ' GETSOURCES:  _________________________________________________________________ '
        echo ' GETSOURCES: |                                                                 |'
        echo ' GETSOURCES: |  Note that this was just an INITIAL (not the FINAL) extraction  |'
        echo ' GETSOURCES: |  and it may have produced a number of spurious sources in the   |'
        echo ' GETSOURCES: |  areas with variable background and noise fluctuation levels.   |'
        echo ' GETSOURCES: |                                                                 |'
        echo ' GETSOURCES: |  ONE SHOULD PERFORM THE FINAL EXTRACTION WITH THE FLATTENING    |'
        echo ' GETSOURCES: |  PARAMETER SET TO Y, COMPLETING ALL EXTRACTION STEPS.           |'
        echo ' GETSOURCES: |_________________________________________________________________|'
      fi
      if [[ $savespace -eq 0 ]]
      then
        echo ' GETSOURCES:'
      fi
    fi

    if [[ $bgfisub != "yes" ]]
    then
      echo ' GETSOURCES:  _________________________________________________________________ '
      echo ' GETSOURCES: |                                                                 |'
      echo ' GETSOURCES: |  Note that this extraction was performed WITHOUT subtracting    |'
      echo ' GETSOURCES: |  any contribution of variable backgrounds and filaments. This   |'
      echo ' GETSOURCES: |  option was activated by the user in the configuration file.    |'
      echo ' GETSOURCES: |                                                                 |'
      echo ' GETSOURCES: |  THIS IS GENERALLY A DANGEROUS (NOT RECOMMENDED) OPTION AND THE |'
      echo ' GETSOURCES: |  USER MUST CLEARLY UNDERSTAND WHAT HE (SHE) IS DOING. CORRECT   |'
      echo ' GETSOURCES: |  MEASUREMENTS ARE NOT GUARANTEED WITH THIS APPROACH.            |'
      echo ' GETSOURCES: |_________________________________________________________________|'
      if [[ $savespace -eq 0 ]]
      then
        echo ' GETSOURCES:'
      fi
    fi
    
# Clean up to save disk space.
  
    answer=''
    if [[ $savespace -eq 2 && ($measuring == "yes" || \
         ($decomposing == "no" && $cleaning == "no" && $combining == "no" && \
          $detecting == "no" && $measuring == "no" && $visualizing == "no" )) ]]
    then
      echo ' GETSOURCES:  _________________________________________________________________ '
      echo ' GETSOURCES: |                                                                 |'
      echo ' GETSOURCES: |  In "+getsources.cfg" you have SAVESPACE = 2 which means that   |'
      echo ' GETSOURCES: |  you would like to remove unnecessary files and directories     |'
      echo ' GETSOURCES: |  from this INITIAL extraction. Combined "+interface" directory  |'
      echo ' GETSOURCES: |  should and will be preserved for use in the FINAL extraction.  |'
      echo ' GETSOURCES: |_________________________________________________________________|'
      echo ' GETSOURCES:'
      finish_wait1=`date +%s`
      echo -n ' GETSOURCES: Delete unnecessary files (timeout 12 hrs) (y/N)?: '; read -s -t 43200 answer; rc=$?
      finish_wait2=`date +%s`
      finish_wait=$((finish_wait2 - finish_wait1))
    
      if [[ $rc -eq 1 ]]; then answer='?'; fi
    
      if [[ ${answer:0:1} == "y" || ${answer:0:1} == "Y" ]]
      then answer='y'; echo 'yes!'; echo -n ' GETSOURCES: Deleting...'
      elif [[ ${answer:0:1} == "n" || ${answer:0:1} == "N" ]]
      then answer='n'; echo 'no!'
      else answer='n'; echo 'assuming no!'
      fi  
      
      if [[ $answer == "y" ]]
      then 
        if [[ $nwaves -eq 1 && $combinedinitialextraction == 'no' ]]
        then
          if [[ `echo *'.sw.'*` != '*.sw.*' ]]
          then 
            \rm *'.sw.'* 2>&1; chk_rc
          fi
          if [[ `echo 'sm.'*` != 'sm.*' ]]
          then 
            \rm 'sm.'* 2>&1; chk_rc
          fi
          if [[ `echo *'.'[cw][bk]'.'*'.fits'` != '*.[cw][bk].*.fits' ]]
          then 
            \rm *'.'[cw][bk]'.'*'.fits' 2>&1; chk_rc
          fi
          if [[ `echo *'.mso.fits'` != '*.mso.fits' ]]
          then 
            \rm *'.mso.fits' 2>&1; chk_rc
          fi
          if [[ -e ${maskscalesfinalsum[1]}'.hi.fits' ]]
          then
            \rm ${maskscalesfinalsum[1]}'.hi.fits' 2>&1; chk_rc
          fi
        else
          if [[ `echo *'.sw.'*` != '*.sw.*' ]]
          then 
            \rm *'.sw.'* 2>&1; chk_rc
          fi
          if [[ `echo 'sm.'*` != 'sm.*' ]]
          then 
            \rm 'sm.'* 2>&1; chk_rc
          fi
          if [[ `echo *'.c'??????'as.fits'` != '*.c??????as.fits' ]]
          then 
            \rm *'.c'??????'as.fits' 2>&1; chk_rc
          fi
          if [[ `echo *'.'[acbh][nbsi]'.fits'` != '*.[acbh][nbsi].fits' ]]
          then 
            \rm *'.'[acbh][nbsi]'.fits' 2>&1; chk_rc
          fi
          if [[ `echo *'.'[cw][bk]'.'*'.fits'` != '*.[cw][bk].*.fits' ]]
          then 
            \rm *'.'[cw][bk]'.'*'.fits' 2>&1; chk_rc
          fi
          for (( i=1; i <= $nwaves; i++ ))
          do                        
            if [[ -e ${dirmono[i]} && $originpath != ${dirmono[i]} ]]
            then 
              if [[ -e ${dirmono[i]}'/+filaments'  ]]; then \rm -R ${dirmono[i]}'/+filaments' 2>&1; chk_rc; fi
              if [[ -e ${dirmono[i]}'/+iterations' ]]; then \rm -R ${dirmono[i]}'/+iterations' 2>&1; chk_rc; fi
              if [[ -e ${dirmono[i]}'/+visuals'    ]]; then \rm -R ${dirmono[i]}'/+visuals'    2>&1; chk_rc; fi

              if [[ `echo ${dirmono[i]}'/'*'.sw.'*` != ${dirmono[i]}'/*.sw.*' ]]
              then 
                \rm ${dirmono[i]}/*'.sw.'* 2>&1; chk_rc
              fi
              if [[ `echo ${dirmono[i]}'/sm.'*` != ${dirmono[i]}'/sm.*' ]]
              then 
                \rm ${dirmono[i]}/'sm.'* 2>&1; chk_rc
              fi
              if [[ `echo ${dirmono[i]}'/'*'.mso.fits'` != ${dirmono[i]}'/*.mso.fits' ]]
              then
                \rm ${dirmono[i]}/*'.mso.fits' 2>&1; chk_rc
              fi
              if [[ `echo ${dirmono[i]}'/'*'.c'??????'as.fits'` != ${dirmono[i]}'/*.c??????as.fits' ]]
              then
                \rm ${dirmono[i]}/*'.c'??????'as.fits' 2>&1; chk_rc
              fi
              if [[ `echo ${dirmono[i]}'/'*'.'[acbh][nbsi]'.fits'` != ${dirmono[i]}'/*.[acbh][nbsi].fits' ]]
              then
                \rm ${dirmono[i]}/*'.'[acbh][nbsi]'.fits' 2>&1; chk_rc
              fi
              if [[ `echo ${dirmono[i]}'/'*'.'[cw][bk]'.'*'.fits'` != ${dirmono[i]}'/*.[cw][bk].*.fits' ]]
              then
                \rm ${dirmono[i]}/*'.'[cw][bk]'.'*'.fits' 2>&1; chk_rc
              fi
            fi
            if [[ -e ${maskscalesfinalsum[i]}'.hi.fits' ]]
            then 
              \rm ${maskscalesfinalsum[i]}'.hi.fits' 2>&1; chk_rc
            fi
          done
        fi
        if [[ `echo $subdirvisuals/$prefix'.sw.final.reliable.'*'.fits'` != $subdirvisuals'/'$prefix'.sw.final.reliable.*.fits' ]]
        then
          \rm $subdirvisuals/$prefix'.sw.final.reliable.'*'.fits' 2>&1; chk_rc
        fi
        if [[ -e "$subdirfilaments" ]]
        then 
          \rm -R $subdirfilaments 2>&1; chk_rc
        fi
        if [[ -e "$subdiriterations" ]]
        then 
          \rm -R $subdiriterations 2>&1; chk_rc
        fi
        echo ' done.'
      fi
    fi
  fi
    
# Single-scale skeletons are all removed after extractions.
    
  for (( i=1; i <= $nwaves; i++ ))
  do                        
    if [[ $savespace -ge 1 && -e ${dirmono[i]}'/+filaments/+skeletons' ]]
    then 
      \rm -R ${dirmono[i]}'/+filaments/+skeletons' 2>&1; chk_rc
    fi
  done

  finish_end=`date +%s`; finish_time=$((finish_end - finish_beg - finish_wait))
  echo; echo ' GETSOURCES: '$finish_time' SECONDS'
  fun=$funo
}
#___________________________________________________________________________________________________________________________________
#___________________________________________________________________________________________________________________________________
#___________________________________________________________________________________________________________________________________

'GET_VERSION' $*; chk_rc
{
getsources_beg=`date +%s`

for (( b=1; b <= 7; b++ ))
do echo "${banner[b]}"; done

'GET_PARAMETERS' $*; chk_rc

'GET_IMAGE_SIZES' ${detectionclone[1]}; chk_rc

'GET_SMOOTHING_BEAMS'; chk_rc

if [[ $flattening == 'yes' ]]
then
  'FLATTEN_IMAGES'; chk_rc
fi

'DECOMPOSE_IMAGES' $scale1 $nscales $sfactor; chk_rc

'CLEAN_SINGLE_SCALES'; chk_rc
                               
'COMBINE_OVER_WAVES'; chk_rc

'DETECT_ALL_SOURCES'; chk_rc

'MEASURE_PROPERTIES'; chk_rc

'VISUALIZE_SOURCES'; chk_rc

'FINISH'; chk_rc

getsources_end=`date +%s`
getsources_time=$((getsources_end - getsources_beg - finish_wait))

cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
echo
echo ' '$script': DONE: '$getsources_time' SECONDS'
echo
echo ' '$cdate
echo
} | tee -a $logfile

exit
#___________________________________________________________________________________________________________________________________
