pro word_conv, ainput, ieee2vax=ieee2vax, vax2ieee=vax2ieee

;+
;NAME:
;	word_conv
;PURPOSE:
;	Converts data written on a DEC machine to SUN format by swapping
;	bytes appropriately for the type of the input data.  Optionally
;	convert REALs between IEEE and VAX format.
;SAMPLE CALLING SEQUENCE:
;	word_conv, a
;INPUTS:
;	a = input variable which is to have its bytes swapped
;OPTIONAL KEYWORD INPUT PARAMETERS:
;	ieee2vax - If set, then convert the REALs from IEEE to VAX format
;	vax2ieee - If set, then convert the REALs from VAX to IEEE format
;OUTPUTS:
;	a = reformatted variable is passed back in the original variable
;COMMON BLOCKS:
;	None
;SIDE EFFECTS:
;	None
;RESTRICTIONS:
;	None
;PROCEDURE:
;	Determines the type of the variable and swaps the bytes depending
;	on the type.  If the variable is a structure, the tags are 
;	recursively searched so that the bytes are swapped throughout
;	the structure.
;MODIFICATION HISTORY:
;	T. Metcalf 5/20/91  Version 1.0
;       T. Metcalf Aug 1991: Added complex floating point  Version 1.1
;       T. Metcalf Nov 1991: Converted vax2sun to dec2sun
;	13-Apr-93 (MDM) Took DEC2SUN and modified it into WORD_CONV
;-

a = ainput  ; Protect the input variable in case of error

sofa = size(a)
ns = n_elements(sofa)

case sofa(ns-2) of
       0:                                  ; Undefined
       1:                                  ; Byte
       2: byteorder,a,/sswap               ; Integer
       3: byteorder,a,/lswap               ; Longword integer
       4: begin
	     if (keyword_set(ieee2vax)) then ieee2vax, a else $
		if (keyword_set(vax2ieee)) then vax2ieee, a else $
		     byteorder,a,/lswap               ; Floating Point
	  end
       5: begin                            ; Double precision floating point
	     if (keyword_set(ieee2vax)) then ieee2vax, a else $
		if (keyword_set(vax2ieee)) then vax2ieee, a else begin
	             byteorder,a,/lswap        
	             na = n_elements(a)
	             longa=long(a,0,2*na)
	             longb=lonarr(2*na,/nozero)
	             even = indgen(na)*2
	             odd = even+1
	             longb(even)=longa(odd)
	             longb(odd)=longa(even)
	             a = double(longb,0,na)
	         end
          end
       6: begin                            ; Complex floating point
            rc=float(a)
            ic=imaginary(a)
	    word_conv, rc, ieee2vax=ieee2vax, vax2ieee=vax2ieee
	    word_conv, ic, ieee2vax=ieee2vax, vax2ieee=vax2ieee
            a = complex(rc,ic)
          end
       7:                                  ; String
    else: begin
	na = sofa(ns-1)

        ; In the case of a structure, search all the fields (recursively if 
        ; necessary) to swap all bytes which need swapping in the structure.

	for tag = 0, n_tags(a)-1 do begin
	    temp = a.(tag)      ; byteorder won't work on a structure field
	    word_conv, temp, ieee2vax=ieee2vax, vax2ieee=vax2ieee
	    a.(tag) = temp
	endfor
      end
endcase

ainput = a
end
