!> Prints the required number of elements in a Fibonacci series.
!!
!! The program reads the number of elements to calculate and to print from
!! stdin, computes them and prints them on the fly to stdout. It stops the
!! calculation of the series if there is a danger of integer
!! overflow. (Appropriate error message is printed.) The program can be left by
!! entering 0 or a negative number for the number of elements to calculate.
!!
!! \author Bálint Aradi
!!
program fibonacci
  implicit none

  integer :: limit
  integer :: f1, f2, tmp
  integer :: ii

  ! Main loop for reading in the limits and calculate the series.
  lpmain: do
    write(*,*)
    write(*,*) "> How many elements to calculate? (0 or negative number to &
        &stop):"
    read (*,*) limit

    if (limit <= 0) then
      exit lpmain
    end if

    write(*,*)
    write(*,*) "The first ", limit, " elements of the Fibonacci series:"

    f1 = 1
    f2 = 1

    write(*,*) 1, f1
    if (limit >= 2) then
      write(*,*) 2, f2
    end if
    if (limit >= 3) then
      do ii = 3, limit
        ! Prevent overflow
        if (huge(tmp) - f1 < f2) then
          write(*,*)
          write(*,*) "Error: Calculation stopped to prevent overflow!"
          exit
        end if
        tmp = f1 + f2
        f1 = f2
        f2 = tmp
        write(*,*) ii, f2
      end do
    end if

  end do lpmain
  
end program fibonacci
