;+
;
; Project   : s3drs reconstruction software
;                   
; Name      : spread_h
;               
; Purpose   : memory tools and Pixon 'syntax sugar' helper routines
;               
; Explanation: mimics the fortran routine 'spread'
;               
; Use       : 
;    
; Inputs    : 
;               
; Outputs   : 
;
; Keywords  : 
;               
; Common    : 
;               
; Restrictions: none
;               
; Side effects: 
;               
; Category    : 
;               
; Prev. Hist. : None.
;
; Written     : Sandy Antunes, NRC, March-April 2009
;               
;-            
; $Id: spread_h.pro,v 1.1 2009/04/22 18:32:37 antunes Exp $
;+
; <p> This function mimics the FORTRAN function SPREAD.  It expands the
;    dimensionality of the input array A by duplicating it N times along
;    DIMENSION.
;
; <p> Dimension numbers follow the same notation as dimension variables in IDL
;    functions such as TOTAL, i.e., they go from 1 up, with a maximum of 8.
;
; @copyright
;    Copyright © Pixon LLC, 1999-2004.  All rights reserved.
;    Unauthorized reproduction prohibited.
; @author
;    <a href="mailto:Amos.Yahil\@Pixon.com">Amos Yahil, Pixon LLC.</a>
; @param   a {in}
;    array to be spread.
; @param   dimension {in}
;    New dimension into which to spread.
; @param   n {in}
;    # of copies for spreading.
;-
FUNCTION Spread, a, dimension, n

                                ; Compilation options
   COMPILE_OPT IDL2, HIDDEN, STRICTARRSUBS

   dim = Dim(a)
   ndim = Ndim(a)
                                ; Reform and new dimensions
   CASE 1 OF
      dimension EQ 1: BEGIN
         dim1 = [1, dim]
         dimn = [n, dim]
      END
      dimension EQ ndim+1: BEGIN
         dim1 = [dim, 1]
         dimn = [dim, n]
      END
      dimension LT 1 OR dimension GT ndim+1: BEGIN
         MESSAGE, 'DIMENSION must be between 1 and NDIM+1'
      END
      ELSE: BEGIN
         dim1 = [dim[0:dimension-2], 1, dim[dimension-1:*]]
         dimn = [dim[0:dimension-2], n, dim[dimension-1:*]]
      ENDELSE
   ENDCASE
                                ; Spread (rebin) the array
   shmmap,DIMENSION=dim1,get_name=segname,/DOUBLE
   tempa=shmvar(segname)
   shmmap,DIMENSION=dimn,get_name=segname,/DOUBLE
   out=shmvar(segname)

   help,/mem
   tempa=REFORM(a, dim1, /OVERWRITE)
   print,'rebinning from ',dim1,' to ',dimn
   help,/mem
   out = REBIN(tempa,dimn,/SAMPLE)
;   out = CONGRID(tempa,dimn)
   help,/mem
   print,'rebing done'
;   out = REBIN(REFORM(a, dim1, /OVERWRITE), dimn, /SAMPLE)
                                ; Restore the old dimensions of A
   shmmap,DIMENSION=dim,get_name=segname,/DOUBLE
   a2=shmvar(segname)
   help,/mem
;   a = REFORM(a, dim, /OVERWRITE)
   a2 = REFORM(a, dim, /OVERWRITE)
   help,/mem
   shmmap,DIMENSION=dim,get_name=segname,/DOUBLE
   a=shmvar(segname)
   a=a2
                                ; Done
   RETURN, out
END
