      program shortenGPX  ! 06Aug2024/uk
c
c     - Read *.gpx-File gerated by GSAK
c     - Convert it to a *.CSV - File
c     - Make sure, the first character in the name - if it starts with a " -
c       is onverted to a '  (otherweise we have problems filling it to SQlite
c
      implicit none
      integer i,k,j(4), n, m1,m2, trimlen
      real xlat,xlon
      character inpfile*80, gpxfil*80, gpxfile*80, cline*80,
     &          gpxfileout*80, cname*100
      logical favoriten
c
      call GETARG(1,gpxfile)
      if(gpxfile.eq."Favoriten.gpx")then
         favoriten=.true.
      else
         favoriten=.false.
      endif
      open(3,file=gpxfile,status="old")
ccc      write(6,*) gpxfile
      open(4,file="outfile.CSV",status="unknown")
  1   read(3,'(a)', end=999) cline
      i=index(cline(1:10)," <wpt lat=")
      if(i.gt.0)then
         n=0
         do k=1,len(cline)
            if(cline(k:k).eq.'"')then 
               n=n+1
               j(n)=k
            endif
         enddo
ccc         write(6,*) j(1),j(2),j(3),j(4)
ccc         write(6,*) cline
         read(cline(j(1)+1:j(2)-1),*) xlat
         read(cline(j(3)+1:j(4)-1),*) xlon
ccc         write(6,*) xlat,xlon
      else
         goto 1
      endif
      if(.not.favoriten)then
         read(3,'(a)') cline
      endif
      read(3,'(a)') cline
      m1=index(cline,"<name>")
      m2=index(cline,"</name>")
      if(.not.favoriten)then
         read(cline(m1+8:m2-1),'(a)') cname   ! Cachetyp und Blank weglassen
      else
         read(cline(m1+6:m2-1),'(a)') cname
      endif
ccc      write(4,*) xlat,",",xlon,",",cname
      if(cname(1:1).eq."""")then    ! Datenbank will kein " als ersters Zeichen
         cname(1:1)="'"
      endif
      write(4,'(f11.6,a,f12.6,a,a)') xlat,",",xlon,",",
     &                               cname(1:trimlen(cname))
c
      goto 1
c
 999  continue
c
      end ! of shortenGPX.f
c
      integer function TRIMLEN(t)   ! Urs Kradolfer, June 1986
c
c     Call:    nc=TRIMLEN(char)
c
c          --> nc says, how many characters the input-string has
c              (ignoring trailing blanks!).
c
      implicit none
      character t*(*)
      do trimlen=LEN(t),1,-1
        if(t(trimlen:trimlen).ne.' ') goto 9
      enddo
      trimlen=1
  9   continue
      end ! of integer function trimlen
c
