;function find_centroid
;
;PURPOSE:
;       To find a centroid of a small rectangular region that is known to 
;       contain a star. 
;       
;       It relies on the return_centroid.pro function to return a centroid 
;       for a small rectangle.
;
;INPUTS:
;       Image - The 2d image containing the star
;
;OUTPUTS: A 4 element array
;         1 - X Centroid Global coordinate
;         2 - Y Centroid Global coordinate
;
;KEYWORDS:
;       TVFLAG:
;         0 - Don't plot or Tv
;         1 - Tv the star and print out the centroids as iterated
;
;	XBORDER:
;	  The number of pixels to avoid on the edge of the image
;         X = (R right) (L left) (T top) (B bottom)
;	GLOBAL:
;	  XMin, XMax, YMin, and YMax will be updated with the 
;	  values found by this function
function find_centroid, Image, XMin, XMax, YMin, YMax, $
         TvFlag = TvFlag, Global=Global, $
         LBorder = LBorder, RBorder=RBorder,$
         TBorder = TBorder, BBorder = BBorder

If N_Elements(TvFlag) eq 0 then TvFlag = 0
If N_Elements(LBorder) eq 0 then LBorder = 2
If N_Elements(RBorder) eq 0 then RBorder = 2 
If N_Elements(TBorder) eq 0 then TBorder = 2 
If N_Elements(BBorder) eq 0 then BBorder = 0 


Naxis1 = (Size(Image))[1] & Naxis2 = (Size(Image))[2]
X = 0D & Y = 0D
XMinL = XMin & XMaxL = XMax
YMinL = YMin & YMaxL = YMax
IterNum = 0.

StarCen = [2,2]
Star = Image(XMinL:XMaxL, YMinL:YMaxL)

while abs(StarCen(0)) ge 1 or abs(StarCen(1)) ge 1 do begin
          StarMin = Min(Star(where(Star ne 0)))
          StarCen = Return_Centroid(Star-StarMin, /RemoveBad)
          XMinL = (XMinL+StarCen(0)) > LBorder
          XMaxL = (XMaxL+StarCen(0)) < (Naxis1-1-RBorder)
          YMinL = (YMinL+StarCen(1)) > BBorder
          YMaxL = (YMaxL+StarCen(1)) < (Naxis2-1-TBorder)
          Star  = Image(XMinL:XMaxL, YMinL:YMaxL)
endwhile

If Global then begin
  XMin = XMinL & XMax = XMaxL & YMin=YMinL & YMax = YMaxL
EndIf
;Computer the centroid
XCen = (XMinL+XMaxL)/2
YCen = (YMinL+YMaxL)/2

Return, [XCen, YCen]

End
