! Determines the centres of gravity of the granules in the frame

	module centres_de_gravite

contains

	subroutine cg(ip,xg,yg,card,ng_com)

	use param_run
	use thename
	use readfits
	use detection
!	use m_correction
!	use m_intersec
!	use m_elimin
	use segmentation

	implicit none

	integer n,k,i,ip,ngmax,nbss,nx_cg,ny_cg
	integer, allocatable :: ia(:,:),nff(:)
	real, allocatable :: xgc(:,:),ygc(:,:),b(:,:)


 ! For reading the image
 
	real, pointer :: a(:,:)
!!$        real, allocatable :: a(:,:)
        integer naxes(2)
	character*128, pointer :: frame(:)

! For output
	real, intent(out) :: xg(:,:),yg(:,:)
	integer, intent(out) :: card(:,:),ng_com
	character suff*4,fichier*100

! Find the file
	call the_name(ip,frame)
	ngmax=size(xg,1)

	nbss=nbs(ip)
	allocate(nff(nbss),xgc(ngmax,nbss),ygc(ngmax,nbss))

! We transform the images into a set of points (xg,yg): the barycentres
	nx_cg=nx2-nx1+1; ny_cg=ny2-ny1+1
	allocate(ia(nx_cg,ny_cg),b(nx_cg,ny_cg)); ia=0; b=0
	 if (sub_im ==1) print*, 'we treat a sub-image of size',nx_cg,ny_cg
	 if (sub_im ==1) print*, ''
	 sub_im=0 ! this is a flag for the above prints

	do k=1,nbss
	 if (verbose >= 1) print*,'in cg ip,k,frame(k)',ip,k,frame(k)
	 nullify(a)
	 call readimage(frame(k),a,naxes)  ! nx=naxes(1); ny=naxes(2)
	 if (nx_cg <0 .or. ny_cg <0 .or. nx_cg>naxes(1) .or. ny_cg>naxes(2)) &
	       stop'in cg.f90: the sub-image is larger than the image!'

         b(1:nx_cg,1:ny_cg)=a(nx1:nx2,ny1:ny2)
	 if (.not. segmented) then
          if (typeseg == 'strouss') then
!           call segment(a(nx1:nx2,ny1:ny2),nx,ny,ia)
            call segment(b,nx_cg,ny_cg,ia)
          else if (typeseg == 'CD') then
           call segment_CD(a(nx1:nx2,ny1:ny2),nx_cg,ny_cg,ia, &
                          ech_lap,seuil_lap,seuil_rel,seuil_courb)
	    if (maxval(ia) == 1) ia=4*ia
          else if (typeseg == 'CD2') then
           call segment_CD2(a(nx1:nx2,ny1:ny2),nx_cg,ny_cg,ia, &
                          ech_lap,seuil_haut,seuil_bas)
	    if (maxval(ia) == 1) ia=4*ia
          else if (typeseg == 'CD3') then
            call segment_CD3(a(nx1:nx2,ny1:ny2),nx_cg,ny_cg,ia,n_moy, &
                           seuil_lap,seuil_bas)
	    if (maxval(ia) == 1) ia=4*ia
	  else
	   print*,'typeseg = ',typeseg
	   stop'this type of segmentation is not included'
	  endif
	 else
	  print*,'The image is already segmented; true level assumed =255'
	  ia=int(a/255)*4
	 endif
	
	 if (option == 'segmentation') then
	  if (verbose >= 1) print*,'option segmentation in cg'
	  write(suff,"(i4)") ip
	  suff=trim(adjustl(suff))
	  fichier='results/image_seg'//suff
          open(unit=4,file=fichier,form='formatted')
          !open(unit=4,file=fichier,form='unformatted')
                write(4,*) nx_cg,ny_cg
                write(4,*) ia(1:nx_cg,1:ny_cg)
                !write(4) nx_cg
                !write(4) ny_cg
                !write(4) ia
          close(4)
          n=count(ia == 4)
          print*,'nb of pixels with data',n,'fraction of total',float(n)/nx_cg/ny_cg
	  return
	 endif

	 if (verbose >= 4) then
           open(unit=4,file='image_seg')
                write(4,*) nx_cg,ny_cg
                write(4,*) ia
           close(4)
	 else if (verbose >= 1) then
	  n=count(ia == 4)
	  print*,'nb of pixels with data',n,'fraction of total',float(n)/nx_cg/ny_cg
	 endif

	 call detect(ia,nx_cg,ny_cg,xg(:,k),yg(:,k),card(:,k),nff(k)) 
	 if (verbose >=1) print*,'nb of pix. in granules',sum(card(1:nff(k),k))
	enddo

! All the sets need to have the same set of granules. We first determine the
! corrected (from distorsion) positions and then the common set

!	do k=2,nbss
!	 call correction(xg(:,k),yg(:,k),nff(k),xgc(:,k),ygc(:,k),ip,k)
!	 call intersection(xg(:,1),yg(:,1),xgc(:,k),ygc(:,k),nff(1),nff(k))
!	enddo

! The intersection is in xg,yg(:,1); we select the same granules in all
! the other frames k#1
!	do k=2,nbss
!	 call elimination(xg(:,1),yg(:,1),nff(1),xgc(:,k),ygc(:,k),&
!                          xg(:,k),yg(:,k),nff(k),ng_com)
!	enddo

	if (nbss == 1) ng_com=nff(1)

	deallocate(a,ia,nff)
	end subroutine


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!      Centre de gravite pour la version CST de 2013

      subroutine centre_gravite(coord,image,nx,ny,dimxx,dimyy,aire_max,fene,valeur,cgravx,cgravy)

            implicit none

            integer      valeur,posx,posy,xmin,xmax,ymin,ymax,fene
            integer      xl,yl,dimxx,dimyy,aire_max,nx,ny

            integer      image(nx,ny), obj(2*fene+1,2*fene+1)

            real         cgravx, cgravy, XG,YG,compt
            real         coord(2)

            posx=coord(1) 
            posy=coord(2) 
              
            xmin=posx-fene      
            xmax=posx+fene      
            ymin=posy-fene       
            ymax=posy+fene       
       
            if(xmin .lt. 1)  xmin=1 
            if(xmax .gt. nx) xmax=nx
            if(ymin .lt. 1)  ymin=1 
            if(ymax .gt. ny) ymax=ny 

           obj=0
           obj=image(xmin:xmax,ymin:ymax)  

            compt=0.

            XG=0.
            YG=0.
            cgravx=0
            cgravy=0
  
           do yl=1,dimyy 
             do xl=1,dimxx    
              if(obj(xl,yl) .eq. valeur) then 
                XG= real(xl)+xmin-1+ XG
                YG= real(yl)+ymin-1+ YG                 
                compt= compt +1
                if ( compt .gt. aire_max-1) goto 10  
              endif
             end do      
           end do

 10       continue

          cgravx=(XG/compt)  
          cgravy=(YG/compt) 

         end subroutine

	end module
