implicit none

integer :: nx, ny
real, allocatable ::  data(:,:)

integer :: iargc, argc
character :: argv*1024, binfilename*1024, textfilename*1024

integer :: i, j

 argc = iargc()
 if(argc<3) then
 	write(0,*) 'convert bin file into textfile'
 	write(0,*) './a.out binfile nx ny textfile'
        stop
 end if


	call getarg(1, argv)
	binfilename = argv(1:len_trim(argv))
	
	call getarg(2, argv)
	read( argv, *) nx

	call getarg(3, argv)
	read( argv, *) ny

	call getarg(4, argv)
	textfilename = argv(1:len_trim(argv))


	write(0,*) 'From ', binfilename(1:len_trim(binfilename)), &
	  nx ,'x', ny, 'to ', textfilename(1:len_trim(textfilename))

	allocate(data(nx,ny))
	data = 0


	open( 10, file=binfilename(1:len_trim(binfilename)), &
		access ='direct', form='unformatted', recl=4*nx, &
		err = 900 )

	do j=1, ny
	 read(10, rec=j, err=999) (data(i, j), i=1, nx)
	end do

	close(10)

	open(11, file=textfilename(1:len_trim(textfilename)))
	  do j=1, ny
	   do i=1,nx
	  write(11, *) i, j, data(i,j)
	   end do
	  end do
	close(11)



stop

999  write(0,*) 'READ error', i, j
stop
900  write(0,*) 'open error'
stop
end
