      program fav2csv  ! 10Aug2024/uk mit Hilfe von ChatGPT
c
      implicit none
      character(len=3000000) :: bigstring
      character(len=5000) :: line, waypoint
      integer :: pos, endpos, unit, read_stat, startpos

      ! Öffnen der Datei
      open(unit=10, file='Favoriten.gpx', status='old', action='read')
      open(unit=20, file='Favoriten.CSV', status='replace', 
     &     action='write')

      ! Initialisieren des Strings
      bigstring = ''

      ! Datei in einen langen String einlesen
      do
          read(10, '(A)', iostat=read_stat) line
          if (read_stat /= 0) then
              exit
          endif
          bigstring = trim(bigstring) // line
      end do

      ! Suche nach <wpt> und </wpt> und extrahiere die Informationen
      pos = 1
      do while (pos > 0)
          startpos = index(bigstring(pos:), '<wpt lat=') + pos - 1
          if (startpos < pos) exit  ! Wenn kein neues <wpt> gefunden wird
          endpos = index(bigstring(startpos:), '</wpt>') + startpos - 1
          if (endpos < startpos) exit  ! Wenn kein </wpt> gefunden wird
          waypoint = bigstring(startpos:endpos+len('</wpt>')-1)
          call extract_info(waypoint)
          write(20, '(A)') trim(waypoint)
          pos = endpos + len('</wpt>')  ! Update pos to search after the current </wpt>
      end do

      close(10)
      close(20)
      end

      subroutine extract_info(wpt)
      implicit none
      character(len=*), intent(inout) :: wpt
      character(len=20) :: lat, lon
      character(len=5000) :: name
      integer :: pos1, pos2, pos3

      pos1 = index(wpt, 'lat="') + 5
      pos2 = index(wpt(pos1:), '"') + pos1 - 2
      lat = wpt(pos1:pos2)

      pos1 = index(wpt, 'lon="') + 5
      pos2 = index(wpt(pos1:), '"') + pos1 - 2
      lon = wpt(pos1:pos2)

      pos1 = index(wpt, '<name>') + 6
      pos3 = index(wpt, '</name>') - 1
      name = wpt(pos1:pos3)

      wpt = trim(lat) // ',' // trim(lon) // ',' // trim(name)
      end subroutine extract_info

