!
!  find stars
!
!  Copyright © 2013-4, 2016 F.Hroch (hroch@physics.muni.cz)
!
!  This file is part of Munipack.
!
!  Munipack is free software: you can redistribute it and/or modify
!  it under the terms of the GNU General Public License as published by
!  the Free Software Foundation, either version 3 of the License, or
!  (at your option) any later version.
!  
!  Munipack is distributed in the hope that it will be useful,
!  but WITHOUT ANY WARRANTY; without even the implied warranty of
!  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!  GNU General Public License for more details.
!  
!  You should have received a copy of the GNU General Public License
!  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.


program find

  use fitsio
  use fitsfind

  implicit none

  character(len=4*FLEN_FILENAME) :: line,key,val
  character(len=FLEN_FILENAME) :: outname, file,backup, output = ''
  character(len=FLEN_KEYWORD), dimension(2) :: fkeys
  real :: lothresh = 7.0
  real :: threshold = 7.0
  real :: fwhm = 3.0
  real :: readns = -1
  real :: satur = -1
  real :: shrplo = 0.2, shrphi = 1.0
  real :: rndlo = -1.0, rndhi = 1.0
  integer :: maxsky = 10000
  logical :: verbose = .false., plog = .false.
  integer :: eq,istat

  fkeys(1) = FITS_KEY_SATURATE
  fkeys(2) = FITS_KEY_READNS

  do
     read(*,'(a)',end=20) line

     eq = index(line,'=')
     if( eq == 0 ) stop 'Improper input.'
     key = line(:eq-1)
     val = line(eq+1:)

     if( key == 'VERBOSE' ) then

        read(val,*) verbose

     else if( key == 'PIPELOG' ) then

        read(val,*) plog

     else if( key == 'FWHM' ) then

        read(val,*) fwhm

     else if( key == 'READNOISE' ) then

        read(val,*) readns

     else if( key == 'SATURATE' ) then

        read(val,*) satur

     else if( key == 'THRESHOLD' ) then

        read(val,*) threshold

     else if( key == 'LOWER_THRESHOLD' ) then

        read(val,*) lothresh

     else if( key == 'ROUND_LOWER' ) then

        read(val,*) rndlo

     else if( key == 'ROUND_HIGHER' ) then

        read(val,*) rndhi

     else if( key == 'SHARP_LOWER' ) then

        read(val,*) shrplo

     else if( key == 'SHARP_HIGHER' ) then

        read(val,*) shrphi

     else if( key == 'FITS_KEY_SATURATE' ) then

           read(val,*) fkeys(1)

     else if( key == 'FITS_KEY_READNOISE' ) then

           read(val,*) fkeys(2)

     else if( key == 'FILE' ) then

        read(val,*) file, backup, output

        istat = 0
        call fitsback(file,backup,output,.false.,outname,istat)

        if( verbose ) then
           write(*,*)
           write(*,'(a)') "========  Processing file: "//trim(outname)
           write(*,*)
        end if
           
        call ffind(outname,maxsky,verbose,plog,fkeys,fwhm,readns, &
             satur,lothresh,threshold,shrplo,shrphi,rndlo,rndhi)

     end if

  end do

20 continue

  stop 0

end program find
