program metheth_nmf
implicit none

integer					:: i,j,k,l,m,n,s,nmoves,index1,index2,index3,iacc,iacc_total,cutoff,&
Acutoff,ncheck,nprm, ngaus,gauscomp,nbkgprm,nop,maxmoves,nprint,Fno
real, allocatable		::r(:)
real*8, allocatable		:: D(:,:),C(:,:),H(:,:),A(:,:),A_diff(:,:),C_trial(:,:),H_trial(:,:),&
A_trial(:,:),A_diff_trial(:,:),G(:,:,:),Gpress(:,:),Gcurve(:,:),&
Gtot(:),bkgprm(:,:),bkgpress(:),bkg(:),pvalue(:),Ctot(:),z(:),dz(:),press(:),dtemp(:)
real*8					:: temperature,increment,incfac,tempfac,random,random2,random3,Fnorm,&
Fnorm_trial,Fdiff,prob,rmin,Crmin,dx,Armin,p0,bkgk,bkgj,rmax,Qmax,f,t,pi,temppress,Fcheck,Fcheckdiff
character (len=48)		:: line
character (len=63)		:: rundir,directory,datafile
character(len=8)		:: cystring
character(len=255)		:: cwd
character (len=1)		:: MC,WV

call init_random_seed()

maxmoves=150000000
nprint=1000000
Fno=1000000
Fcheck=100

!------Experiment-dependent variables------!
write(*,*)'Enter number of pressure points:'
read(*,*)m
allocate(press(m))
do i=1,m
	write(6,'(a15,i2,a8)',advance='no') 'Enter pressure ',i, ' (GPa): '
	read(*,*) press(i)
	if (press(i)>10.0) write(*,*) '!!!ERROR!!! 10 GPa max.'
end do
write(6,'(a12)',advance='no')'Enter Qmax: '
read(*,*)Qmax
write(6,'(a12)',advance='no')'Enter rmax: '
read(*,*)rmax
write(6,'(a103)',advance='no')'Enter minimum r value to fit pure sample component to (value just'&
's below first expected sample peak): '
read(*,*)Crmin
write(*,*)'Fitting methanol:ethanol components to an rmin of 0.8 Angstroms.'
write(6,'(a37)',advance='no')'Allow individual weight values? (Y/N)'
read(*,*)WV
Armin=0.8
s=m*2
rmin=0.02
dx=0.02
cutoff=(((Crmin/dx)-(rmin/dx))+1)
Acutoff=(((Armin/dx)-(rmin/dx))+1)
n=rmax/dx

allocate(D(n,m))			!Measured PDF data
allocate(C(n,s))			!PTM + sample components
allocate(H(s,m))			!Weights
allocate(C_trial(n,s))		!Trial PTM + sample components
allocate(H_trial(s,m))		!Trial weights
allocate(A(n,m))			!Calculated fit
allocate(A_diff(n,m))		!Fit difference
allocate(A_trial(n,m))		!Trial calculated fit
allocate(A_diff_trial(n,m))	!Trial fit difference
allocate(r(n))				!x values of measured data
allocate(dtemp(n))

!------Info for building metheth PDFs------!
pi=3.14159265
ngaus=10	
nprm=2		
gauscomp=3
nbkgprm=2
nop=4

allocate(G(ngaus,nprm,gauscomp)) 	! 
allocate(Gpress(ngaus,gauscomp))	!
allocate(Gcurve(ngaus,n))			!
allocate(bkgprm(nbkgprm,nprm))		!
allocate(bkgpress(nbkgprm))			!
allocate(bkg(n))					!
allocate(pvalue(nop))				!
allocate(Gtot(n))					!
allocate(Ctot(n))					!
allocate(z(n))						!
allocate(dz(n))						!
Gpress(:,:)=0
G(:,:,:)=0
C(:,:)=0
H(:,:)=0 

