unit_tex Function

private pure function unit_tex(u) result(t)

Typeset unit w/ negative exponents.

a/b^n/c -> a b^{-n} c^{-1}, cc -> cm^3, Msun, Rsun, Lsun -> solar symbols. Other forms returned as written.

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: u

Unit as header or suffix gives it.

Return Value character(len=96)


Source Code

   pure function unit_tex(u) result(t)
      !! Typeset unit w/ negative exponents.
      !!
      !! `a/b^n/c` -> `a b^{-n} c^{-1}`, `cc` -> `cm^3`, `Msun`, `Rsun`, `Lsun` -> solar symbols.
      !! Other forms returned as written.
      ! Arguments
      character(len=*), intent(in) :: u
         !! Unit as header or suffix gives it.
      character(len=96) :: t
      character(len=64) :: rest, seg, base, ex
      character(len=*), parameter :: LETTERS = &
         'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      integer(int32) :: p, nb, e, ios, nseg

      t = ''; nseg = 0
      rest = adjustl(u)
      if (trim(rest) == 'gcc') rest = 'g/cc'
      do
         nseg = nseg + 1
         p = index(rest, '/')
         if (p == 0) then
            seg = rest
         else
            seg = rest(1:p - 1)
         end if
         nb = verify(seg, LETTERS) - 1
         if (nb < 0) nb = len_trim(seg)
         if (nb == 0) then
            if (nseg /= 1 .or. trim(seg) /= '1') then
               t = u
               return
            end if
         else
            base = seg(1:nb)
            ex = seg(nb + 1:)
            if (ex(1:1) == '^') ex = ex(2:)
            if (ex(1:1) == '{' .and. index(ex, '}') == len_trim(ex)) ex = ex(2:len_trim(ex) - 1)
            e = 1
            if (len_trim(ex) > 0) then
               ios = 1
               if (verify(trim(ex), '+-0123456789') == 0) read (ex, *, iostat=ios) e
               if (ios /= 0) then
                  t = u
                  return
               end if
            end if
            if (nseg > 1) e = -e
            select case (trim(base))
            case ('cc'); base = 'cm'; e = 3*e
            case ('Msun'); base = 'M_\odot'
            case ('Rsun'); base = 'R_\odot'
            case ('Lsun'); base = 'L_\odot'
            end select
            if (len_trim(t) > 0) then
               t = trim(t)//' '//trim(base)
            else
               t = base
            end if
            if (e /= 1) then
               write (ex, '(i0)') e
               t = trim(t)//'^{'//trim(ex)//'}'
            end if
         end if
         if (p == 0) exit
         rest = rest(p + 1:)
      end do
   end function unit_tex