      program collatz
      implicit none
      character (len = 100) :: file_name  
      integer, parameter :: big = selected_int_kind(11)
      integer  :: n
      call getarg( 1, file_name )  
      OPEN(unit = 7, file = file_name)
      read (7,*) n
      write (unit = *, fmt = "(I0)") search_collatz(n)

      contains

      function collatz_next (n) result (r)
      implicit none
      integer (kind = big)  :: r,n
      if (0 == mod(n,2)) then
         r = n/2
      else
         r = 1 + 3*n
      end if 
      end function collatz_next
      
      function collatz_length (n) result (r)
      implicit none
      integer (kind = big)  :: t
      integer :: n,r
      r = 1
      t = n
      do 
         if (1 == t) then
         exit
         end if
         r = r + 1
         t = collatz_next(t)
      end do
      end function collatz_length
      
      function search_collatz (n) result (r)
      implicit none
      integer n,r,i,max,max_val,temp_val
      integer (kind = big) :: t
      t = n
      do i = 1,n-1
         temp_val = collatz_length(i)
         if (temp_val > max_val) then
         max = i
         max_val = temp_val
      end if
      end do
      r = max
      end function search_collatz
      end program collatz
