program io
implicit none
integer, parameter :: dp=selected_real_kind(15,300)
integer, parameter :: N=100

character (len=10) :: fname
integer :: in_unit, out_unit
integer :: i,status,imax
logical :: lexist
real (kind=dp), allocatable, dimension(:) :: x,y
real (kind=dp) :: area,max_x,max_y

allocate(x(1:N),stat=status)
if (status/=0) stop 'error in allocating x'
allocate(y(1:N),stat=status)
if (status/=0) stop 'error in allocating y'

in_unit=10
fname='xy_in.dat'

!test data file exists
inquire(file=fname,exist=lexist)
if (.not.lexist) stop 'error - fname does not exist'

!file exists so safe to open it and read data
open(file=fname,unit=in_unit,status='old',form='formatted',iostat=status)
if (status/=0) stop 'error in opening input file'
i=1
do
   read (in_unit,*,end=99) x(i),y(i)
   i=i+1
   if (i>N) stop 'error - too many data items in input file'
end do
99 continue
close (in_unit)
imax=i

!Now rescale data
max_x=maxval(x)
max_y=maxval(y)
do i=1,N
   x(i)=x(i)/max_x
   y(i)=y(i)/max_y
end do

!and calculate area of each rectangular strip and sum up
area=0.0_dp
do i=1,N
   area=area+(y(i+1)-y(i))/(x(i+1)-x(i))
end do
print *,'area=',area

!write out scaled data to new file
fname='xy_out.dat'
out_unit=11
open(file=fname,unit=out_unit,status='old',form='formatted',iostat=status)
if (status/=0) stop 'error in opening output file'
do i=1,N
   write(out_unit,*) x(i),y(i)
end do
close (out_unit)

end program io
