C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C%%%%   Subroutine "readoszi" is used to read the total free   %%%%
C%%%%   energy from the file "OSZICAR_{N1}_{N2}"               %%%%
C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        subroutine readoszi(toten, nelastic)

        use constant
        implicit none

        integer nelastic
        double precision toten
        dimension toten(21,ndef)

        integer i, rownum, tempI
        integer num, strnum, ios
        logical filefound
        character*1 temp
        character*2 tempC
        character*20 osziname 

        do num=1,nelastic
           do strnum=1,ndef

              write(osziname,'(a8,i02.2,a1,i03.3)') 
     &                                'OSZICAR_',num,'_',strnum

C             To determine whether the file exists

              inquire (file=osziname, exist=filefound)
              if (.NOT.filefound) then
                      open(unit=19,position='Append',FILE='RELAS') 
                      write(19,'(a17, a, a15)') 'ERROR!! The file ',
     &                                trim(osziname), ' is not exit!!!'
                      close(19)
                      stop        
              endif

              open (9, file = Trim(osziname))

              rownum=0

              do
                 read(9,*,iostat=ios) temp
                 if ( ios .NE. 0 ) THEN
                        exit
                 endif
                 rownum=rownum+1
              enddo
              
              rewind(9)
              
              do i=1,rownum-1
                 read(9,*) 
              enddo

              read(9,*) tempI, tempC, toten(num,strnum)
           
              close(9)

              if ( tempC(1:1) .NE. 'F' ) THEN
                      open(unit=19,position='Append',FILE='RELAS') 
                      write(19,'(a17,a9,i02.2,a1,i03.3, a19)') 
     &                             'ERROR!! The file ','OSZICAR_',num,
     &                             '_',strnum, ' isnot completed!!!'
                      close(19)
                      stop
              endif

           enddo
        enddo

C        open(unit=19,position='Append',FILE='RELAS')

C        write(19,*) 'The energy matrix is: '
C        write(19,*) 

C        do num=1,nelastic
C           write(19,'(13f12.6)') (toten(num,strnum), strnum=1,ndef)
C        enddo
C
C        close(19)
        
        end
C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C%%%%                     End of readoszi.f                    %%%%
C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%      

