;FILE:  IO.pro
;includes:
;   function READ_IMG, file, HSIZE=hs
;   function PCX_READ, file
;   pro WRITE_BIN, file, arr
;   function READ_BIN, file
;
; (11-nov-00 cgz)
;	NOTE : Nothing other than READ_IMG is used in AXIS.  
;		Created READ_IMG.PRO.  IO.PRO is obsolete and can be eliminated
;

;Import Data Translation .IMG file format ( PRISM expt )
FUNCTION READ_IMG, file, HSIZE=hs

ON_ERROR, 2
file=strlowcase(file)
if (strpos(file,'.img') eq -1) then file=file+'.img'
print, file
;
hdr=strarr(512)
a=bytarr(512,512)
;
openr, unit, file, /GET_LUN
readu, unit, hdr
readu, unit, a
FREE_LUN, unit
;flip vertical
a=rotate(a,7)

if keyword_set(hs) eq 0 then hs=640
vs=round(hs*0.75)
print, hs, vs

outarray=congrid(a(0:511,32:511),hs, vs)  
return, outarray
END

;Import PC/Windows .PCX image format
;Decoding not implemented yet
FUNCTION PCX_READ, file

ON_ERROR, 2
file=strlowcase(file)
if (strpos(file,'.pcx') eq -1) then file=file+'.pcx'
print, file
;
openr, unit, file, /GET_LUN
hdr=bytarr(128)
readu, unit, hdr

siz=intarr(4)		;Xmin, Ymin, Xmax, Ymax
for i=0,3 do siz(i)=hdr(4+2*i)+256*hdr(5+2*i)
print, siz
palette=hdr(68)+256*hdr(69)
print, 'palette=',palette
bytlinpln=hdr(66)+256*hdr(67)
print, 'byte_line_plane=',bytlinpln
hsize=hdr(70)+256*hdr(71)
vsize=hdr(72)+256*hdr(73)
print, 'Screen Size: H,V = ',Hsize, Vsize


;imag=bytarr(Hsize,Vsize)
;imag=bytarr(siz(2)+1,siz(3)+1)
;readu, unit, imag

byt=bytarr(bytlinpln)
for i=1,siz(3) do begin
   readu, unit, byt
   print,i,byt(0)
endfor

;also color palette exists after end of image if greater than 16 shades

FREE_LUN, unit
;flip vertical
;imag=rotate(imag,7)

return, imag
END

pro WRITE_BIN, file, arr

  on_error,2
  arrsiz=size(arr)
  print,arrsiz
  openw,unit, file, /get_lun
  writeu, unit, arrsiz
  writeu, unit, arr
  free_lun, unit

END

function READ_BIN, file

  on_error,2

file=strlowcase(file)
if (strpos(file,'.') eq -1) then file=file+'.bin'
print, file

  ndim=long(1)
  openr, unit, file, /get_lun
  readu, unit, ndim

  dim=lonarr(ndim)
  readu, unit, dim

  dtyp=long(1)
  readu, unit, dtyp

  ntot=long(1)
  readu, unit, ntot
  print, ndim, dim, dtyp, ntot

  case dtyp of
  0: print,'undefined array data type'
  1: arr=bytarr(ntot)
  2: arr=intarr(ntot)
  3: arr=lonarr(ntot)
  4: arr=fltarr(ntot)
  5: arr=dblarr(ntot)
  6: arr=complexarr(ntot)
  7: arr=strarr(ntot)
  8: print,'structure data type load nont implemented'
  else: print,'Non-valid data type',dtyp
  endcase

  case ndim of
  1: arr=reform(arr,dim(0))
  2: arr=reform(arr,dim(0),dim(1)) 
  3: arr=reform(arr,dim(0),dim(1),dim(2))
  4: arr=reform(arr,dim(0),dim(1),dim(2),dim(3))
  5: arr=reform(arr,dim(0),dim(1),dim(2),dim(3),dim(4))
  6: arr=reform(arr,dim(0),dim(1),dim(2),dim(3),dim(4),dim(5))
  else: print,'dimensions >6 not implemented'
  endcase

  readu, unit, arr
  free_lun, unit

  return, arr
END











