  program read_ascii_dat
  
! -----------------------------------------------------------------------------
! Frame   : Procedures and program used in JGR data report 
!           "Use of twenty years CLUSTER/FGM data to observe the mean behavior 
!           of the magnetic field and current density of Earth's magnetosphere" 
!           By P. Robert and M. Dunlop, October 2021
!
! Program : read_ascii_dat.f90
! Object  : Read a *dat ascii file of the DATA_Curl_Div database
! Input   : path of a Curl file
! Output  : comments
! Author  : P. Robert, LPP-ScientiDev, 2020-Oct.2021
! Mail    : patrick.robert@lpp.polytechnique.fr
! -----------------------------------------------------------------------------
  
  
  real(kind=4), dimension(4) :: Pxe,Pye,Pze,Bxe,Bye,Bze
  
  character(len=255)         :: file_curl_div
  character(len=24)          :: datiso
  
  logical                    :: file_exists

  
  print*
  print*,'-----------------------------------'
  print*,'read_ascii_dat.exe'
  print*,'-----------------------------------'
  print*

! read data file path and check if exists
    
  print*, 'path of file to read ? (ex: DATA_PRo/DATA_Curl_Div_raw/2001/2001_01/Curl_FGM_SPIN_20010117.dat)'
  read(*,'(a)', iostat=iosta) file_curl_div
  
  if(iosta /= 0) stop '*** read_ascii_dat : bad filename'
  print*, 'file to read: ',trim(file_curl_div)
  
  INQUIRE(FILE=trim(file_curl_div), EXIST=file_exists)
  print*,file_exists
  
  if(file_exists) then
     open(1, file=file_curl_div)
                  else
     stop '*** read_ascii_dat : input file does not exist'
  endif

! read number of blocks
  
  read(1,*,iostat=iosta) nbloc
  print*, 'read ',trim(file_curl_div),'  nbloc=',nbloc

! read data and print first 10

  DO n=1,nbloc
  
  read(1,200,iostat=iosta2,end=20) datiso,Pxe,Pye,Pze,Bxe,Bye,Bze,GJxe,GJye,GJze,curl,div,ajb,elong,plana,diptan 
  200 format(a24,/,12E14.6,/,12E14.6,/,6E11.3,2E10.2,E11.3)

  if(iosta2 /= 0)  stop '*** read_ascii_dat : error during reading file' 
  
  if(n < 10) then
      print*,'---------------------------------'
      print*,'n=',n    
      print*,'datiso=',datiso
      print*,'Pxe=',Pxe
      print*,'Pye=',Pye
      print*,'Pze=',Pze
      print*
      print*,'Bxe=',Bxe
      print*,'Bye=',Bye
      print*,'Bze=',Bze
      print*
      print*,'Jxe=',Gjxe
      print*,'Jxe=',Gjye
      print*,'Jxe=',Gjze
      print*
      print*,'curl=',curl
      print*,'div =',div
      print*,'ajb=',ajb
      print*,'elong,plana=',elong,plana
      print*,'diptan=',diptan
      print*
  endif  
  
  if(n==11) print*,'Please wait during reading file...'
  
  ENDDO
  
  close(1) 
  print*
  print*,'all ',n,' records have been read'
  stop '    read_ascii_dat : NORMAL TERMINATION'
  
  20 continue
  stop '*** read_ascii_dat : ABNORMAL TERMINATION'
  end

