; $Id: insertvalueinarray.pro,v 1.2 2005/01/24 17:34:51 azuah Exp $
;###############################################################################
;
; NAME:
;   insertValueInArray
;
; PURPOSE:
;   Insert a value into a sorted array at the appropriate location.
;
; CATEGORY:
;   Data Browser
;
; AUTHOR:
;   Richard Tumanjong Azuah
;   NIST Center for Neutron Research
;   100 Bureau Drive, Gaithersburg, MD 20899
;   United States
;   azuah@nist.gov; (301) 9755604
;   Feb, 2003
;
; 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 of if the code in this file is
;  included in another product.
;
;###############################################################################



;===============================================================================
; insertValueInArray
;
; PURPOSE:
;   Insert a value into a sorted array at the appropriate location.
;   NB: function only works if the array is sorted in increasing
;   numerical order and should only work for numerical arrays.
;
; PARAMETERS:
;   array [in|out; req] - the sorted array
;
;   value [in; req] - the value to be inserted.
;
; RETURN VALUE
;   The index of the array at which the value is inserted is returned.
;
function insertValueInArray, array, value

res = where(array gt value, count)

case count of
    0: begin                    ; then add new value to end of array
        array = [array,value]
        return, n_elements(array) - 1
    end
    else: begin
        if (res[0] eq 0) then begin ; then add new value to start of array
            array = [value,array]
            return, 0
        endif
        i = res[0]
        array = [array[0:i-1],value,array[i:*]]
        return, i
    end
endcase

end
