program main
! count to tbb v1.00
implicit none
character*29::arg
character*8::filelist
integer :: status, system
real*4,dimension(17000)::tbb
integer*2,dimension(17000)::cnt
integer*2:: i, j, k, io,NoF,N
integer*2,parameter::pix=6000
integer*2,dimension(pix,pix)::data_all
real,dimension(pix,pix)::data_tbb
real,dimension(pix,pix)::data_rtbb    ! sorted data
call getarg( 1, arg ) 
call getarg( 2, filelist)

! Open and Read data
Open(21,file=arg,access='direct',status='old',iostat=io, recl=6000*6000*2)
if(status==0)then
read(21,rec=1)((data_all(i,j),i=1,pix),j=1,pix);close (21)
end if

! Read Tbb table file
NoF=17000
Open ( Unit=20, FILE=filelist,&
   STATUS='OLD',ACCESS='SEQUENTIAL',FORM='FORMATTED')
do N=1,NoF
READ (20, *, IOSTAT = io ) cnt(N),tbb(N)
if (io .ne. 0)exit
end do

! convert CTT to TBB
do i=1,pix
   do j=1,pix
      data_tbb(i,j)=real(tbb(data_all(i,j)+1))
   end do
end do

! reorder data_tbb (high to low latitude)->data_rtbb(low to high latitude)

do i=1,pix
   do j=1,pix
      data_rtbb(i,j)=data_tbb(i,6001-j)
   end do
end do



!Open ( Unit=10, File="grid20.dat", access='DIRECT',recl=6000*6000*4)
!   Write ( 10,rec=1 )((data_tbb(i,j),i=1,6000),j=1,6000)

! longitude and latitude for the reordered 6000 x 6000 data: 
! longitude:  from  85.01E to 205.01E, 0.02 degree interval 
! latitude:   from  59.99S to 59.99N,  0.02 degree interval 

! Japan area: i=2101 =>127.01E, i=3100=>146.99
! Japan area: j=4501 =>30.01N, j=5500=>49.99N

Open ( Unit=10, File="grid20.dat", access='DIRECT',recl=1000*1000*4)
   Write ( 10,rec=1 )((data_rtbb(i,j),i=2101,3100),j=4501,5500)

close(10)
end program
