! Program to remove spaces from data and to make the data comma separated. 
! Assumes the first line is a header with information about the contents of the file. 
! Here is an example of how the data might be structured.
! 2017 05 23 15 04 58 .03      23    -68    -24     73     76 160.8 -23.8  34922  302.63 0862.46
! Treats the data solely as text so that the format of the original data is preserved.

	IMPLICIT NONE ! Require all variables to be declared.

	CHARACTER*1000 line ! Reads in a line of text.
	CHARACTER*1000 out  ! Output line of data.

	INTEGER il,i,ill,j,jj	

! Open the data file to be converted, and its comma separated value as output.
	OPEN(1,FILE='May23_RAWsonic.txt')
	OPEN(2,FILE='May23_RAWsonic.csv')

	READ(1,1) line ! Read the first line, header.
1	FORMAT(a1000)

	il=LEN(TRIM(line))

	DO i=1,il
	IF (line(i:i).EQ.' ') line(i:i)=','
	ENDDO

	WRITE(2,*) line(2:il) ! Write the header to the output.

	DO j=1,100000000 ! loop over all lines.

	READ(1,1,END=10) line
	il=LEN(TRIM(line))

	DO i=1,il-1
	IF (line(i:i).EQ.' ') THEN
	  ill = i+1	
	  IF (line(ill:ill).NE.' ') THEN
	     line(i:i)=','
	  ELSE
	     line(i:i)=""
	  END IF
	ELSE
	END IF

	ENDDO ! DO i=1 ...

	il=LEN(TRIM(line))
	jj=0
	DO i=1,il
	IF (line(i:i).NE.' ') THEN
	  jj=jj+1
	  out(jj:jj)=line(i:i)
	END IF	
	ENDDO 

	WRITE(2,*) out(1:jj)
	ENDDO ! DO j=1, ...


10	CLOSE(1)
	CLOSE(2)
	END

	
	
	
