; saves space.spec (for arnell IAM system) to file
; the bounds are assumed to be -180 to 180 and -90 to 90 ; this may be untrue for GCMs

pro SaveSpec, RegN, ModelLongN, ModelLatN, MapIDLReg, RegName, Weights

SpecFilePath = "" & RefTitle = ""
MissVal = -999.0
DatumCha = "" & DumpInt=0L

print, "  > Enter the filepath of the space.spec file to save: "	; specify file
OpenStatus = -1
while (OpenStatus NE 0) do begin
  read, SpecFilePath
  SpecFilePath = strtrim(SpecFilePath,2)
  openw, lunSpec, SpecFilePath, /get_lun, error=OpenStatus
  if (OpenStatus NE 0) then print, "  > File cannot be opened. Re-enter filepath."
endwhile  

MeshLong = 360.0 / float(ModelLongN) & MeshLat = 180.0 / float(ModelLatN)

printf,lunSpec, ModelLongN,ModelLatN,RegN,0,format='(4i6)'		
printf,lunSpec, MeshLatN,MeshLongN,90.0,180.0,-90.0,-180.0, format='(6f8.2)' ; write dims

for XLat = 0, (ModelLatN-1) do begin			; write lat weights			
    DumpInt = Weights(XLat)
    printf,lunSpec, DumpInt,format='(f10.4)'
endfor
for XLong = 0, (ModelLongN-1) do begin			; write region indices	(1...)	
  for XLat = 0, (ModelLatN-1) do begin				
    DumpInt = MapIDLReg (XLong,XLat)
    if (DumpInt NE -999L) then DumpInt=DumpInt+1L
    printf,lunSpec, DumpInt,format='(i10)'
  endfor
endfor
for XReg = 0L, (RegN-1) do begin			; write region names
    DatumCha = RegName (XReg)
    printf,lunSpec, DatumCha, format="(A20)"
endfor

free_lun, lunSpec

end
