#!/bin/bash
banner[1]='_______________________________________________________________________________'
banner[2]='                                                                               '
banner[3]='               RESAMPLE = Resample Image to Different Pixel Size               '
banner[4]='              Alexander Men`shchikov, SAp IRFU CEA Saclay, France              '
banner[5]='                         Using SWARP by Emmanuel Bertin                        '
banner[6]='                                Version 1.141027                               '
banner[7]='_______________________________________________________________________________'
#
# Development initiated on 2009/09/30 by A.M. (alexander.menshchikov@cea.fr)
#___________________________________________________________________________________________________________________________________

CONDITIONS ()
{
  echo '#  _____________________________________________________________________________'
  echo '# |                                                                             '
  echo '# |              RESAMPLE = Resample Image to Different Pixel Size              '
  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`; scriptnamelo=`echo $scriptname | tr A-Z a-z`; hell='/dev/null'
image=$1; pixel=$2; nx=$3; ny=$4; coord1=$5; coord2=$6; rotangle=$7
#___________________________________________________________________________________________________________________________________

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

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 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 8 ]]; then break; fi
done
} < $0

headerinfo[1]='#  ___________________________________________________________________________________________________________________________________'
headerinfo[2]='# |                                                                                                                                   '
headerinfo[3]='# | RESAMPLE = Resample Image to Different Pixel Size = '$versnum' = Alexander Men'\''shchikov, SAp IRFU CEA Saclay                '
headerinfo[4]='# |___________________________________________________________________________________________________________________________________'

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

'CONDITIONS' >> '+log.CONDITIONS'

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

if [[ $pixel  == '' ]]; then pixel='0.123456789'; fi
if [[ $nx     == '' ]]; then nx=10; fi
if [[ $ny     == '' ]]; then ny=10; fi
if [[ $coord1 == '' ]]; then coord1='00:00:00.00'; fi
if [[ $coord2 == '' ]]; then coord2='00:00:00.0'; fi
coosys='EQUATORIAL'

'swarp' 2>$hell; rc=$?
if [[ $rc -eq 126 ]]; then echo; echo ' '$script': ERROR:'; echo; echo "   Trouble executing binary swarp..." ; echo; exit 99; fi
if [[ $rc -eq 127 ]]; then echo; echo ' '$script': ERROR:'; echo; echo "   Utility swarp not found..." ; echo; exit 99; fi

if [[ $image == '' ]]
then
  echo
  echo ' USAGE: '$scriptname' <image> [<pixel>] [<nx> <ny> <coord1> <coord2> <rotangle>]'
  echo
  echo '        where <image>  is the FITS image to resample'
  echo '              <pixel>  is the desired pixel size (arcseconds)'
  echo '              <nx>     is the image size in the 1st dimension'
  echo '              <ny>     is the image size in the 2nd dimension'
  echo '              <coord1> is the 1st coordinate of projection center (hh:mm:ss.ss)'
  echo '              <coord2> is the 2nd coordinate of projection center (dd:mm:ss.s)'
  echo '            <rotangle> is the rotation angle (east of north, as position angle)'
  echo
  echo '        resampled image is projected in the equatorial coordinate system'
  echo '        with optional rotation'
  echo; exit 99
fi

if [[ ${pixel:0:1} == '-' ]]
then
  yorno='N'
  pixel=${pixel:1}
else
  yorno='Y'
fi

image=${image/.fits/}

options1='-write_xml N -fscalastro_type NONE'
options2='-celestial_type '$coosys' -projection_type TAN'

if [[ $coord1 == '00:00:00.00' || $coord2 == '00:00:00.0' ]]
then
  options3='-center_type ALL' 
else
  options3='-center_type MANUAL -center '$coord1,$coord2 
fi
options4='-back_type MANUAL -back_default 0.0 -subtract_back N'
options5='-resample '$yorno' -pixelscale_type MANUAL -pixel_scale '$pixel 
options6='-combine Y -image_size '$nx,$ny

# One can rotate resampled images using SWarp.

if [[ $rotangle != "" ]]
then
  pixdeg=$(echo "scale=20; $pixel/3600" | bc); chk_rc
  rotrad=$(echo "scale=20; ($rotangle)*3.14159265/180" | bc); chk_rc

# Hanisch & Wells (1988), WCS representations within FITS format

  CD1_1=$(echo "scale=20; -$pixdeg*c($rotrad)" | bc -l); chk_rc
  CD1_2=$(echo "scale=20; -$pixdeg*s($rotrad)" | bc -l); chk_rc
  CD2_1=$(echo "scale=20; -$pixdeg*s($rotrad)" | bc -l); chk_rc
  CD2_2=$(echo "scale=20;  $pixdeg*c($rotrad)" | bc -l); chk_rc

# SWarp will read this ASCII file and use it while resampling.

  echo 'CD1_1   = '$CD1_1' / linear projection matrix'  > 'coadd.head'
  echo 'CD1_2   = '$CD1_2' / linear projection matrix' >> 'coadd.head'
  echo 'CD2_1   = '$CD2_1' / linear projection matrix' >> 'coadd.head'
  echo 'CD2_2   = '$CD2_2' / linear projection matrix' >> 'coadd.head'
  echo 'END'  >> 'coadd.head'
fi

echo
echo ' Executing: swarp' $image'.fits'
echo '                  '$options1
echo '                  '$options2
echo '                  '$options3
echo '                  '$options4
echo '                  '$options5
echo '                  '$options6

'swarp' $image'.fits' $options1 $options2 $options3 $options4 $options5 $options6

\mv 'coadd.fits' $image'.resamp.fits'; chk_rc; \rm 'coadd.weight.fits' 2>&1; chk_rc
                                                     
if [[ $pixel == '0.123456789' ]]
then echo;
  echo '  WARNING: Used generic pixel size (pixel = '$pixel').'
  echo '     INFO: Specify actual pixel size to get a useful image.'
  echo
  echo '    USAGE: '$scriptname' <image> [[-]<pixel> <nx> <ny> <coord1> <coord2>]'
  echo
fi
if [[ $nx -eq 10 || $ny -eq 10 ]]
then echo;
  echo '  WARNING: Used generic pixel numbers (nx = '$nx', ny = '$ny').'
  echo '     INFO: Specify actual numbers of pixels to get a useful image.'
  echo
  echo '    USAGE: '$scriptname' <image> [[-]<pixel> <nx> <ny> <coord1> <coord2>]'
  echo
fi
if [[ $coord1 == '00:00:00.00' || $coord2 == '00:00:00.0' ]]
then echo;
  echo '  WARNING: No projection center coordinates were specified.'
  echo '     INFO: Specify actual coordinates to fix the center manually.'
  echo
  echo '    USAGE: '$scriptname' <image> [[-]<pixel> <nx> <ny> <coord1> <coord2>]'
  echo
fi

exit $?
