function cat_ptr, ptra, out, index, free = free

;+
; CAT_PTR
;	Concatentate a an array of pointers to arrays into a single
;	array. 
;
; Usage:
;	array = cat_ptr(ptra)
;
; Result:
; 	The total number of elements found.
;
; Arguments:
;	ptra	ptr	An array of pointers to arrays.
;	out		An array of any type, containing all the
;			elements of the components
;	index	long	A named varible to list which element the
;			values came from.
;
; Keyword:
;	/free	If set, then free the input pointer array on
;		completion.
;
; Restrictions:
;	All arrays must be coercable to the type of the first.
;
; History:
;	Original: 4/12/12; SJT
;	Changed to return the list as an argument and the count as the
;	result to better cope with cases where there's nothing
;	there: 8/9/14; SJT
;-

  na = n_elements(ptra)

  nsa = lonarr(na)

  for j = 0l, na-1 do if (ptr_valid(ptra[j])) then $
     nsa[j] = n_elements(*ptra[j])
  nout = total(nsa, /int)


  ioff = 0l
  sflag = 1b
  for j = 0l, na-1 do begin
     if (nsa[j] eq 0) then continue
     if (sflag) then begin
        out = replicate((*ptra[j])[0], nout)
        index = lonarr(nout)
        sflag = 0b
     endif
     out[ioff:ioff+nsa[j]-1] = *ptra[j]
     index[ioff:ioff+nsa[j]-1] = j
     ioff += nsa[j]
  endfor

  if (keyword_set(free)) then ptr_free, ptra

  return, nout

end
