#!/bin/bash
banner[1]='_______________________________________________________________________________'
banner[2]='                                                                               '
banner[3]='           PREPAREOBS = Prepare Observed Images for Source Extraction          '
banner[4]='              Alexander Men`shchikov, SAp IRFU CEA Saclay, France              '
banner[5]='                                Version 1.140127                               '
banner[6]='_______________________________________________________________________________'
#
# Development initiated on 2009/09/30 by A.M. (alexander.menshchikov@cea.fr)
#_________________________________________________________________________________________________________________________________

CONDITIONS ()
{
  echo '#  _____________________________________________________________________________'
  echo '# |                                                                             '
  echo '# |          PREPAREOBS = Prepare Observed Images for Source Extraction         '
  echo '# |             Alexander Men''shchikov, SAp IRFU CEA Saclay, France             '
  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 something like this:            '
  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.                     '
}
#_________________________________________________________________________________________________________________________________
#
executing="$0"; scriptname=`basename "$executing"`; script=`echo $scriptname | tr a-z A-Z`; logfile='+log.'$script
#_________________________________________________________________________________________________________________________________

USAGE ()
{
  echo
  echo '                           PREPAREOBS: USAGE SYNTAX'
  echo
  echo ' '$scriptname' PARAMETERS FILE OPTIONS'
  echo
  echo '---- PARAMETERS: <instrument> {<scanspeed>|<beamsize>} <mapmaker> <fieldname>  '
  echo
  echo '   <instrument>: Name of the instrument used to perform observations:'
  echo '                 [pacs|spire|saboca|laboca|scuba4|scuba8|sharcii|pdb1|pdb3|'
  echo '                 mambo|simba|bolocam|spitzer4|spitzer8|spitzer24|other]'
  echo '    <scanspeed>: For Herschel observations: scan speed [10|20|20p|30|60|60p]'
  echo '                 (arcsec/sec; "p" stands for PACS/SPIRE parallel mode).'
  echo '     <beamsize>: For non-Herschel observations: beam size (FWHM arcsec).'
  echo '     <mapmaker>: Name of the map-making algorithm used to create the images:'
  echo '                 [-][naive|photproj|madmap[_mosaic|_combined]|scanamorphos|'
  echo '                 romagal|coldens|other]. Add "-" for plain images or those'
  echo '                 previously extracted from the complex FITS files of the HIPE'
  echo '                 output maps or those produced by SCANAMORPHOS.'
  echo '    <fieldname>: Name of the observed field or object (for the FITS headers).'
  echo
  echo '---------- FILE: <image> ------------------------------------------------------'
  echo
  echo '        <image>: Input image in FITS format.'
  echo
  echo '------- OPTIONS: [-]<pixel> [<nx> <ny> <coord1> <coord2> <rotangle>]'
  echo
  echo '        <pixel>: Desired pixel size (arcsec) of the output images. One can use'
  echo '                 the "-" sign to skip resampling and reprojection.'
  echo '           <nx>: Number of pixels along horizontal axis of the output images.'
  echo '           <ny>: Number of pixels along vertical axis of the output images.'
  echo '       <coord1>: 1st coordinate of the projection center of the output images.'
  echo '       <coord2>: 2nd coordinate of the projection center of the output images.'
  echo '     <rotangle>: Rotation angle (east of north) of the output images.'
  echo
  echo '-------------------------------------------------------------------------------'
  echo
  echo '  NOTES. Parameters are mandatory, except the optional ones (in brackets []).'
  echo '         PREPAREOBS calls a suite of FORTRAN utilities (by A. Men`shchikov):'
  echo '         READHEAD, MODFITS, IMGSTAT, OPERATE, FFTCONV, SEPARATE, and SPLITCUBE.'
  echo '         It also uses SWARP by Emmanuel Bertin for image resampling & rotation.'
  echo
  echo '         The parameters in square brackets must be the same for all images of'
  echo '         the field that one is going to prepare (at all wavelengths). Better to'
  echo '         begin with the shortest-wavelength image and then proceed to longer'
  echo '         wavelengths.'
  echo
  echo '-------------------------------------------------------------------------------'
  echo
  echo '  SYNTAX SUMMARY:'
  echo
  echo ' prepareobs <instrument> {<scanspeed>|<beamsize>} <mapmaker> <fieldname> <image> [-]<pixel> [<nx> <ny> <coord1> <coord2> <rotangle>] [<cutfact>]'
  echo
  echo '-------------------------------------------------------------------------------'
}
#_________________________________________________________________________________________________________________________________

chk_rc () # internal function 'chk_rc' for checking return code and exiting if abnormal termination.
{
  rc=$?; if [[ "$rc" != "0" ]]; then echo; echo ' Error in '$script': '$fun': Aborted.'; exit "$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 '   Too few parameters.'; fun=$funo; exit 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 '   Too few parameters.'; fun=$funo; exit 99
  fi
  if [[ $2 != ">" && $2 != "<" && $2 != "=" && $2 != "!=" && $2 != ">=" && $2 != "<=" ]]
  then echo; echo ' '$script': '$funo': '$fun': ERROR:'; echo; echo '   Unsupported operator:' $2; fun=$funo; exit 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
}
#_________________________________________________________________________________________________________________________________

