! nob: number of observations
! no_it: number of ideal types
! no_cv: number of context variables
! no_des: number of design variables
      USE MSIMSLSS
      INTEGER    INTCEPT, LDX, NCOEF, NIND, NOBS
C	      
      REAL       B(3), SSE, SST, X(6,3), Y(6)      
	REAL       config_c(10,15),config_d(10,15),xc(3000,15)
	REAL       xd(3000,15),fit(3000),	config_h(3000,15),sfit(3000)
!
!	 x(no_cv,no_it), y(no_cv)
!	 B(ncoef)
!
      open (unit=7, file='d:\FitCalculate\hybrid\htfout.txt')
	  open (unit=8, file='d:\FitCalculate\hybrid\htfin.txt')
	  read (8,*) nob,no_it,no_cv,no_des
	  INTCEPT=0
	  NIND = no_it
	  NOBS = no_cv+no_des
	  LDX =NOBS
	  NCOEF = INTCEPT + NIND  

!
	  do 10 i=1,no_it
	    read(8,*) (config_c(i,j),j=1,no_cv),(config_d(i,j),j=1,no_des)
10 	  continue
!
	  do 7 i =1,no_cv
	    do 8 j = 1,no_it  
	     X(i,j) = config_c(j,i)
8         continue
7       continue
!
        do 17 i=no_cv+1,no_cv+no_des
	     do 18 j =1,no_it
	      X(i,j)=config_d(j,i-no_cv)	 	
18         continue
17      continue
!	
      do 20 i=1,nob
	  	 read(8,*) (xc(i,j),j=1,no_cv),(xd(i,j),j=1,no_des)
		 do 21 j1= 1,no_cv
		    Y(j1)=xc(i,j1)
21         continue
       	 do 221 j1=no_cv+1,no_cv+no_des
	        Y(j1)=xd(i,j1-no_cv)
221        continue
!	      
	CALL RLSE (NOBS, Y, NIND, X, LDX, INTCEPT, B, SST, SSE)
	sfit(i)=-(SSE**0.5)
!    	
!      write(*,*) B
!	write(7,777) nobs,ncoef,nind,ldx,(B(jjj),jjj=1,ncoef),sst,sse	
!777   format(1x, 4(i5,x),6(f7.3,1x))				   
!	do 707 ii=1,no_cv+no_des
!	   write(7,708) (x(ii,jj),jj=1,no_it),y(ii)
!708      format(1x, 4(f10.4,1x))
!707   continue
      do 35 j1=1,no_cv
	     config_h(i,j1)=0.
	     do 36 j2=1,no_it			    
		    config_h(i,j1)=config_h(i,j1)+B(j2)*config_c(j2,j1)
36       continue
35    continue
! 
      do 335 j1=no_cv+1,no_cv+no_des
	     config_h(i,j1)=0.   
	     do 336 j2=1,no_it
!	write(*,*) '--->',config_h(i,j1),B(j2),config_d(j2,j1-no_cv)
	   config_h(i,j1)=config_h(i,j1)+B(j2)*config_d(j2,j1-no_cv)
336        continue
335   continue  			  
!
!         write(*,*) (config_h(i,jjj),jjj=1,no_cv+no_des)
	   fit(i)=0. 
	   do 39 k2=1,no_cv
	           fit(i) = fit(i) +  (xc(i,k2)-config_h(i,k2))**2.
39       continue			    
         do 40 k2=1,no_des
			   fit(i) = fit(i) +  (xd(i,k2)-config_h(i,no_cv+k2))**2.
40       continue 			 
          fit(i)= -(fit(i)**0.5) 		 	  
20    continue
      do 60 i=1,nob
	    write(7,66) fit(i),sfit(i)
66      format(1x,2(f10.4,1x))
60    continue
	  end
!
! 

c
      