!
!  Read catalogue
!
!
!  Copyright © 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/>.
!

!  *  proper motion is omited


module catio

!  use iso_fortran_env

  implicit none

  integer, parameter, private :: dbl = selected_real_kind(15)

contains

  subroutine catalogue(cat,labels,alpha,delta,mag,catid)

    use fitsio

    character(len=*), intent(in) :: cat
    character(len=*), dimension(:), intent(in) :: labels
    real(dbl), dimension(:), allocatable, intent(out) :: alpha,delta,mag
    character(len=*), intent(out) :: catid

    integer, parameter :: frow = 1, felem = 1
    real(dbl), parameter :: nullval = 99.99999

    integer :: nrows, status, i
    integer, dimension(size(labels)) :: cols
    character(len=FLEN_CARD) :: buf
    logical :: anyf


    status = 0

    ! open and move to a table extension
    call fttopn(15,cat,0,status)
    call ftgnrw(15,nrows,status)
    if( status /= 0 ) goto 666

    ! define reference frame and identification of catalogue
    call ftgkys(15,'EXTNAME',catid,buf,status)
    if( status == KEYWORD_NOT_FOUND ) then
       catid = ''
       status = 0
    end if

    ! find columns by labels
    do i = 1, size(labels)
       call ftgcno(15,.true.,labels(i),cols(i),status)
    end do
    if( status /= 0 ) goto 666

    if( nrows == 0 ) stop 'catio: no stars available.'

    allocate(alpha(nrows),delta(nrows),mag(nrows))
    call ftgcvd(15,cols(1),frow,felem,nrows,nullval,alpha,anyf,status)
    call ftgcvd(15,cols(3),frow,felem,nrows,nullval,delta,anyf,status)
    call ftgcvd(15,cols(5),frow,felem,nrows,nullval,mag,anyf,status)

    call ftclos(15,status)
    if( status /= 0 ) goto 666

    return

666 continue

    call ftclos(15,status)
    call ftrprt('STDERR',status)

    if( allocated(mag) ) deallocate(mag,alpha,delta)

    stop 'CATSIO'

  end subroutine catalogue

end module catio
