c************
c  Description:	Detect complex input signal into AM, FM, PM
c
c  Author:	ged  4/92
c
c  $Revision: 1.1 $
c  $Modtime:   18 Aug 1993 14:44:56  $
c  
c************
	program detect

	implicit none
	include 'primitive.inc'
	record /HEADER/ hin, ham, hfm, hpm
	integer*4  L_bbuf, LPER
	parameter (L_bbuf=32768)
	include 'buffers.inc'
	record /BUFFER/ in, am, fm, pm

	integer*4	i, ngot
	real*4		fr, fi, fmult, fpii, plast
	logical*4	block

	call M$CHECKIN

c open and test complex input 
	hin.file_name = M$APICK(1)
	hin.type_allow = '1000,2000'	
	hin.format_allow = 'C#,-CP'
	call M$INOK (hin)

c allocate output files
	call M$PROPAGATE (hin, ham)
	ham.file_name = M$APICK(2)
	ham.format = 'SF'
	ham.switch = 'OPTIONAL'
	call M$ALLOCATE (ham)

	call M$PROPAGATE (ham, hfm)
	hfm.file_name = M$APICK(3)
	hfm.switch = 'OPTIONAL'
	call M$ALLOCATE (hfm)

	call M$PROPAGATE (ham, hpm)
	hpm.file_name = M$APICK(4)
	hpm.switch = 'OPTIONAL'
	call M$ALLOCATE (hpm)

	if (.not.ham.open .and. .not.hfm.open .and. .not.hpm.open)
     &	  call M$WARNING ('No output file specified')

c make everybody look like Type 1000 
	call M$FORCE1000 (hin)
	call M$FORCE1000 (ham)
	call M$FORCE1000 (hfm)
	call M$FORCE1000 (hpm)

c setup GRAB parameters
	hin.buf_type = 'F'		!force reformat in GRAB, if needed
	ham.buf_type = hin.buf_type	!force reformat in FILAD, if needed
	hfm.buf_type = hin.buf_type
	hpm.buf_type = hin.buf_type
	LPER = M$XFER_LENGTH (max(hin.bpe,8),L_bbuf)

c test for block processing mode
	block = M$GET_SWITCH('BLOCK') .gt. 0

c set parameters for computing FM
	if (hin.type .lt. 2000) then
	  fmult = 1/hin.xdelta
	else
	  fmult = 1/hin.ydelta
	endif
	fpii = 1./twopi
	plast = 0

c signal dataflow 
	call M$SYNC

c loop through buffers
	do while ( M$DO(LPER,hin.xfer_len) )

c get complex input
	  call M$GRABX (hin, IN, ngot)

c compute magnitude, phase, and frequency from complex data
	    do i = 1,ngot
	      fr = REAL  (IN.cfbuf(i))
	      fi = AIMAG (IN.cfbuf(i))
	      AM.fbuf(i) = SQRT (fr*fr + fi*fi)
	      if (fi.eq.0 .and. fr.eq.0) fr = 1.0
	      PM.fbuf(i) = fpii*ATAN2 (fi, fr)
	      fr = PM.fbuf(i) - plast
	      if (fr.gt.0.5) then
		FM.fbuf(i) = (fr-1)*fmult
	      elseif (fr.lt.-0.5) then
		FM.fbuf(i) = (fr+1)*fmult
	      else
		FM.fbuf(i) = fr*fmult
	      endif
	      plast = PM.fbuf(i) 
	    enddo
	    if (block) FM.fbuf(1) = FM.fbuf(2) 

c write out results
	  call M$FILAD (ham, AM, ngot)
	  call M$FILAD (hfm, FM, ngot)
	  call M$FILAD (hpm, PM, ngot)
	enddo

c close files
	call M$CLOSE (hin)
	call M$CLOSE (ham)
	call M$CLOSE (hfm)
	call M$CLOSE (hpm)

	call M$RETURN
	end

