	PROGRAM EXTRACT_ICE

! This program reads an ice file in the format used by CALSEA and outputs 
! each time slice into an XYZ file that can be used to plot the ice sheet
! at various times

	IMPLICIT NONE

	CHARACTER*255 infoline, argname, filename, outname, outnamecomb, dummy, outlog

	CHARACTER*1 ext1
	CHARACTER*2 ext2
	CHARACTER*3 ext3, extfin
	real ncolat, scolat, latsp, longsp, times(140), colat(720), &
	     colong(720,720), ivalues(720, 720, 140)
	integer numtimes, outnamelength, numlong, k, l, m, n, j, &
              longvalue(720), numcolat
	logical tester
	


	call getarg(1, filename)
!	read(argname,*) filename

	

	call getarg(2,argname)
	read(argname,*) outname

	write(6,*) "extracting ", filename
	write(6,*) "time ", outname

! find the length of the output name

	tester=.true.
	outnamelength=0

	DO WHILE (tester)
	  outnamelength=outnamelength+1
	
	  if (outname(outnamelength:outnamelength) .eq. ' ') THEN
	   tester=.false.
	  ENDIF



	END DO



	call read_ice(filename, times, numcolat, numtimes, latsp, longsp, colat, colong, ivalues, longvalue)

! write out results


	outlog = outname(1:outnamelength-1) // "/" // outname(1:outnamelength-1) // "." // "log"

	open (unit=12, file=outlog, form="formatted", access="sequential", status="new")

	write(12,*) latsp, longsp

	DO n = 1, numtimes, 1

		if (n < 10) THEN
			write(dummy,'(i1)') n
		elseif (n < 100) THEN
			write(dummy,'(i2)') n
		else
			write(dummy,'(i3)') n

		endif

		read (dummy,*) extfin

		outnamecomb = outname(1:outnamelength-1) // "/" // outname(1:outnamelength-1) // "." // extfin

!		write(6,*) n, times(n)

		write(12,*) n, times(n)

		open (unit=11, file=outnamecomb, access="sequential", form="formatted", status="new")

		DO m = 1, numcolat-1, 1

			DO j=1, longvalue(m), 1



				if (ivalues(m, j, n) < 0.) THEN
					if (colong(m,j) <180. ) THEN
						write(11, 200) colong(m, j), 90.-colat(m), -ivalues(m, j, n)
					else
						write(11, 200) colong(m, j)-360, 90.-colat(m), -ivalues(m, j, n)
					endif
				endif
200	FORMAT(F8.3,1X,F7.3,1X,F6.0)


			enddo

		enddo

		close (unit=11)

	enddo



	close (unit=12)

	STOP
	END
		
