	program main

	parameter (MAXDAT=1000000)
	real nvar,value(100,MAXDAT),sum,sumsq,mean,variance,
     +	 cvsq,b,a,f,new(MAXDAT),nnew(MAXDAT),newsum,newmean,nnewmean,
     +	 newvar,nnewsum,newsumsq,nnewsumsq,nnewvar,dat(5)
	character char*60

c
c  Open data file
c
	f =0.7
      open(1,file='data-2.txt')
	read(1,*)
      read (1,*) nvar
	do i=1,nvar
		read(1,*) char
	end do
c
c Open Output File
c
	open(2,file='ilc.out')
	write(2,*) 'Indirect Lognormal Correction'
	write(2,*) '2'
	write(2,*) 'Original Value'
	write(2,*) 'Corrected Value'
c
c Read data values and compute mean and variance
c
	do i=1,MAXDAT
		read(1,*,end=99) (value(j,i),j=1,10)
		nd=nd+1
		sum=sum+value(8,i)
		sumsq=sumsq+value(8,i)*value(8,i)
	end do
 99	continue
      mean=sum/nd
	variance=sumsq/(nd-1)-mean*mean
	cvsq=variance/(mean*mean)
	write(*,*) ' Original Mean           =',mean
	write(*,*) ' Original Variance       =',variance
	write(*,*) ' Number of Data          =',nd
      write(*,*) ' Original Coeff. of Var. =',sqrt(cvsq)

c
c Sort data to do quantile transformation
c
c	call sortem(1,nd,value,0,b,c,d,e,f,g,h)
c
c Compute coefficients a and b for transformation
c
	b=sqrt((log(f*cvsq+1))/(log(cvsq+1)))
	a=mean/(sqrt(f*cvsq+1))*((sqrt(cvsq+1))/(mean))**b
	write(*,*) ' Coefficient a           =',a
	write(*,*) ' Coefficient b           =',b
c
c Transform data and compute mean
c
	do i=1,nd
		new(i)=a*value(8,i)**b
		newsum=newsum+new(i)
		newsumsq=newsumsq+new(i)*new(i)
	end do
	newmean=real(newsum)/real(nd)
	newvar=real(newsumsq)/real(nd-1)-newmean*newmean
	write(*,*) ' Temporal Mean           =',newmean
	write(*,*) ' Temporal Variance       =',newvar
c
c Rescale mean  and write output
c
	do i=1,nd
		nnew(i)=mean/newmean*new(i)
		write(2,100) nnew(i)
		nnewsum=nnewsum+nnew(i)
		nnewsumsq=nnewsumsq+nnew(i)*nnew(i)
	end do
	nnewmean=real(nnewsum)/real(nd)
	nnewvar=real(nnewsumsq)/real(nd-1)-nnewmean*nnewmean
	write(*,*) ' Corrected Mean          =',nnewmean
	write(*,*) ' Corrected Variance      =',nnewvar
100	format(f12.5)
	end
	

