pro make_gcp_file, filename, outfile, citol, ertol

;This program takes the output file generated by imcorr and makes
;a ENVI gcp file to be used in the warp.



junk=load_cols(filename, data)

;The fourth column of this file is the result flag.  A result flag of
;one means a successful correlation.  So, take out all values that don't
;have a result flag of one. Also, correlation index tolerance (cotol)  
;must be set to eliminate all 
;matches with a low correlation index (bad matches). Typical values for 
;tol are between 10 and 11. Ertol must also be set to further eliminate 
;bad points, typical values are between .4 and .6.

index=where(data(4,*) eq 1.0 and data(3,*) gt citol, count)
if (count ne 0)  then begin
  data=data(*,index)
  help, data
  cols=n_elements(data(0,*))

  output=fltarr(4,cols)

  output(0,*)=data(0,*)
  output(1,*)=data(1,*)
  output(2,*)=data(0,*)+data(5,*)
  output(3,*)=data(1,*)+data(6,*)

  openw, un1, outfile, /get
  printf, un1, output
  free_lun, un1
endif else begin
  print,'Correlation Index Tolerance too high, no good points found'

endelse

;The program now edits the gcp file and throws out all points with 
;displacements that exceed the average displacement by ertol

junk=load_cols(outfile, data)
cols=n_elements(data(0,*))
sumx=0
sumy=0
for i=0,cols-1 do begin
   sumx=sumx+abs(data(0,i)-data(2,i))
   sumy=sumy+abs(data(1,i)-data(3,i))
endfor
avgx=sumx/cols
avgy=sumy/cols
diffx=abs(data(0,*)-data(2,*))
diffy=abs(data(1,*)-data(3,*))
index=where(sqrt((diffx-avgx)^2+(diffy-avgy)^2)  lt ertol,count2 )
print,'average x displacement:',avgx
print,'average y displacement:',avgy 
 
if (count2 ne 0)  then begin
  data=data(*,index)
  help, data
  openw, un1, outfile, /get
  printf, un1, data
  free_lun, un1

endif else begin
  print,'Tolerance too low, no good points found'
 
endelse

end