!Prms for metheth build. G(ngaus,nprm,gauscomp)!
G(1,1,1)=13.3687   ; G(1,1,2)=0.93997   ; G(1,1,3)=0.00843
G(2,1,1)=38.7864   ; G(2,1,2)=1.12184   ; G(2,1,3)=0.00597
G(3,1,1)=1.69243   ; G(3,1,2)=1.43701   ; G(3,1,3)=0.02823
G(4,1,1)=1.98776   ; G(4,1,2)=1.82020   ; G(4,1,3)=0.059		
G(5,1,1)=1.14016   ; G(5,1,2)=2.10307   ; G(5,1,3)=0.08247
G(6,1,1)=0.73789   ; G(6,1,2)=4.19965   ; G(6,1,3)=0.7789	
G(7,1,1)=0.74228   ; G(7,1,2)=5.89068   ; G(7,1,3)=1.18849
G(8,1,1)=0.56305   ; G(8,1,2)=2.82531   ; G(8,1,3)=0.68215
G(9,1,1)=0.19607   ; G(9,1,2)=7.69561   ; G(9,1,3)=0.74348
G(10,1,1)=0.07021  ; G(10,1,2)=8.55338  ; G(10,1,3)=0.66596
G(1,2,1)=10.6467   ; G(1,2,2)=0.93999   ; G(1,2,3)=0.0069
G(2,2,1)=30.0013   ; G(2,2,2)=1.12432   ; G(2,2,3)=0.00502
G(3,2,1)=1.10191   ; G(3,2,2)=1.42307   ; G(3,2,3)=0.02694
G(4,2,1)=1.32051   ; G(4,2,2)=1.81945   ; G(4,2,3)=0.05761
G(5,2,1)=0.77506   ; G(5,2,2)=2.09224   ; G(5,2,3)=0.08667
G(6,2,1)=0.7761    ; G(6,2,2)=3.57569   ; G(6,2,3)=0.82707
G(7,2,1)=0.70076   ; G(7,2,2)=5.44504   ; G(7,2,3)=1.23998
G(8,2,1)=0.62872   ; G(8,2,2)=2.55983   ; G(8,2,3)=0.36258
G(9,2,1)=0.2857    ; G(9,2,2)=6.99541   ; G(9,2,3)=1.14765
G(10,2,1)=0.006    ; G(10,2,2)=10.2135  ; G(10,2,3)=0.28649

bkgprm(1,1)=7.97582	;	pvalue(1)=4.84938
bkgprm(2,1)=6.17381 ;	pvalue(2)=0.55094
bkgprm(1,2)=7.74072 ;	pvalue(3)=3.85773
bkgprm(2,2)=6.54081	;	pvalue(4)=4.25796

!------Generate methanol:ethanol PTM PDFs------!
do i=1,m
	Ctot=0
	temppress=press(i)
	call makemetheth(m,n,ngaus,nbkgprm,bkgprm,nprm,gauscomp,G,pvalue,temppress,Gtot,Ctot)
	do j=1,n  
		C(j,i)=Ctot(j)  
	end do
end do

!Output convolved PDF!
open(10, file='MEPDFs.txt', status='replace')
write(10,*) 'Analytical methanol:ethanol PTM PDFs', 'Qmax:', Qmax
write(10,*) 'r', (press(i), i=1,m)
do i=1,n
	write(10,*) i*dx, (C(i,j), j=1,m) 
enddo
close(10)
write(*,*) 'Methanol:ethanol PTM PDFs have been generated.'

