#!/bin/bash
banner[1]='_______________________________________________________________________________'
banner[2]='                                                                               '
banner[3]='             CONVOLVE = Convolve Image to Desired Lower Resolution             '
banner[4]='              Alexander Men`shchikov, SAp IRFU CEA Saclay, France              '
banner[5]='                                Version 1.140127                               '
banner[6]='_______________________________________________________________________________'
#
# Development initiated on 2010/12/24 by A.M. (alexander.menshchikov@cea.fr)
#___________________________________________________________________________________________________________________________________

CONDITIONS ()
{
  echo '#  _____________________________________________________________________________'
  echo '# |                                                                             '
  echo '# |            CONVOLVE = Convolve Image to Desired Lower Resolution            '
  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:                                '
  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.                     '
}
#___________________________________________________________________________________________________________________________________
#
nparams=${#*}; commandline="$*"; scriptname=`basename "$0"`; script=`echo $scriptname | tr a-z A-Z`
scriptnameup=`echo $scriptname | tr a-z A-Z`; scriptnamelo=`echo $scriptname | tr A-Z a-z`
currentres=$1; desiredres=$2; fitsimage=$3; imageout=$4; verb=$5
#_________________________________________________________________________________________________________________________________

chk_rc ()
{
# Internal function 'chk_rc' for checking return code and exiting if abnormal termination.
 
  local rc=$?
  if [[ "$rc" != "0" ]]
  then where=$script; if [[ $fun != "" ]]; then where=$where': '$fun; fi; echo; echo ' ERROR in '$where': Aborted.'; exit "$rc"
  fi
}
#_________________________________________________________________________________________________________________________________

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
}
#___________________________________________________________________________________________________________________________________

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

headerinfo[1]='#  ___________________________________________________________________________________________________________________________________'
headerinfo[2]='# |                                                                                                                                   '
headerinfo[3]='# | CONVOLVE = Convolve Image to Desired Lower Resolution = '$versnum' = Alexander Men'\''shchikov, SAp IRFU CEA Saclay            '
headerinfo[4]='# |___________________________________________________________________________________________________________________________________'

if [[ "$*" == ":" ]]
then
  echo "${headerinfo[3]:3:98}"
  exit 0
fi

'CONDITIONS' >> '+log.CONDITIONS'

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

if [[ $verb == "" ]]; then verb='-verb2'; fi

if [[ $fitsimage == "" ]]
then
  echo
  echo ' USAGE: convolve <currentres> <desiredres> <image> [<imageout>] [-verb[0|1|2]]'
  echo
  echo '        This script will convolve any FITS image from current resolution'
  echo '        <currentres> to a desired lower resolution <desiredres> (in arcseconds).'
  echo
  echo '        If only <currentres> and <desiredres> are specified on the command line,'
  echo '        the script will just returns the additional smoothing beam required.'

  if [[ $currentres != "" && $desiredres != "" ]]
  then
    echo; echo ' '$scriptname $*
    smobeam=$(echo "scale=9; sqrt($desiredres*$desiredres-$currentres*$currentres)" | bc); chk_rc
    echo; echo ' Additional smoothing beam: '$smobeam' arcsec'
  fi
  echo; exit 1
fi

echo; echo ' '$scriptname $*
smobeam=$(echo "scale=9; sqrt($desiredres*$desiredres-$currentres*$currentres)" | bc); chk_rc
echo; echo ' Additional smoothing beam: '$smobeam' arcsec'

fitsimage=${fitsimage/.fits/}

# Get the pixel sizes in both dimensions (in degrees).
  
'readhead' save CDELT1 CDELT2 $fitsimage'.fits' $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 sizes in arcseconds.

dxas=$(echo "scale=20; $dx*3600" | bc); chk_rc
dyas=$(echo "scale=20; $dy*3600" | bc); chk_rc

addpix=$(echo "scale=20; 3*$smobeam/$dxas" | bc); chk_rc

if [[ $imageout == "" ]]
then
  outfile=$fitsimage'.r'${desiredres/./p}'.fits'
else
  outfile=$imageout
fi

'modfits' expand $addpix $fitsimage'.fits' -o $outfile $verb; chk_rc
'fftconv' $smobeam 0 $outfile -o $outfile $verb; chk_rc
'modfits' border -$addpix $outfile -o $outfile $verb; chk_rc

exit
