!******************************************************************
!***Routine for Negative Log Likelihood Function Being Minimized***
!***Called with parameter set being optimized 
!******************************************************************
	REAL*8 FUNCTION FUNCCALC(OPTPARMVAL)
	USE SHAREDVARS
	REAL*8 MODELCALC
	REAL*8 PARMMODEL(4),OPTPARMVAL(4)
	INTEGER IDAT,IPARM
	REAL*8 SUM,PROB
	EXTERNAL MODELCALC,Y0LIMIT
!***
!***Calculation of full parameter set PARMMODEL for calls to MODELCALC
!***
	IF(IPHASE.EQ.0) THEN
		IF(FIXPARMLIMID.EQ.0) THEN
			PARMMODEL(1)=OPTPARMVAL(1)
			PARMMODEL(2)=OPTPARMVAL(2)
			PARMMODEL(3)=OPTPARMVAL(3)
			PARMMODEL(4)=OPTPARMVAL(4)
		ELSEIF(FIXPARMLIMID.EQ.1) THEN
			PARMMODEL(1)=FIXPARMLIMVAL
			PARMMODEL(2)=OPTPARMVAL(1)
			PARMMODEL(3)=OPTPARMVAL(2)
			PARMMODEL(4)=OPTPARMVAL(3)
		ENDIF
	ELSEIF(IPHASE.EQ.1) THEN
		IF(FIXPARMLIMID.EQ.0) THEN
          		IF(FIXPARMCLID.EQ.2) THEN
          			PARMMODEL(1)=OPTPARMVAL(1)
          			PARMMODEL(2)=FIXPARMCLVAL
          			PARMMODEL(3)=OPTPARMVAL(2)
          			PARMMODEL(4)=OPTPARMVAL(3)
          		ELSEIF(FIXPARMCLID.EQ.3) THEN
          			PARMMODEL(1)=OPTPARMVAL(1)
          			PARMMODEL(2)=OPTPARMVAL(2)
          			PARMMODEL(3)=FIXPARMCLVAL
          			PARMMODEL(4)=OPTPARMVAL(3)
          		ENDIF
		ELSEIF(FIXPARMLIMID.EQ.1) THEN
          		IF(FIXPARMCLID.EQ.2) THEN
          			PARMMODEL(1)=FIXPARMLIMVAL
          			PARMMODEL(2)=FIXPARMCLVAL
          			PARMMODEL(3)=OPTPARMVAL(1)
          			PARMMODEL(4)=OPTPARMVAL(2)
          		ELSEIF(FIXPARMCLID.EQ.3) THEN
          			PARMMODEL(1)=FIXPARMLIMVAL
          			PARMMODEL(2)=OPTPARMVAL(1)
          			PARMMODEL(3)=FIXPARMCLVAL
          			PARMMODEL(4)=OPTPARMVAL(2)
          		ENDIF
		ENDIF
	ELSEIF(IPHASE.EQ.2) THEN
		PARMMODEL(1)=FIXPARMCLVAL
		PARMMODEL(2)=OPTPARMVAL(1)
		PARMMODEL(3)=OPTPARMVAL(2)
		PARMMODEL(4)=OPTPARMVAL(3)
		IF(PRINTFLAG) TYPE "('***In FUNCCALC PHASE2, PARMMODEL',4G15.7)",PARMMODEL
	ENDIF
!***
!***Likelihood calculation for PARMMODEL
!***
	SUM=0D0
	DO IDAT=1,NDAT
		PROB=MODELCALC(XDAT(IDAT),PARMMODEL)
		SUM=SUM-(MDAT(IDAT)-YDAT(IDAT))*LOG(1D0-PROB)-YDAT(IDAT)*LOG(PROB)
		!IF(Y0HIFLAG) TYPE "('In FUNCCALC PHASE2 *Y0 HIGH DETECTED*',I3,4G15.7)",IDAT,PROB,SUM
	ENDDO
	FUNCCALC=SUM
	RETURN
	END FUNCTION FUNCCALC



