!> Sort characters of a string.
!!
!! Strings are read from stdin, characters of the strings sorted in ascending
!! order. Result is printed to stdout. Program can be left by providing the
!! string \c STOP.
!!
!! \warning The program does not handle multibyte characters correctly. 
!! It fails if language specific characters are entered in a Unicode or UTF-8
!! environment.
!! \warning Strings exceeding the specified maximal length are chopped without
!! warning.
!!
!! \author Bálint Aradi
!!
program character_sorting
  implicit none

  integer, parameter :: maxlen = 20     ! Maximal string length
  
  character(maxlen) :: string
  character :: tmp                      ! Temporary buffer (1 character)
  integer :: ii, nn
  logical :: swapped

  lpmain: do
    read(*,*) string
    if (string == "STOP") then
      exit lpmain
    end if
    nn = len_trim(string)
    swapped = .true.
    do while (swapped)
      swapped = .false.
      do ii = 1, nn - 1
        if (string(ii:ii) > string(ii+1:ii+1)) then
          tmp = string(ii:ii)
          string(ii:ii) = string(ii+1:ii+1)
          string(ii+1:ii+1) = tmp
          swapped = .true.
        end if
      end do
      nn = nn - 1
    end do
    write(*,"(A)") trim(string)
  end do lpmain
  
end program character_sorting
