; $Id: dm_common.pro,v 1.5 2005/02/07 20:03:58 qiuym Exp $
;#######################################################################
;
; NAME:
;  dm_common
;
; PURPOSE:
;  This program finds out the common elements in array1 and array2, which are both indices of arrays
;  return -1 if no common elements(0 or positive integers) are found
;
; CATEGORY:
;  general
;
; AUTHOR:
;  Yiming Qiu
;  NIST Center for Neutron Research
;  100 Bureau Drive, Gaithersburg, MD 20899-8562
;  United States
;  yiming.qiu@nist.gov
;  Feb, 2005
;
; LICENSE:
;  The software in this file is written by an employee of
;  National Institute of Standards and Technology
;  as part of the DAVE software project.
;
;  The DAVE software package is not subject to copyright protection
;  and is in the public domain. It should be considered as an
;  experimental neutron scattering data reduction, visualization, and
;  analysis system. As such, the authors assume no responsibility
;  whatsoever for its use, and make no guarantees, expressed or
;  implied, about its quality, reliability, or any other
;  characteristic. The use of certain trade names or commercial
;  products does not imply any endorsement of a particular product,
;  nor does it imply that the named product is necessarily the best
;  product for the stated purpose. We would appreciate acknowledgment
;  if the DAVE software is used or if the code in this file is
;  included in another product.
;
;#######################################################################

function dm_common,arr1,arr2,count,no_copy=no_copy,debug=debug
    if keyword_set(debug) then current=systime(/sec)
    pos_arr1 = where(arr1 ge 0,count1)
    pos_arr2 = where(arr2 ge 0,count2)
    if (count1 eq 0) or (count2 eq 0) then begin
       pos_arr1 = -1 & pos_arr2 = -1
       count=0L  ;no common elements
       if keyword_set(no_copy) then begin    ;destroy arr1 and arr2
         n_arr = temporary(arr1)
         n_arr = temporary(arr2)
       endif
       if keyword_set(debug) then print,'dm_common finished in ',systime(/sec)-current,' sec.'
       return,-1L
    endif
    n_arr1 = max(arr1)
    n_arr2 = max(arr2)
    n_arr  = max([temporary(n_arr1),temporary(n_arr2)])
    tmp    = bytarr(n_arr+1)
    if keyword_set(no_copy) then begin ;destroy arr1 and arr2 after this function
       tmp[arr1[pos_arr1]]=1b    & pos_arr1=-1
       tmp[arr2[pos_arr2]]=tmp[arr2[pos_arr2]]+1b  & pos_arr2 = -1
       arr1 = -1 & n_arr = temporary(arr1)
       arr2 = -1 & n_arr = temporary(arr2)
    endif else begin
       tmp[arr1[pos_arr1]] = 1b  & pos_arr1 = -1
       tmp[arr2[pos_arr2]] = tmp[arr2[pos_arr2]]+1b & pos_arr2 = -1
    endelse
    if keyword_set(debug) then print,'dm_common finished in ',systime(/sec)-current,' sec.'
    return,where(temporary(tmp) eq 2b,count)
end