!------Setting the directory------!
call getcwd(cwd)
rundir =trim(cwd)//'\output'
call execute_command_line('mkdir '//trim(rundir)//'\samplecomponent')
call execute_command_line('mkdir '//trim(rundir)//'\weight')

!------Read in dataset------!
do j=1,m
	write(6,'(a38,f4.2,a6)',advance='no') 'Enter data file name for pressure at, ', press(j), ' GPa: '
	read(*,*)datafile

	open(10, file=trim(datafile),status='old')
		read(10,*) ncheck
		if (ncheck<n) then
			write(*,*) '!!! ERROR !!! Not enough data points.'
		endif
		read(10,*) line
		do i=1,n
			read(10,*) r(i), D(i,j)
		enddo
		if(r(1)/=0.02) then
			write(*,*) '!!! ERROR !!! First data point should be r = 0.02A.'
		endif
		if((r(2)-r(1))/=0.02) then
			write(*,*) '!!! ERROR !!! Bin of 0.02 required.'
		endif
	close(10)
enddo
!------Initialising weights------!
!Assigning random initial values to MMF coefficients!
call random_number(random)
do j=1,m
	H(j,j)=random
	H(j+m,j)=1.0-random
end do

!Calculate initial fit!
A = matmul(C,H)
do i=Acutoff, n
	do j=1, m
		A_diff(i,j) = (D(i,j) - A(i,j))
	end do
end do
Fnorm = norm2(A_diff)

!Read out initial MMF configuration!
open(10,file=trim(rundir)//'\samplecomponent\'//'1'//'.txt', status='replace')	
	do i = 1, n
		write(10,*) (C(i,j), j=m+1,s)
	enddo
close(10)
open(10,file=trim(rundir)//'\weight\'//'1'//'.txt', status='replace')
	do i = 1, s
		write(10,*) (H(i,j), j=1,m)
	enddo
close(10)

!------Monte Carlo parameters------!
write(*,*)'|----------Monte Carlo parameters----------|'
write(6,'(a54)',advance='no')'Would you like to use the default MC parameters? (Y/N)'
read(*,*) MC
if(MC=='Y') then
	temperature=0.01
	increment=0.01
	nmoves=10000
	incfac=1.0
	tempfac=0.99
elseif(MC=='N') then
	write(6,'(a19)',advance='no')'Enter temperature: '
	read(*,*)temperature
	write(6,'(a17)',advance='no')'Enter move size: '
	read(*,*)increment
	write(6,'(a66)',advance='no')'Enter number of moves before temperature and increment reduction: '
	read(*,*)nmoves
	write(6,'(a40)',advance='no')'Enter increment factor (1.0=no factor): '
	read(*,*)incfac
	write(6,'(a34)',advance='no')'Enter temperature product factor: '
	read(*,*)tempfac
end if

open(10,file=trim(rundir)//'\NMF_startingconfig.txt', status='replace')
	write(10,*)'Initial temp:', temperature
	write(10,*)'Initial move size:', increment
	write(10,*)'No. moves before temp. and inc. reduction:', nmoves
	write(10,*)'Increment factor:', incfac
	write(10,*)'Temperature factor:', tempfac
close(10)
open(10,file=trim(rundir)//'\NMF_charge_progress.txt', status='replace')
	write(10,'(A8,X,A8,X,A4,X,A9,X,A13)') 'Moves', 'Accepted', 'Temp', 'Increment', 'Energy(Fnorm)'
	write(10,*) 0, 0, temperature, increment, Fnorm
close(10)

do l = 1, maxmoves  
!Terminal readout of parameters!
	if(mod(l,nmoves)==1)then
		temperature = tempfac*temperature	!Reducing 'temperature'
		increment = increment*incfac		!Reducing the amount by which elements can vary during each MC move 
		write(*,*)'Cycle', l
		write(*,*)'Changing temperature'
		write(*,*)'New temperature:',temperature
		write(*,*)'New increment:',increment
		write(*,*)'Moves proposed, accepted:',nmoves,iacc
		write(*,*)'Current energy:',Fnorm
		write(*,*)

		A_trial = matmul(C,H)
		
		do i=Acutoff, n
			do j=1, m
				A_diff_trial(i,j) = (D(i,j) - A_trial(i,j))
			end do
		end do
		Fnorm_trial = norm2(A_diff_trial)

        iacc=0		
		
	end if
!------Changing sample component------!
	if(mod(l,2)/=0) then
		C_trial(:,:) = C(:,:)
		H_trial(:,:) = H(:,:)
		!Selecting element to vary!
		call random_number(random)
		random = (random * n) + 1
		index1 = int(random)	
		!Which component to vary!
		call random_number(random)
		random = (random * m) + (m+1)
		index2 = int(random)
		
		!if r value is lower than Crmin, then leave at 0!
		if(index1<cutoff) then
			do i=1,cutoff
				C_trial(i,index2)=0
			end do
		endif
		if(index1>=cutoff) then
		!Selecting magnitude of MC move!
			call random_number(random2)
			random2 = random2 * increment
			call random_number(random3)
			if(random3<=0.5) then
				C_trial(index1,index2) = C_trial(index1,index2) + random2
			endif
			if(random3>0.5) then
				C_trial(index1,index2) = C_trial(index1,index2) - random2
			endif
			!Non-negative constraint!
			if(C_trial(index1,index2)<=0) then
				C_trial(index1,index2) = C_trial(index1,index2) + random2
			endif
		end if
				
		!Calculate fit!
		A_trial = matmul(C_trial,H_trial)
		do i=Acutoff, n
			do j=1, m
				A_diff_trial(i,j) = (D(i,j) - A_trial(i,j))
			end do
		end do
		Fnorm_trial = norm2(A_diff_trial)
		Fdiff = Fnorm_trial - Fnorm
	
		!Acceptance criteria!						
		if(Fdiff <= 0.0) then
			C = C_trial
			H = H_trial
			A = A_trial
			A_diff = A_diff_trial
			Fnorm = Fnorm_trial
			iacc=iacc+1
		endif
		if(Fdiff > 0.0) then
			prob = exp(-Fdiff/temperature)
			call random_number(random)
			if(prob > random) then
				C = C_trial
				H = H_trial
				A = A_trial
				A_diff = A_diff_trial
				Fnorm = Fnorm_trial
				iacc=iacc+1
			endif
			if(prob <= random) then
				C_trial = 0.0
				H_trial = 0.0
				A_trial = 0.0
				A_diff_trial = 0.0
				Fnorm_trial = 0.0						
			endif
		endif
	endif
	
!------Changing weights------!		
	if(mod(l,2)==0) then
		C_trial(:,:) = C(:,:)
		H_trial(:,:) = H(:,:)
		!Selecting weight to vary!
		call random_number(random)
		random = (random * m) + 1

		index3 = int(random)
		!Selecting magnitude of MC move!
		call random_number(random)
		random = random * increment
		
		call random_number(random3)
		if(random3<=0.5) then
			if(WV=='Y') then
				H_trial(index3,index3)=H_trial(index3,index3) + random
				H_trial(index3+m,index3)=1-H_trial(index3,index3)
				!Non-negative constraint on weights!
				if(H_trial(index3+m,index3)<0.0) then
					H_trial(index3,index3) = H_trial(index3,index3) - random
					H_trial(index3+m,index3)=1-H_trial(index3,index3)
					cycle
				endif				
			
			elseif(WV=='N') then
				do j=1,m
					H_trial(j,j)=H_trial(j,j)+random
					H_trial(j+m,j)=1-H_trial(j,j)
					if(H_trial(j,j)<0.0) then
						H_trial(j,j)=H_trial(j,j)-random
						H_trial(j+m,j)=1-H_trial(j,j)
						cycle
					endif
				end do
			endif
		endif
		
		if(random3>0.5) then
			if(WV=='Y') then
				H_trial(index3,index3) = H_trial(index3,index3) - random
				H_trial(index3+m,index3)=1-H_trial(index3,index3)
				!Non-negative constraint on weights!
				if(H_trial(index3,index3)<0.0) then
					H_trial(index3,index3) = H_trial(index3,index3) + random
					H_trial(index3+m,index3)=1-H_trial(index3,index3)
					cycle
				endif
			elseif(WV=='N') then
				do j=1,m
					H_trial(j,j)=H_trial(j,j)-random
					H_trial(j+m,j)=1-H_trial(j,j)
					if(H_trial(j,j)<0.0) then
						H_trial(j,j)=H_trial(j,j)+random
						H_trial(j+m,j)=1-H_trial(j,j)
						cycle
					endif
				end do
			endif
		endif
				
		!Calculate fit!
		A_trial = matmul(C_trial,H_trial)
		do i=Acutoff, n
			do j=1, m
				A_diff_trial(i,j) = (D(i,j) - A_trial(i,j))
			end do
		end do
		Fnorm_trial = norm2(A_diff_trial)
		Fdiff = Fnorm_trial - Fnorm

		!Acceptance criteria!						
		if(Fdiff <= 0.0) then
			C = C_trial
			H = H_trial
			A = A_trial
			A_diff = A_diff_trial
			Fnorm = Fnorm_trial
			iacc=iacc+1
		endif
		if(Fdiff > 0.0) then
			prob = exp(-Fdiff/temperature)
			call random_number(random)
			if(prob > random) then
				C = C_trial
				H = H_trial
				A = A_trial
				A_diff = A_diff_trial
				Fnorm = Fnorm_trial
				iacc=iacc+1
			endif
			if(prob <= random) then
				C_trial = 0.0
				H_trial = 0.0
				A_trial = 0.0
				A_diff_trial = 0.0
				Fnorm_trial = 0.0						
			endif
		endif
	endif	

	!Read-out current configuration to record progress of factorisation!		
	if(mod(l,nprint)==1) then
		write(cystring,'(i5)') (l+nprint)/nprint
		open(10,file=trim(rundir)//'\samplecomponent\'//trim(adjustl(cystring))//'.txt', status='replace')
		do i = 1, n
			write(10,*) (C(i,j), j=m+1,s)
		enddo
		close(10)
	endif
	if(mod(l,nprint)==1) then
		write(cystring,'(i5)') (l+nprint)/nprint
		open(10,file=trim(rundir)//'\weight\'//trim(adjustl(cystring))//'.txt', status='replace')
		do i = 1, s
			write(10,*) (H(i,j), j=1,m)
		enddo
		close(10)
	endif
		
	!Write to charge progress!
	iacc_total=iacc_total+iacc

	if(mod(l,nprint)==1) then	
		write(cystring,'(i5)') (l+nprint)/nprint
		open(10,file=trim(rundir)//'\NMF_charge_progress.txt', status='unknown', access='append')
		write(10,*) l, iacc_total, temperature, increment, Fnorm
		close(10)
	endif
	
	if(mod(l,Fno)==1) then
		Fcheckdiff=Fcheck-Fnorm
		write(*,*) Fcheck, Fnorm, Fcheckdiff
		if(abs(Fcheckdiff)<0.00000001) then 
		exit
		elseif(abs(Fcheckdiff)>=0.00000001) then
			Fcheck=Fnorm
		endif
	endif

end do

write(6,*) 'FINISHED!!! Final energy:', Fnorm

open(10,file=trim(rundir)//'\corrected_PDFs.txt', status='replace')
write(10,*) 'r', (press(i), i=1,m)
do i=1,n
	write(10,*)  r(i), ((D(i,j)-(C(i,j))*(H(j,j)))/H(j+m,j), j=1,m)
enddo
close(10)

!close(11)
deallocate(D)
deallocate(C)
deallocate(H)
deallocate(A)
deallocate(A_diff)
deallocate(C_trial)
deallocate(H_trial)
deallocate(A_trial)
deallocate(A_diff_trial)
deallocate(r)
deallocate(G)
deallocate(Gpress)
deallocate(Gcurve)
deallocate(Gtot)
deallocate(bkgprm)
deallocate(bkgpress)
deallocate(bkg)
deallocate(pvalue)
deallocate(press)
deallocate(Ctot)
deallocate(z)
deallocate(dz)
deallocate(dtemp)

contains

subroutine makemetheth(m,n,ngaus,nbkgprm,bkgprm,nprm,gauscomp,G,pvalue,press,Gtot,Ctot)
	implicit none
	integer 	:: i,m,ngaus,gauscomp,n,nbkgprm,nprm
	real*8		:: Gpress(ngaus,gauscomp),Gcurve(ngaus,n),bkgprm(nbkgprm,nprm),G(ngaus,nprm,gauscomp),pvalue(nop)
	real*8		:: Gtot(n),bkgpress(nbkgprm),bkg(n),Ctot(n),z(n),dz(n),press
	real*8		   f,t
	pi=3.14159265
	
	Gtot=0
	Ctot=0
	Gpress=0
	Gcurve=0
	bkgpress=0
	!Calculate Gaussian prms!
	do i=1,ngaus
		do k=1, gauscomp
			if (k==1) then
			Gpress(i,k)=(G(i,2,k) + ((G(i,1,k)-G(i,2,k))*Exp(-(temppress/(pvalue(2))))))
			else if (k==2) then
			Gpress(i,k)=(G(i,2,k) + ((G(i,1,k)-G(i,2,k))*Exp(-(temppress/(pvalue(3))))))
			else if (k==3) then
			Gpress(i,k)=(G(i,2,k) + ((G(i,1,k)-G(i,2,k))*Exp(-(temppress/(pvalue(4))))))
			end if
		end do
	end do
	!Calculate individual Gaussians!
	do i=1, ngaus
		do j=1,n
			Gcurve(i,j) = (Gpress(i,1))*Exp(-(((j*dx)-(Gpress(i,2)))**2)/(2*(Gpress(i,3))**2))
			Gtot(j) = Gtot(j)+Gcurve(i,j)
		end do
	end do
	!Background!
	!Calculate background prms!
	do i=1,nbkgprm
		bkgpress(i)=(bkgprm(i,2) + ((bkgprm(i,1)-bkgprm(i,2))*Exp(-(temppress/(pvalue(1))))))
	end do
	!Calculate background!
	do i=1,n
		bkg(i)=(1-Exp(-(((i*dx)/bkgpress(1))**bkgpress(2))))
	end do
	!Gaussians+background!
	do i=1, n
		Gtot(i) = Gtot(i)+bkg(i)
	end do
	
	!Convolution program from convol_norm_new!
	do i=1,n
	z(i)=i*dx
	end do
	dz(1)=z(2)-z(1)
	dz(n)=z(n)-z(n-1)
	do i=2,n-1
		dz(i)=(z(i+1)-z(i-1))*0.5
	enddo
	
	do i=1,n
		Ctot(i)=0.
		do j=1,n
			f=abs(z(j)-z(i))
			t=(z(j)+z(i))
			if (i.eq.j) then
				Ctot(i)=Ctot(i)+z(j)*(Gtot(j))*(Qmax-sin(t*Qmax)/t)*dz(j)
			else
				Ctot(i)=Ctot(i)+z(j)*(Gtot(j))*(sin(f*Qmax)/f-sin(t*Qmax)/t)*dz(j)
			endif
		enddo
		Ctot(i)=Ctot(i)/(z(i)*pi)
	enddo
end subroutine

!Random number generator!
subroutine init_random_seed()
	integer :: i, n, clock
	integer, dimension(:), allocatable :: seed
	
	call random_seed(size = n)
	allocate(seed(n))

	call system_clock(count=clock)

	seed = clock + 37 * (/ (i - 1, i = 1, n) /)
	call random_seed(put = seed)

	deallocate(seed)
end subroutine init_random_seed

end program metheth_nmf