set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go




--

ALTER FUNCTION [dbo].[fGetNearbyFrameEq] (

	@ra float, @dec float, @radius float, @zoom int, @band varchar(4)

)

-------------------------------------------------------------------------

--/H Returns frames nearby (@ra,@dec) at a given @zoom level, and @band

-------------------------------------------------------------------------

--/T <br> Used by the cutout web service

--/T Parameters:

--/T <li> @ra, @dec float specify the search position in degrees. 

--/T <li> @radius float is the search radius in arcmins

--/T <li> @zoom int is the zxoom factor times 10, one of (0, 10, 20, 30)

--/T <li> @band varchar(4) gives the image band

-------------------------------------------------------------

--/T <p> returned table is sorted nearest first:  

--/T <li> fieldID bigint,        -- field identifier

--/T <li> fieldID 	bigint NOT NULL,

--/T <li> crval1 	float NOT NULL ,

--/T <li> crval2	float NOT NULL ,

--/T <li> crpix1	float NOT NULL ,

--/T <li> crpix2	float NOT NULL ,

--/T <li> cd1_1 	float NOT NULL ,

--/T <li> cd1_2		float NOT NULL ,

--/T <li> cd2_1		float NOT NULL ,

--/T <li> cd2_2		float NOT NULL 

--/T <br>

--/T Sample call to find frame nearest to 185,0 and within one arcminute of it.

--/T <br><samp>

--/T <br>select *

--/T <br>from  dbo.fGetNearbyFrameEq(185,0,1)  

--/T  </samp>  

--/T  <br>see also fGetNearestFrameEq

-------------------------------------------------

RETURNS @proxtab TABLE (

	fieldID 	char(32) NOT NULL,

	crval1 		float NOT NULL ,

	crval2		float NOT NULL ,

	crpix1		float NOT NULL ,

	crpix2		float NOT NULL ,

	cd1_1 		float NOT NULL ,

	cd1_2		float NOT NULL ,

	cd2_1		float NOT NULL ,

	cd2_2		float NOT NULL

  	)

AS

BEGIN

	DECLARE @nx float,

		@ny float,

		@nz float,

		@r float,

		@cmd varchar(1000)

	SET @r = @radius 

	SET @nx  = COS(RADIANS(@dec))*COS(RADIANS(@ra));

	SET @ny  = COS(RADIANS(@dec))*SIN(RADIANS(@ra));

	SET @nz  = SIN(RADIANS(@dec));

	SET @cmd = 'CIRCLE J2000 ' +str(@ra,22,15)+' '+str(@dec,22,15)+' '+str(@radius,5,2)

	--

	INSERT @proxtab	SELECT  

	    fieldID, crval1, crval2, crpix1, crpix2, cd1_1, cd1_2, cd2_1, cd2_2  

	    FROM fHtmCover(@cmd) , FrameWCS

	    WHERE (htmid BETWEEN  HTMIDstart AND HTMIDend)

	    AND zoom = @zoom

	    AND ( (2*DEGREES(ASIN(sqrt(power(@nx-cx,2)+power(@ny-cy,2)+power(@nz-cz,2))/2))*60)< @r) 

	    ORDER BY (2*DEGREES(ASIN(sqrt(power(@nx-cx,2)+power(@ny-cy,2)+power(@nz-cz,2))/2))*60) ASC

	OPTION(FORCE ORDER, LOOP JOIN) 

	--

	RETURN

END