INITIALIZE ()
{
  local funo=$fun; fun='INITIALIZE'; title=$script': => '\'$fun\'
  echo; cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`; local i; local j
  echo '                         '$cdate; echo; echo ' Executing: '"$executing"
  if [[ "$1" != "" ]]; then echo; echo ' '$scriptname "$*"; fi
  nparams=${#*}; commandline="$*"
  instrument=$1; scanspeedorbeam=$2; mapmaker=$3; fieldname=$4; image=$5; pix0=$6; nx0=$7; ny0=$8; ra0=$9; dec0=${10}; rota=${11}
  
  if [[ $scanspeedorbeam != "" ]]
  then
    'COMPARE_NUMBERS' $scanspeedorbeam '=' '0.00'; rcssbs=$?

    if [[ $rcssbs -eq 1 ]]
    then
      echo; echo ' '$script': '$fun': ERROR:'
      echo; echo '   Second parameter (scan speed or beam size) is zero, which is obviously wrong...'
      exit 99
    fi
  fi
  
  if [[ $instrument == "pacs" || $instrument == "spire" ]]
  then
    scanspeed=$scanspeedorbeam
    beam=0
  else
    scanspeed=0
    beam=$scanspeedorbeam
  fi

  if [[ $ra0 == '' ]]; then ra0='00:00:00.00'; fi
  if [[ $dec0 == '' ]]; then dec0='00:00:00.0'; fi

  if [[ ${pix0:0:1} == "-" ]]
  then
    pix0=${pix0:1}
    doresample='no'
  else
    doresample='yes'
  fi

# 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 7 ]]
    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:14}; fi
    fi
    if [[ $l -eq 7 ]]; then break; fi
  done
  } < $executing

  headerinfo[1]='#  ___________________________________________________________________________________________________________________________________'
  headerinfo[2]='# |                                                                                                                                   '
  headerinfo[3]='# | PREPAREOBS = Prepare Observed Images for Source Extraction = '$versnum' = Alexander Men'\''shchikov, SAp IRFU CEA Saclay         '
  headerinfo[4]='# |___________________________________________________________________________________________________________________________________'

  'POSITION' $scriptname $executing; nsn=$returnposition; nsnm2=$(( nsn - 2 ))
  if [[ $nsn -gt 0 ]]; then path=${executing:0:nsnm2}; else path=''; fi

  if [[ $path == "" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   Trouble obtaining the path to '$script; exit 99
  fi
  if [[ $path == '/Users/amenshch/Astronomy/+Computing/+GETSOURCES' ]]
  then
    path='/Users/amenshch/bin/+GETSOURCES'
  fi
  
  'CONDITIONS' >> '+log.CONDITIONS'

  verb='-verb1'
  coosys='EQUATORIAL'
  ctype1out='RA---TAN'
  ctype2out='DEC--TAN'
  
  if [[ $pix0 != '' && $nx0 == '' && $ny0 == '' && $ra0 == '00:00:00.00' && $dec0 == '00:00:00.0' && $rota == '' ]]
  then
    nx0=10; ny0=10; rota=0
  else
    if [[ ! ($pix0 != '' && $nx0 != '' && $ny0 != '' && $ra0 != '00:00:00.00' && $dec0 != '00:00:00.0' && $rota != '') ]]
    then
      if [[ $pix0 == '' ]]
      then
        'USAGE'; exit 99
      fi
    fi
  fi
  echo; echo ' '$title

  if [[ $rota == '' ]]
  then
    rota=0
  fi

  if [[ $coosys != "" && $coosys != "EQUATORIAL" && $coosys != "GALACTIC" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   Invalid coordinate system specified: '$coosys; exit 99
  fi
  hell='/dev/null'

# Make sure that all my required utilities can be found in the system.
         
  $path'/fftconv'   : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/fftconv..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/fftconv not found or error loading shared libraries..." ; exit 99; fi
  $path'/imgstat'   : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/imgstat..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/imgstat not found or error loading shared libraries..." ; exit 99; fi
  $path'/modfits'   : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/modfits..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/modfits not found or error loading shared libraries..." ; exit 99; fi
  $path'/operate'   : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/operate..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/operate not found or error loading shared libraries..." ; exit 99; fi
  $path'/readhead'  : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/readhead..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/readhead not found or error loading shared libraries..."; exit 99; fi
  $path'/separate'  : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/separate..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/separate not found or error loading shared libraries..."; exit 99; fi
  $path'/splitcube' : 2>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary $path/splitcube..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Utility $path/splitcube not found or error loading shared libraries..."; exit 99; fi
  'swarp' --version   &>$hell; rc=$?
  if [[ $rc -eq 126 ]]; then       echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Trouble executing binary swarp..." ; exit 99; fi
  if [[ $rc -eq 127 ]]; then echo; echo; echo ' '$script': '$fun': ERROR:'; echo; echo "   Program swarp not found or error loading shared libraries..."; exit 99; fi
  echo
  
  image=${image/.fits/}; resamp='.resamp'

  if [[ ! -e $image'.fits' ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   File '\'$image'.fits'\'' does not exist...'
    exit 99
  fi

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

EXTRACT_IMAGES ()
{                                         
  local funo=$fun; fun='EXTRACT_IMAGES'; title=$script': => '\'$fun\'
  echo; echo ' '$title
  echo
  echo ' '$script': Preparing image '\'$image\''...'

  if [[ ${mapmaker:0:1} != '-' ]]
  then
    if [[ -e $image'.01.fits'    ]]; then \rm $image'.01.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.02.fits'    ]]; then \rm $image'.02.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.03.fits'    ]]; then \rm $image'.03.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.04.fits'    ]]; then \rm $image'.04.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.05.fits'    ]]; then \rm $image'.05.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.06.fits'    ]]; then \rm $image'.06.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.07.fits'    ]]; then \rm $image'.07.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.08.fits'    ]]; then \rm $image'.08.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.09.fits'    ]]; then \rm $image'.09.fits'    2>&1; chk_rc; fi
    if [[ -e $image'.image.fits' ]]; then \rm $image'.image.fits' 2>&1; chk_rc; fi
    mapmakerx=$mapmaker
  else
    mapmakerx=${mapmaker:1}
  fi
  
  echo; echo ' '$script': Assuming images observed by '\'$instrument\'' and made by '\'$mapmaker\''...'; sleep 1

  if [[ $instrument == 'pacs' || $instrument == 'spire' || $instrument == 'saboca' || $instrument == 'laboca' || \
        $instrument == 'scuba4' || $instrument == 'scuba8' || $instrument == 'sharcii' || $instrument == 'pdb1' || \
        $instrument == 'pdb3' || $instrument == 'mambo' || $instrument == 'simba' || $instrument == 'bolocam' || \
        $instrument == 'spitzer4' || $instrument == 'spitzer8' || $instrument == 'spitzer24' || $instrument == 'other' ]]
  then
    \cp $image'.fits' $image'.image.fits'; chk_rc
  else
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   Unknown instrument: '$instrument; exit 99
  fi
  
  if [[ $mapmakerx != 'naive' && $mapmakerx != 'photproj' && ${mapmakerx:0:6} != 'madmap' && \
        $mapmakerx != 'scanamorphos' && $mapmakerx != 'romagal' && $mapmakerx != 'coldens' && $mapmakerx != 'other' ]]
  then
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   Unknown map-making method: '$mapmaker; exit 99
  fi
  
  if [[ $mapmakerx == 'photproj' ]]
  then
    if [[ $mapmaker == 'photproj' ]]
    then
      echo
      echo ' '$script': Separating all extensions of '\'$image\''...'
  
      $path'/separate' $image $verb
      
      if [[ $? -eq 77 ]]
      then 
        mapmaker='-'$mapmaker
        echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO EXTENSIONS TO EXTRACT.'
        echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
        \cp $image'.fits' $image'.image.fits'; chk_rc
      else
        \mv $image'.02.fits' $image'.image.fits'; chk_rc
      fi
    else
      \cp $image'.fits' $image'.image.fits'; chk_rc
    fi
  fi
  
  if [[ $instrument == 'pacs' ]]
  then
    if [[ $mapmakerx == 'madmap_mosaic' ]]
    then
      if [[ $mapmaker == 'madmap_mosaic' ]]
      then
        echo
        echo ' '$script': Separating all extensions of '\'$image\''...'
  
        $path'/separate' $image $verb
        
        if [[ $? -eq 77 ]]
        then 
          mapmaker='-'$mapmaker
          echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO EXTENSIONS TO EXTRACT.'
          echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
          \cp $image'.fits' $image'.image.fits'; chk_rc
        else
          \mv $image'.02.fits' $image'.image.fits'; chk_rc
        fi
      else
        \cp $image'.fits' $image'.image.fits'; chk_rc
      fi
    fi

    if [[ $mapmakerx == 'madmap_combined' ]]
    then
      if [[ $mapmaker == 'madmap_combined' ]]
      then
        echo
        echo ' '$script': Separating all extensions of '\'$image\''...'
  
        $path'/separate' $image $verb
        
        if [[ $? -eq 77 ]]
        then 
          mapmaker='-'$mapmaker
          echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO EXTENSIONS TO EXTRACT.'
          echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
          \cp $image'.fits' $image'.image.fits'; chk_rc
        else
          \mv $image'.02.fits' $image'.image.fits'; chk_rc
        fi
      else
        \cp $image'.fits' $image'.image.fits'; chk_rc
      fi
    fi

    if [[ $mapmakerx == 'madmap' ]]
    then
      if [[ $mapmaker == 'madmap' ]]
      then
        echo
        echo ' '$script': Separating all extensions of '\'$image\''...'
  
        $path'/separate' $image $verb
        
        if [[ $? -eq 77 ]]
        then 
          mapmaker='-'$mapmaker
          echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO EXTENSIONS TO EXTRACT.'
          echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
          \cp $image'.fits' $image'.image.fits'; chk_rc
        else
          \mv $image'.02.fits' $image'.image.fits'; chk_rc
        fi
      else
        if [[ -e $image'.02.fits' ]]
        then
          \mv $image'.02.fits' $image'.image.fits'; chk_rc
        else
          \cp $image'.fits' $image'.image.fits'; chk_rc
        fi
      fi
    fi
  fi
  
  if [[ $instrument != 'pacs' && ($mapmakerx == 'naive' || $mapmakerx == 'madmap') ]]
  then
    if [[ $mapmaker == 'naive' || $mapmaker == 'madmap' ]]
    then
      echo
      echo ' '$script': Separating all extensions of '\'$image\''...'
  
      $path'/separate' $image $verb
      
      if [[ $? -eq 77 ]]
      then 
        mapmaker='-'$mapmaker
        echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO EXTENSIONS TO EXTRACT.'
        echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
        \cp $image'.fits' $image'.image.fits'; chk_rc
      else
        \mv $image'.02.fits' $image'.image.fits'; chk_rc
      fi
    else
      \cp $image'.fits' $image'.image.fits'; chk_rc
    fi
  fi

  if [[ $mapmakerx == 'scanamorphos' ]]
  then
    if [[ $mapmaker == 'scanamorphos' ]]
    then
      echo
      echo ' '$script': Separating all cube planes of '\'$image\''...'
  
      $path'/splitcube' $image $verb

      if [[ $? -eq 77 ]]
      then 
        mapmaker='-'$mapmaker
        echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO DATACUBE TO SPLIT.'
        echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
        \cp $image'.fits' $image'.image.fits'; chk_rc
      else
        \cp $image'.01.fits' $image'.image.fits'; chk_rc
      fi
    else
      \cp $image'.fits' $image'.image.fits'; chk_rc
    fi
  fi

  if [[ $mapmakerx == 'romagal' ]]
  then
    if [[ $mapmaker == 'romagal' ]]
    then
      echo
      echo ' '$script': Separating all cube planes of '\'$image\''...'
  
      $path'/splitcube' $image $verb

      if [[ $? -eq 77 ]]
      then 
        mapmaker='-'$mapmaker
        echo; echo ' '$script': WARNING: SINGLE IMAGE FOUND: NO DATACUBE TO SPLIT.'
        echo; echo ' '$script': WARNING: SWITCHING TO THE METHOD '\'$mapmaker\''...'; sleep 10
        \cp $image'.fits' $image'.image.fits'; chk_rc
      else
        \cp $image'.01.fits' $image'.image.fits'; chk_rc
      fi
    else
      \cp $image'.fits' $image'.image.fits'; chk_rc
    fi
  fi

  if [[ $mapmakerx == 'other' ]]
  then
    \cp $image'.fits' $image'.image.fits'; chk_rc
  fi
  
  echo
  echo ' '$script': Zeroing all NaNs in '\'$image'.image'\''...'
  
  $path'/modfits' nanzero $image'.image' -o $image'.image' $verb; chk_rc
  
  echo
  echo ' '$script': Zeroing all INF values in '\'$image'.image'\''...'
  
  $path'/modfits' maximum 1e30 y $image'.image' -o $image'.image' $verb; chk_rc
  
  $path'/modfits' multiply 1 $image'.image' -o $image'.image' $verb; chk_rc

  if [[ -e $image'.01.fits' ]]; then \rm $image'.01.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.02.fits' ]]; then \rm $image'.02.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.03.fits' ]]; then \rm $image'.03.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.04.fits' ]]; then \rm $image'.04.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.05.fits' ]]; then \rm $image'.05.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.06.fits' ]]; then \rm $image'.06.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.07.fits' ]]; then \rm $image'.07.fits' 2>&1; chk_rc; fi
  if [[ -e $image'.08.fits' ]]; then \rm $image'.08.fits' 2>&1; chk_rc; fi
  
  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

GET_PIXEL_SIZES ()
{                                         
  local funo=$fun; fun='GET_PIXEL_SIZES'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  echo
  echo ' '$script': Reading pixel size from '\'$image'.image'\''...'
  
##  if [[ $instrument != 'pacs' || ( $mapmakerx != 'naive' && $mapmakerx != 'madmap'  && $mapmakerx != 'scanamorphos' ) ]]
##  then  
##    $path'/readhead' save CDELT1 CDELT2 $image'.image' $verb; rc=$?
##    if [[ $rc -gt 0 ]]
##    then
##      $path'/readhead' save CD1_1 CD2_2 $image $verb; chk_rc
##    fi
##    read cdelt1 dx cdelt2 dy < '.+readhead'; chk_rc ##; \rm '.+readhead' 2>&1; chk_rc
##  else
##  fi

  $path'/readhead' save CDELT1 CDELT2 $image'.image' $verb; rc=$?
  if [[ $rc -gt 0 ]]
  then
    $path'/readhead' save CD1_1 CD2_2 $image $verb; chk_rc
  fi

  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 a 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=9; ${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=9; ${dy:0:(lendy-4)}*10^$dexpy" | bc); chk_rc
  fi
  if [[ ${dexpx:1:1} == "E" || ${dexpx:1:1} == "e" ]]
  then dexpx=${dexpx:2}; dx=$(echo "scale=9; ${dx:0:(lendx-3)}*10^$dexpx" | bc); chk_rc
  fi
  if [[ ${dexpy:1:1} == "E" || ${dexpy:1:1} == "e" ]]
  then dexpy=${dexpy:2}; dy=$(echo "scale=9; ${dy:0:(lendy-3)}*10^$dexpy" | bc); chk_rc
  fi
  
  # Convert pixel sizes in arcseconds.
  
  dxas=$(echo "scale=20; $dx*3600+0.000001" | bc); chk_rc; dyas=$(echo "scale=20; $dy*3600+0.000001" | bc); chk_rc
  
  echo
  echo ' '$script': Correcting pixel size in '\'$image'.image'\''...'
  
  $path'/modfits' keyword CDELT1 $dxas $image'.image' -o $image'.image' $verb; chk_rc
  $path'/modfits' keyword CDELT2 $dyas $image'.image' -o $image'.image' $verb; chk_rc
  
  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

GET_BEAM_SIZES ()
{                                         
  local funo=$fun; fun='GET_BEAM_SIZES'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  echo
  echo ' '$script': Obtaining beam size for image '\'$image\''...'
     
  wave=0; effres=0

  if [[ $instrument == "pacs" || $instrument == "spire" ]]
  then
    if [[ $scanspeed != "10" && $scanspeed != "20" && $scanspeed != "20p" && $scanspeed != "30" && \
          $scanspeed != "60" && $scanspeed != "60p" ]]
    then 
      echo; echo ' '$script': '$fun': ERROR:'
      echo; echo '   Incorrect value of scanspeed for '$instrument': "'$scanspeed'"'
            echo '   The second command line parameter is inconsistent.'
      exit 99
    fi
  fi

  if [[ $instrument == "pacs" ]]
  then
    rcb=0
    if [[ $rcb -eq 0 ]]; then 'POSITION' _B_    $image; rcb=$returnposition; fi
    if [[ $rcb -eq 0 ]]; then 'POSITION' _blue  $image; rcb=$returnposition; fi
    if [[ $rcb -eq 0 ]]; then 'POSITION' blue_  $image; rcb=$returnposition; fi
    if [[ $rcb -eq 0 ]]; then 'POSITION' _070   $image; rcb=$returnposition; fi
    if [[ $rcb -eq 0 ]]; then 'POSITION' 70     $image; rcb=$returnposition; fi
    rcg=0
    if [[ $rcg -eq 0 ]]; then 'POSITION' _G_    $image; rcg=$returnposition; fi
    if [[ $rcg -eq 0 ]]; then 'POSITION' _green $image; rcg=$returnposition; fi
    if [[ $rcg -eq 0 ]]; then 'POSITION' green_ $image; rcg=$returnposition; fi
    if [[ $rcg -eq 0 ]]; then 'POSITION' _100   $image; rcg=$returnposition; fi
    if [[ $rcg -eq 0 ]]; then 'POSITION' 100    $image; rcg=$returnposition; fi
    rcr=0
    if [[ $rcr -eq 0 ]]; then 'POSITION' _R_    $image; rcr=$returnposition; fi
    if [[ $rcr -eq 0 ]]; then 'POSITION' _red   $image; rcr=$returnposition; fi
    if [[ $rcr -eq 0 ]]; then 'POSITION' red_   $image; rcr=$returnposition; fi
    if [[ $rcr -eq 0 ]]; then 'POSITION' _160   $image; rcr=$returnposition; fi
    if [[ $rcr -eq 0 ]]; then 'POSITION' 160    $image; rcr=$returnposition; fi

# PACS Scan Map release note 1.1 (Feb 23, 2010):
# PSF at 070: sqrt (  5.26 *  5.61 ) = 5.432 ~  5.4"
# PSF at 100: sqrt (  6.57 *  6.81 ) = 6.689 ~  6.7"
# PSF at 160: sqrt ( 10.46 * 12.06 ) = 11.23 ~ 11.2"
# PACS Photometer PSF v1.01 (Dieter Lutz, Nov 3, 2010):
# 10"/s PSF at 070:  5.25 x  5.61 (Vesta),  5.20 x  5.56 (alpha Tau) => sqrt (  5.225 x  5.585 ) =  5.40 ~  5.4"
# 10"/s PSF at 100:  6.53 x  6.78 (Vesta),  6.52 x  6.76 (alpha Tau) => sqrt (  6.525 x  6.77  ) =  6.65 ~  6.7"
# 10"/s PSF at 160: 10.38 x 11.95 (Vesta), 10.41 x 11.98 (alpha Tau) => sqrt ( 10.395 x 11.965 ) = 11.15 ~ 11.2"

    if [[ $scanspeed == "10" ]]
    then
      if [[ $rcb -gt 0 ]]; then wave='070'; beam='5.4' ; effres='05.8'; fi #<-- 7%
      if [[ $rcg -gt 0 ]]; then wave='100'; beam='6.7' ; effres='07.2'; fi #<-- 7%
      if [[ $rcr -gt 0 ]]; then wave='160'; beam='11.2'; effres='11.9'; fi #<-- 6%
    fi

# PACS Scan Map release note 1.1 (Feb 23, 2010):
# PSF at 070: sqrt (  5.46 *  5.76 ) = 5.607 ~  5.6"
# PSF at 100: sqrt (  6.69 *  6.89 ) = 6.789 ~  6.8"
# PSF at 160: sqrt ( 10.65 * 12.13 ) = 11.37 ~ 11.4"
# PACS Photometer PSF v1.01 (Dieter Lutz, Nov 3, 2010):
# 20"/s PSF at 070:  5.46 x  5.77 (Vesta),  5.40 x  5.70 (alpha Tau) => sqrt (  5.43  x  5.735 ) =  5.58 ~  5.6"
# 20"/s PSF at 100:  6.66 x  6.89 (Vesta),  6.63 x  6.83 (alpha Tau) => sqrt (  6.645 x  6.86  ) =  6.75 ~  6.8"
# 20"/s PSF at 160: 10.53 x 12.06 (Vesta), 10.58 x 12.06 (alpha Tau) => sqrt ( 10.555 x 12.06  ) = 11.28 ~ 11.3"

    if [[ $scanspeed == "20" ]]
    then
      if [[ $rcb -gt 0 ]]; then wave='070'; beam='5.6' ; effres='06.0'; fi #<-- 7%
      if [[ $rcg -gt 0 ]]; then wave='100'; beam='6.8' ; effres='07.2'; fi #<-- 6%
      if [[ $rcr -gt 0 ]]; then wave='160'; beam='11.3'; effres='12.0'; fi #<-- 6%
    fi

# PACS Photometer PSF v1.01 (Dieter Lutz, Nov 3, 2010):
# 20"/s para PSF at 070:  5.57 x 6.33 (Vesta) => sqrt ( 5.57 x 6.33 ) = 5.94 ~  5.9"
# 20"/s para PSF at 100:  6.73 x 7.29 (Vesta) => sqrt ( 6.73 x 7.29 ) = 7.00 ~  7.0"
# 20"/s para PSF at 160:  no information... extrapolating from 20"/s =>      ~ 11.7"

    if [[ $scanspeed == "20p" ]]  #<-- parallel mode
    then
      if [[ $rcb -gt 0 ]]; then wave='070'; beam='5.9' ; effres='06.3'; fi #<-- 7% increase
      if [[ $rcg -gt 0 ]]; then wave='100'; beam='7.0' ; effres='07.4'; fi #<-- 6% increase
      if [[ $rcr -gt 0 ]]; then wave='160'; beam='11.7'; effres='12.4'; fi #<-- 6% increase
    fi
  
# PACS Scan Map release note 1.1 (Feb 23, 2010):
# PSF at 070: sqrt (  5.75 *  9.00 ) = 7.194 ~  7.2"
# PSF at 100: sqrt (  6.89 *  9.74 ) = 8.192 ~  8.2"
# PSF at 160: sqrt ( 11.31 * 13.32 ) = 12.27 ~ 12.3"
# PACS Photometer PSF v1.01 (Dieter Lutz, Nov 3, 2010):
# 60"/s PSF at 070:  5.73 x  9.11 (Vesta),  5.70 x  8.92 (alpha Tau) => sqrt (  5.715 x  9.015 ) =  7.18 ~  7.2"
# 60"/s PSF at 100:  6.83 x  9.82 (Vesta),  6.84 x  9.66 (alpha Tau) => sqrt (  6.835 x  9.74  ) =  8.16 ~  8.2"
# 60"/s PSF at 160: 11.38 x 13.34 (Vesta), 11.35 x 13.30 (alpha Tau) => sqrt ( 11.365 x 13.32  ) = 12.30 ~ 12.3"

    if [[ $scanspeed == "60" ]]
    then
      if [[ $rcb -gt 0 ]]; then wave='070'; beam='7.2' ; effres='07.7'; fi #<-- 7% increase
      if [[ $rcg -gt 0 ]]; then wave='100'; beam='8.2' ; effres='08.7'; fi #<-- 6% increase
      if [[ $rcr -gt 0 ]]; then wave='160'; beam='12.3'; effres='13.0'; fi #<-- 6% increase
    fi

# PACS Scan Map release note 1.1 (Feb 23, 2010):
# PSF at 070: sqrt (  5.86 * 12.16 ) =  8.441 ~  8.4"
# PSF at 100: sqrt (  6.98 * 12.70 ) =  9.415 ~  9.4"
# PSF at 160: sqrt ( 11.64 * 15.65 ) = 13.50  ~ 13.5"
# PACS Photometer PSF v1.01 (Dieter Lutz, Nov 3, 2010):
# 60"/s para PSF at 070:  5.82 x 12.09 (Vesta) => sqrt ( 5.82 x 12.09 ) = 8.39 ~ 8.4"
# 60"/s para PSF at 100:  6.94 x 12.65 (Vesta) => sqrt ( 6.94 x 12.65 ) = 9.37 ~ 9.4"

    if [[ $scanspeed == "60p" ]]  #<-- parallel mode
    then
      if [[ $rcb -gt 0 ]]; then wave='070'; beam='8.4' ; effres='09.0'; fi #<-- 7% increase
      if [[ $rcg -gt 0 ]]; then wave='100'; beam='9.4' ; effres='10.0'; fi #<-- 6% increase
      if [[ $rcr -gt 0 ]]; then wave='160'; beam='13.5'; effres='14.4'; fi #<-- 6% increase
    fi
  fi
  
# !!! VERY IMPORTANT !!!
# IF YOU MODIFY THE SPIRE 'BEAMAREA' VALUES BELOW, DON'T FORGET TO MODIFY THEM IN 'FINALCAT' ACCORDINGLY
#
# Beam areas from SPIRE Observer's Manual v.2.2 (Nov. 2010), page 75: 426, 771, 1626 arcsec^2
# Beam areas for SPIRE (Feb. 2013, N. Schneider): 465, 822, 1769 arcsec^2
  
  if [[ $instrument == "spire" ]]
  then
    rcpsw=0
    if [[ $rcpsw -eq 0 ]]; then 'POSITION' PSW  $image; rcpsw=$returnposition; fi
    if [[ $rcpsw -eq 0 ]]; then 'POSITION' psw  $image; rcpsw=$returnposition; fi
    if [[ $rcpsw -eq 0 ]]; then 'POSITION' _250 $image; rcpsw=$returnposition; fi
    if [[ $rcpsw -eq 0 ]]; then 'POSITION' 250  $image; rcpsw=$returnposition; fi
    rcpmw=0
    if [[ $rcpmw -eq 0 ]]; then 'POSITION' PMW  $image; rcpmw=$returnposition; fi
    if [[ $rcpmw -eq 0 ]]; then 'POSITION' pmw  $image; rcpmw=$returnposition; fi
    if [[ $rcpmw -eq 0 ]]; then 'POSITION' _350 $image; rcpmw=$returnposition; fi
    if [[ $rcpmw -eq 0 ]]; then 'POSITION' 350  $image; rcpmw=$returnposition; fi
    rcplw=0
    if [[ $rcplw -eq 0 ]]; then 'POSITION' PLW  $image; rcplw=$returnposition; fi
    if [[ $rcplw -eq 0 ]]; then 'POSITION' plw  $image; rcplw=$returnposition; fi
    if [[ $rcplw -eq 0 ]]; then 'POSITION' _500 $image; rcplw=$returnposition; fi
    if [[ $rcplw -eq 0 ]]; then 'POSITION' 500  $image; rcplw=$returnposition; fi

    if [[ $rcpsw -gt 0 ]]; then wave='250'; beamarea='426' ; beam='18.2'; effres='19.5'; fi #<-- 7% increase
    if [[ $rcpmw -gt 0 ]]; then wave='350'; beamarea='771' ; beam='24.9'; effres='26.5'; fi #<-- 6% increase
    if [[ $rcplw -gt 0 ]]; then wave='500'; beamarea='1626'; beam='36.3'; effres='38.5'; fi #<-- 6% increase
  fi

# OTHER INSTRUMENTS

  if [[ $instrument != "pacs" && $instrument != "spire" ]]
  then
    if [[ $instrument == "other"     ]]; then wave='000' ; fi
    if [[ $instrument == "spitzer4"  ]]; then wave='004' ; fi
    if [[ $instrument == "spitzer8"  ]]; then wave='008' ; fi
    if [[ $instrument == "spitzer24" ]]; then wave='024' ; fi
    if [[ $instrument == "saboca"    ]]; then wave='350' ; fi
    if [[ $instrument == "sharcii"   ]]; then wave='350' ; fi
    if [[ $instrument == "scuba4"    ]]; then wave='450' ; fi
    if [[ $instrument == "scuba8"    ]]; then wave='850' ; fi
    if [[ $instrument == "laboca"    ]]; then wave='870' ; fi
    if [[ $instrument == "bolocam"   ]]; then wave='1100'; fi
    if [[ $instrument == "mambo"     ]]; then wave='1200'; fi
    if [[ $instrument == "simba"     ]]; then wave='1200'; fi
    if [[ $instrument == "pdb1"      ]]; then wave='1300'; fi
    if [[ $instrument == "pdb3"      ]]; then wave='3000'; fi

    if [[ $mapmakerx == "coldens" ]]
    then 
      wave='255'; beam=$beam
      effres=$(echo "scale=20; 1.10*$beam" | bc); chk_rc
    else  
      effres=$(echo "scale=20; 1.07*$beam" | bc); chk_rc
    fi
  fi
  
  if [[ $wave == "0" || $beam == "0" || $effres == "0" ]]
  then 
    echo; echo ' '$script': '$fun': ERROR:'
    echo; echo '   Unassigned wave: "'$wave'" or beam: "'$beam'" or effres: "'$effres'"'
          echo '   Check values of command line parameters for consistency.'
    exit 99
  fi

  smobeam=$(echo "scale=20; sqrt($effres^2-$beam^2)" | bc); chk_rc

  if [[ ${effres:0:1} == '.' ]]
  then effres='0'$effres
  fi
  if [[ ${effres:0:4} == '0.00' ]]
  then effres=${effres:0:7}
  elif [[ ${effres:0:3} == '0.0' ]]
  then effres=${effres:0:6}
  elif [[ ${effres:0:2} == '0.' ]]
  then effres=${effres:0:5}
  else effres=${effres:0:4}
  fi

  echo
  echo ' '$script': Beam size: '$beam', detection image resolution: '$effres
  
  effres=${effres/./p}

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

CHANGE_UNITS ()
{                                         
  local funo=$fun; fun='CHANGE_UNITS'; title=$script': => '\'$fun\'
  echo; echo ' '$title
  echo
  echo ' '$script': Reading intensity units from '\'$image'.image'\''...'
  
  $path'/readhead' save BUNIT $image'.image' $verb; chk_rc
  
  read bunit bunit < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  if [[ ${bunit:0:1} == "'" ]]; then bunit=${bunit:1}; fi
  lenbu=${#bunit}; lenbu=$(( lenbu - 1 ))
  if [[ ${bunit:lenbu:1} == "'" ]]; then bunit=${bunit:0:lenbu}; fi
  bunits=`echo $bunit | tr a-z A-Z`
  
# HIPE output may have units stored in the QTTY____ keyword.  

  if [[ "${bunit:1:1}" == " " ]]
  then
    $path'/readhead' save QTTY____ $image $verb; rcqtty=$?
    
    if [[ $rcqtty -lt 2 ]]
    then
      read bunit bunit < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
      if [[ ${bunit:0:1} == "'" ]]; then bunit=${bunit:1}; fi
      lenbu=${#bunit}; lenbu=$(( lenbu - 1 ))
      if [[ ${bunit:lenbu:1} == "'" ]]; then bunit=${bunit:0:lenbu}; fi
      bunits=`echo $bunit | tr a-z A-Z`
    fi
  fi

  if [[ "${bunit:1:1}" == " " ]]
  then 
    echo; echo ' '$script': '$fun': WARNING:'
    echo; echo '   TROUBLE GETTING UNITS FROM THE INPUT IMAGE HEADER...'
          echo '   WILL ASSUME STANDARD UNITS BASED ON THE INSTRUMENT;'
          echo '   YOU ARE RESPONSIBLE FOR MAKING SURE THIS IS CORRECT.'
    goodunits='no'; bunits='xxxxx'; read -s -t 10 answer; rc=$?
  else
    'POSITION' 'MJY/SR' "$bunits"; rcbunits=$returnposition
  
    if [[ $rcbunits -gt 0 ]]
    then goodunits='yes'
    else goodunits='no'
    fi
  fi

  if [[ $instrument == "other" && $mapmakerx == "coldens" ]]
  then
    $path'/modfits' divide 1e20 $image'.image' -o $image'.image' $verb; chk_rc
  fi
  
  if [[ $goodunits == "no" ]]
  then
    if [[ $instrument == "pacs" ]]
    then
      'POSITION' 'JY/PIXEL' "$bunits"; rcbunits=$returnposition

      if [[ $rcbunits -eq 0 ]]
      then 
        'POSITION' 'JY/MAP PIXEL' "$bunits"; rcbunits=$returnposition
      fi
      
      if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid units in the input image: "'$bunit'"'
              echo '   For PACS the units must be "Jy/pixel".'
        exit 99
      fi
      echo
      echo ' '$script': Changing units Jy/pixel~>MJy/sr in '\'$image'.image'\''...'
    
      $path'/modfits' 'Jy/pixel~MJy/sr' $image'.image' -o $image'.image' $verb; chk_rc
    fi
    
    if [[ $instrument == "spire" ]]
    then
      'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

      if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
      then 
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid units in the input image: "'$bunit'"'
              echo '   For SPIRE the units must be "Jy/beam".'
        exit 99
      fi
      echo
      echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
      $path'/modfits' 'Jy/beam~MJy/sr' -$beamarea $image'.image' -o $image'.image' $verb; chk_rc
    fi
    
    if [[ $instrument == "other" ]]
    then
      if [[ $mapmakerx == "coldens" ]]
      then
        'POSITION' 'H2.CM^-2' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For COLDENS the units must be "H2.cm^-2".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units H2.cm^-2~>MJy/sr in '\'$image'.image'\''...'
      
        $path'/modfits' keyword BUNIT 'MJy/sr' $image'.image' -o $image'.image' $verb; chk_rc
      fi
    fi
    
    if [[ $instrument == "saboca" ]]
    then
      if [[ $wave == '350' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For SABOCA the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for SABOCA: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "sharcii" ]]
    then
      if [[ $wave == '350' ]]
      then
        'POSITION' 'MJY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For SHARCII the units must be "mJy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units mJy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'mJy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for SHARCII: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "laboca" ]]
    then
      if [[ $wave == '870' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For LABOCA the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for LABOCA: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "scuba4" || $instrument == "scuba8" ]]
    then
      if [[ $wave == '450' || $wave == '850' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For SCUBA the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for SCUBA: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "bolocam" ]]
    then
      if [[ $wave == '1100' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For BOLOCAM the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for BOLOCAM: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "mambo" ]]
    then
      if [[ $wave == '1200' ]]
      then
        'POSITION' 'MJY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For MAMBO the units must be "mJy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units mJy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'mJy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for MAMBO: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "simba" ]]
    then
      if [[ $wave == '1200' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For SIMBA the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for SIMBA: '$wave
        exit 99
      fi
    fi
    
    if [[ $instrument == "pdb1" ]]
    then
      if [[ $wave == '1300' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For PDB1 the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for PdB1: '$wave
        exit 99
      fi
    fi

    if [[ $instrument == "pdb3" ]]
    then
      if [[ $wave == '3000' ]]
      then
        'POSITION' 'JY/BEAM' "$bunits"; rcbunits=$returnposition

        if [[ $rcbunits -eq 0 && "${bunit:1:1}" != " " ]]
        then 
          echo; echo ' '$script': '$fun': ERROR:'
          echo; echo '   Invalid units in the input image: "'$bunit'"'
                echo '   For PDB3 the units must be "Jy/beam".'
          exit 99
        fi
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Invalid wavelength for PdB3: '$wave
        exit 99
      fi
    fi

    if [[ $instrument == "other" && $mapmakerx == "other" ]]
    then
      'POSITION' 'JY/BEAM' "$bunits"; rcjybeam=$returnposition
      'POSITION' 'MJY/BEAM' "$bunits"; rcmjybeam=$returnposition
      'POSITION' 'JY/PIXEL' "$bunits"; rcjypixel=$returnposition

      if [[ $rcjybeam -gt 0 ]]
      then 
        echo
        echo ' '$script': Changing units Jy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      elif [[ $rcmjybeam -gt 0 ]]
      then 
        echo
        echo ' '$script': Changing units mJy/beam~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'mJy/beam~MJy/sr' $beam $image'.image' -o $image'.image' $verb; chk_rc
      elif [[ $rcjypixel -gt 0 ]]
      then 
        echo
        echo ' '$script': Changing units Jy/pixel~>MJy/sr in '\'$image'.image'\''...'
    
        $path'/modfits' 'Jy/pixel~MJy/sr' $image'.image' -o $image'.image' $verb; chk_rc
      else
        echo; echo ' '$script': '$fun': ERROR:'
        echo; echo '   Unknown units in the input image: "'$bunit'"'
              echo '   Please convert the image manually into "MJy/sr".'
        exit 99
      fi
    fi
  else
    echo
    echo ' '$script': Intensity units are OK, no need to convert...'
  fi
  
  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

READ_MORE_INFO ()
{                                         
  local funo=$fun; fun='READ_MORE_INFO'; title=$script': => '\'$fun\'
  echo; echo ' '$title
  echo
  echo ' '$script': Reading pixel numbers from '\'$image'.image'\''...'
    
  $path'/readhead' save NAXIS1 NAXIS2 $image'.image' $verb; chk_rc
  
  read naxis1 nx naxis2 ny < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
  if [[ $nx -le $ny ]]; then minpix=$nx; else minpix=$ny; fi             
  if [[ $nx -ge $ny ]]; then maxpix=$nx; else maxpix=$ny; fi             
                                             
  echo
  echo ' '$script': Reading projection type from '\'$image'.image'\''...'
  
  $path'/readhead' save CTYPE1 CTYPE2 $image'.image' $verb; chk_rc
  
  read ctypec ctype1 ctypec ctype2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
  echo
  echo ' '$script': Reading reference pixels from '\'$image'.image'\''...'
  
  $path'/readhead' save CRPIX1 CRPIX2 $image'.image' $verb; chk_rc
  
  read crpixc crpix1 crpixc crpix2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
  echo
  echo ' '$script': Reading reference coords from '\'$image'.image'\''...'
  
  $path'/readhead' save CRVAL1 CRVAL2 $image'.image' $verb; chk_rc
  
  read crvalc crval1 crvalc crval2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  echo
  echo ' '$script': Reading coordinates from '\'$image'.image'\''...'
  
  $path'/readhead' save RA DEC $image'.image' $verb; chk_rc
  
  read rascenc rascen declinc declin < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  if [[ $crval1 != $rascen ]]
  then
    echo
    echo ' '$script': Correcting coordinate RA in '\'$image'.image'\''...'
  
    $path'/modfits' keyword RA $crval1 $image'.image' -o $image'.image' $verb; chk_rc
  fi
  if [[ $crval2 != $declin ]]
  then
    echo
    echo ' '$script': Correcting coordinate DEC in '\'$image'.image'\''...'
  
    $path'/modfits' keyword DEC $crval2 $image'.image' -o $image'.image' $verb; chk_rc
  fi
  
  lent1=${#ctype1}; lent1m1=$(( lent1 - 1 ))
  if [[ ${ctype1:lent1m1:1} == "'" ]]; then ctype1=${ctype1:0:lent1m1}; fi
  if [[ ${ctype1:0:1} == "'" ]]; then ctype1=${ctype1:1}; fi
  lent2=${#ctype2}; lent2m1=$(( lent2 - 1 ))
  if [[ ${ctype2:lent2m1:1} == "'" ]]; then ctype2=${ctype2:0:lent2m1}; fi
  if [[ ${ctype2:0:1} == "'" ]]; then ctype2=${ctype2:1}; fi
  
  bunit='MJy/sr'
         
# Convert image sizes in degrees.
  
  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

  echo
  echo ' '$script': Reading equinox from '\'$image'.image'\''...'
  
  $path'/readhead' save EQUINOX $image'.image' $verb; chk_rc
  
  read equinx equinox < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

CORRECT_HEADERS ()
{                                         
  local funo=$fun; fun='CORRECT_HEADERS'; title=$script': => '\'$fun\'
  echo; echo ' '$title
  echo
  echo ' '$script': Correcting object in '\'$image'.image'\''...'
  
  $path'/modfits' keyword OBJECT "$fieldname" $image'.image' -o $image'.image' $verb; chk_rc

  echo
  echo ' '$script': Correcting wavelength in '\'$image'.image'\''...'
  
  $path'/modfits' keyword WAVE $wave $image'.image' -o $image'.image' $verb; chk_rc
  
  echo
  echo ' '$script': Correcting units in '\'$image'.image'\''...'
  
  $path'/modfits' keyword BUNIT $bunit $image'.image' -o $image'.image' $verb; chk_rc
                     
  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

RESAMPLE_IMAGES ()
{                                         
  local funo=$fun; fun='RESAMPLE_IMAGES'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  logfileresample='+log.RESAMPLE'
  echo > $logfileresample

  echo ' '
  echo ' Field or object name: '$fieldname', physical intensity units: '$bunit
  echo ' Wavelength: '$wave', observational beam: '$beam', scan speed: '$scanspeed
  echo ' Image dimensions: '$nx' x '$ny' pixels, dx = '$dxas', dy = '$dyas' arcsec'
  echo ' Image size: '${sidexas:0:8}' x '${sideyas:0:8}' arcsec = '${sidexdg:0:8}' x '${sideydg:0:8}' degrees'
  echo ' Reference pixel: crpix1 = '$crpix1', crpix2 = '$crpix2
  echo ' Reference pixel coords: crval1 = '$crval1', crval2 = '$crval2
  echo ' Projection type: ctype1 = '$ctype1', ctype2 = '$ctype2
  
  minus=''

  'COMPARE_NUMBERS' $pix0 '>' $dxas; rcx=$?
  'COMPARE_NUMBERS' $pix0 '>' $dyas; rcy=$?

  if [[ $rcx -eq 1 && $rcy -eq 1 ]]
  then echo; echo ' '$script': '$fun': WARNING:'
    echo; echo '   DESIRED PIXEL SIZE '$pix0' IS GREATER THAN THE ORIGINAL PIXEL '$dxas
          echo '   RESAMPLING MAY LEAD TO INACCURACIES OF PEAK INTENSITIES.'
    read -s -t 30 answer; rc=$?; minus=''
  fi

  if [[ $nx0 -eq 10 && $ny0 -eq 10 && $ra0 == '00:00:00.00' && $dec0 == '00:00:00.0' ]]
  then
    pixelo=$dxas

    'resample' $image'.image.fits' $pix0 $nx0 $ny0 $ra0 $dec0 $rota >> $logfileresample 2>&1; chk_rc
    {
    while read word[1] word[2] word[3] word[4] word[5] word[6] word[7] word[8] word[9] 
    do
      if [[ ${word[1]} != "" ]]
      then
        'POSITION' 'Center:' ${word[1]}; result=$returnposition
        if [[ $result -gt 0 ]]
        then
          'POSITION' '00:00:00.00' ${word[2]}; result=$returnposition
          if [[ $result -eq 0 ]]
          then
            'POSITION' 'Scale:' ${word[5]}; result=$returnposition
            if [[ $result -gt 0 ]]
            then
              ra0=${word[2]}; dec0=${word[3]}
              break
            fi
          fi
        fi
      fi
    done
    } < $logfileresample
    
    nx0=$(echo "scale=4; $nx*$pixelo/$pix0" | bc); chk_rc; nx0=${nx0%.*}  #<-- make the number integer
    ny0=$(echo "scale=4; $ny*$pixelo/$pix0" | bc); chk_rc; ny0=${ny0%.*}  #<-- make the number integer
  fi
  
  echo
  echo '     Resample pixel: pix0 = '$pix0
  echo '   Image dimensions: npix1 = '$nx0' npix2 = '$ny0
  echo ' Center coordinates: coord1 = '$ra0' coord2 = '$dec0
  echo '     Rotation angle: '$rota' degrees (east of north)'

###  if [[ "$crtype1" != "RA---TAN" && "$crtype2" != "DEC--TAN" ]]

  if [[ $doresample == "no" ]]
  then
    echo
    echo ' '$script': NO RESAMPLING REQUESTED for '\'$image'.image.fits'\''...'

    \cp $image'.image.fits' $image'.image.resamp.fits'; chk_rc
  else 
    echo
    echo ' '$script': Resampling '\'$image'.image.fits'\''...'

    'resample' $image'.image.fits' $minus$pix0 $nx0 $ny0 $ra0 $dec0 $rota >> $logfileresample 2>&1; chk_rc
  fi
  
  if [[ -e 'swarp.xml' ]]; then \rm 'swarp.xml'; chk_rc; fi

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

CORRECT_SWARP_HEADERS ()
{                                         
  local funo=$fun; fun='CORRECT_SWARP_HEADERS'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  nx=$nx0
  ny=$ny0
  dxas=$pix0
  dyas=$pix0
  
  echo
  echo ' '$script': Reading reference pixels from '\'$image'.image'$resamp\''...'
  
  $path'/readhead' save CRPIX1 CRPIX2 $image'.image'$resamp $verb; chk_rc
  
  read crpix1 crpix1 crpix2 crpix2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
  echo
  echo ' '$script': Reading reference coords from '\'$image'.image'$resamp\''...'
  
  $path'/readhead' save CRVAL1 CRVAL2 $image'.image'$resamp $verb; chk_rc
  
  read crval1 crval1 crval2 crval2 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc
  
  echo
  echo ' '$script': Reading linear projection matrix from '\'$image'.image'$resamp\''...'
  
  $path'/readhead' save CD1_1 CD1_2 $image'.image'$resamp $verb; chk_rc
  read cd11 cd11 cd12 cd12 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  $path'/readhead' save CD2_1 CD2_2 $image'.image'$resamp $verb; chk_rc
  read cd21 cd21 cd22 cd22 < '.+readhead'; chk_rc; \rm '.+readhead' 2>&1; chk_rc

  $path'/operate' $image'.image' h $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc

  $path'/modfits' keyword CTYPE1  $ctype1out  $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CTYPE2  $ctype2out  $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CRPIX1  $crpix1     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CRPIX2  $crpix2     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CROTA1  $rota       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CROTA2  $rota       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CRVAL1  $crval1     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CRVAL2  $crval2     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword RA      $crval1     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword DEC     $crval2     $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword OBJECT "$fieldname" $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CDELT1 -$pix0       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CDELT2  $pix0       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CD1_1   $cd11       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CD1_2   $cd12       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CD2_1   $cd21       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword CD2_2   $cd22       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword WAVE    $wave       $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc
  $path'/modfits' keyword BUNIT   $bunit      $image'.image'$resamp -o $image'.image'$resamp $verb; chk_rc

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

MAKE_DETECTION_IMAGE ()
{                                         
  local funo=$fun; fun='MAKE_DETECTION_IMAGE'; title=$script': => '\'$fun\'
  echo; echo ' '$title

# Convolve image with a small smoothing beam (fraction of observational beam size) to reduce unphysical noise on the pixel scale.
                          
  addpix=$(echo "scale=20; 3.0*$smobeam/$dxas" | bc); chk_rc

  $path'/modfits' expand $addpix $image'.image'$resamp -o $image'.image'$resamp'.r'$effres $verb; chk_rc
  $path'/fftconv' $smobeam 0 $image'.image'$resamp'.r'$effres -o $image'.image'$resamp'.r'$effres $verb; chk_rc
  $path'/modfits' border -$addpix $image'.image'$resamp'.r'$effres -o $image'.image'$resamp'.r'$effres $verb; chk_rc
  
  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

CREATE_MASK_IMAGE ()
{                                         
  local funo=$fun; fun='CREATE_MASK_IMAGE'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  badcover='no'
  
  $path'/imgstat' save -nomed $image'.image'$resamp $verb; chk_rc
  
  read min max mea med totsum sig skew kurt < '.+imgstat1'; chk_rc
  if [[ ${min:0:1} == "*" || ${max:0:1} == "*" || ${sig:0:1} == "*" || $sig == "0.000000000" ]]
  then echo; echo ' '$script': '$fun': ERROR: Bad results from IMGSTAT:'; echo ' '$min $max $sig; badcover='yes'
  fi
  \rm '.+imgstat1' 2>&1; chk_rc
  
  if [[ $badcover == 'no' ]]
  then
    $path'/modfits' mul 0 $image'.image'$resamp -o $image'.image'$resamp'.omask' $verb; chk_rc
    $path'/modfits' add 1 $image'.image'$resamp'.omask' -o $image'.image'$resamp'.omask' $verb; chk_rc

    if [[ $mapmaker != 'scanamorphos' ]]
    then
      echo '_______________________________________________________________________________'
      echo
      echo ' SUMMARY OF THE IMAGES:' 
      echo
      echo ' Field or object name: '$fieldname', physical intensity units: '$bunit
      echo ' Image dimensions: '$nx' x '$ny' pixels, dx = '${dxas:0:8}', dy = '${dyas:0:8}' arcsec'
      echo ' Image size: '${sidexas:0:8}' x '${sideyas:0:8}' arcsec = '${sidexdg:0:8}' x '${sideydg:0:8}' degrees'
      echo ' Reference pixel: crpix1 = '$crpix1', crpix2 = '$crpix2
      echo ' Reference pixel coords: crval1 = '$crval1', crval2 = '$crval2
      echo ' Center coordinates: coord1 = '$ra0' coord2 = '$dec0
      echo '_______________________________________________________________________________'
###      echo
###      echo ' Your next command may look like this:'
###      echo   
###      echo '  '$scriptname" $instrument $scanspeedorbeam $mapmaker $fieldname $image $pix0 $nx0 $ny0 $ra0 $dec0 $rota"
###      echo '_______________________________________________________________________________'
###      exit 99
    fi
  fi

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________

FINISH ()
{                                         
  local funo=$fun; fun='FINISH'; title=$script': => '\'$fun\'
  echo; echo ' '$title

  \mv $image'.image'$resamp'.omask.fits' $image'.image'$resamp'.r'$effres'.omask.fits'; chk_rc

  echo '_______________________________________________________________________________'
  echo
  echo ' IMAGES PREPARED FOR SOURCE EXTRACTION FOR THE FIELD:' $fieldname
  echo
  echo ' WAVEBAND:' $wave 'OBSBEAM:' $beam 'SCANSPEED:' $scanspeed 'ROTATION:' $rota 'deg (E of N)'
  echo
  echo '  Observed image: '$image'.image'$resamp'.fits'
  echo ' Detection image: '$image'.image'$resamp'.r'$effres'.fits'
  echo '  Obs.mask image: '$image'.image'$resamp'.r'$effres'.omask.fits'
  echo ' _____________________________________________________________________________ '
  echo '|                                                                             |'
  echo '| VERY IMPORTANT! REMEMBER TO *ALWAYS* VERIFY THE OBSERVATIONAL MASK IMAGES,  |'
  echo '| OPENING THEM AND INSPECTING THOSE AUTOMATICALLY-CREATED IMAGES TO MAKE SURE |'
  echo '| THEY INDEED CORRECTLY COVER THE AREA WHERE SOURCES ARE TO BE EXTRACTED. THE |'
  echo '| MASK IMAGES SHOULD EXCLUDE NOISY AREAS AND PIXELS OUTSIDE IMAGE COVERAGE.   |'
  echo '| USERS NOT FOLLOWING THIS ADVICE RISK WASTING THEIR TIME.                    |'
  echo '|                                                                             |'
  echo '| "THERE'\''S NEVER TIME TO DO IT RIGHT, BUT THERE'\''S ALWAYS TIME TO DO IT OVER." |'
  echo '|                                                                             |'
  echo '| The observational masks automatically produced by PREPAREOBS have values of |'
  echo '| all pixels set to 1. If the masks are not appropriate, one could produce    |'
  echo '| masks using other software (e.g., ImageJ) that enables users to create a    |'
  echo '| polygon, fill it with a value of 1, and save in the FITS format. Having     |'
  echo '| employed third-party software to create mask images, the user should make   |'
  echo '| image headers consistent with other prepared images by copying the default  |'
  echo '| FITS header using the OPERATE utility:                                      |'
  echo '|                                                                             |'
  echo '  operate '$image'.image'$resamp'.r'$effres'.omask.fits h \'
  echo '          your.manual.mask.fits -o \'
  echo '          '$image'.image'$resamp'.r'$effres'.omask.fits'
  echo '|                                                                             |'
  echo '| In effect, the above command replaces the default mask with the manual one. |'
  echo '|_____________________________________________________________________________|'
  echo
  echo ' Command to prepare an image of the same field for another wavelength:'
  echo   
  echo ' '$scriptname" $instrument $scanspeedorbeam $mapmaker $fieldname <IMAGE> $pix0 $nx0 $ny0 $ra0 $dec0 $rota"
  echo
  echo ' You may need to edit first 5 command-line parameters.'

  fundone=$fun; fun=$funo
}
#_________________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________________

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

'INITIALIZE' $*; chk_rc

'EXTRACT_IMAGES'; chk_rc

'GET_PIXEL_SIZES'; chk_rc

'GET_BEAM_SIZES'; chk_rc

'CHANGE_UNITS'; chk_rc

'READ_MORE_INFO'; chk_rc

'CORRECT_HEADERS'; chk_rc

'RESAMPLE_IMAGES'; chk_rc

'CORRECT_SWARP_HEADERS'; chk_rc

'MAKE_DETECTION_IMAGE'; chk_rc

'CREATE_MASK_IMAGE'; chk_rc

'FINISH'; chk_rc

cdate=`date +%d\ %b\ %Y\ %a\ %H:%M:%S\ %Z`
echo
echo ' '$script' DONE.'
echo
echo ' '$cdate

} | tee -a $logfile
exit
#_________________________________________________________________________________________________________________________________
