!****************************************************************************
program extractEASE2_cut	! 20160611, cut SMAP data in ESAE2 proj for TP
! data format: ease-grid2, integer (16 bytes);  nrow: 812 (half of global maps); &
! ncol: 3856;  lat/lons for ease-grid2 see 

	integer nCols, nRows, iCol, iRow, iCol2, iRow2, nCols2, nRows2
	parameter(nCols=3856, nRows=812, nCols2=300, nRows2=150)
	integer(kind=2) nDataRaw(nCols, nRows), nDataCutLine(nCols2)
	integer nCutCols(nCols2, nRows2), nCutRows(nCols2, nRows2)
	integer iYear, iMon, iDay, nDOM(12)
	character sLayer*9, sYear4*4, sMon2*2, sDay2*2, sFileIn*100, sFileOu*100, sTemp*15

	nDOM = (/31,28,31,30,31,30,31,31,30,31,30,31/)
	sLayer = 'surface'

	sFileIn = 'EASE2_grid_TP.csv'
	open(100, file=trim(sFileIn), form='formatted', status='old')
	read(100, *) sTemp
	do iRow2 = 1, nRows2
		do iCol2 = 1, nCols2
			read(100, *)  rLat, rLon, nCutRows(iCol2, iRow2), nCutCols(iCol2, iRow2)
		enddo
	enddo
	close(100)

	do iYear = 2015, 2015
		write(sYear4, "(I4.4)") iYear
		
		do iMon = 4, 12
			write(sMon2, "(I2.2)") iMon
			print *, sYear4, sMon2

			do iDay = 1, nDOM(iMon)
				write(sDay2, "(I2.2)") iDay

				sFileIn = 'sm_'//trim(sLayer)//'/'//'SMAP_L4_SM_gph_sm_'//trim(sLayer)//'.'//sYear4//sMon2//sDay2//'.int16'
!print *, sFileIn	
				open(101, file=trim(sFileIn), form='unformatted', ACCESS='direct', RECL=2*nCols*nRows)
				!																					to check word longth (2 or 4 byte)
				read(101, rec=1) nDataRaw
				close(101)

				sFileOu = 'tp_'//trim(sLayer)//'/'//'TP_SMAP_'//trim(sLayer)//'.'//sYear4//sMon2//sDay2//'.bin'
				open(202, file=trim(sFileOu), form='unformatted',RECL=2*nCols2, access='direct',status='replace')

				do iRow2 = nRows2, 1, -1  
					do iCol2 = 1, nCols2
						nDataCutLine(iCol2) = nDataRaw(nCutCols(iCol2, iRow2), nCutRows(iCol2, iRow2)) 
					enddo
					write(202, rec=iRow2) nDataCutLine
				enddo

				close(202)
			enddo
		enddo
	enddo

end program extractEASE2_cut
!****************************************************************************
