      PROGRAM DOFFT
C PROFORM FFT CALCULATION
      USE MKL_DFTI
      
      IMPLICIT NONE

      INTEGER                             :: N            ! NUMBER OF ELEMENTS
      REAL, DIMENSION(:), ALLOCATABLE     :: DR           ! REAL PARTS
      REAL, DIMENSION(:), ALLOCATABLE     :: DI           ! IMAGINARY PARTS
      COMPLEX, DIMENSION(:), ALLOCATABLE  :: D            ! IN/OUT VARIABLE
      INTEGER                             :: OPENSTATUS   ! STATUS INDICATOR FOR FILE OPERATIONS
      INTEGER                             :: ARRAYSTAT    ! STATUS FOR ALLOCATING MEMORY
      INTEGER                             :: I            ! COUNTER
      INTEGER                             :: FFTSTATUS    ! STATUS INDICATOR FOR FFT CALCULATIONS
      TYPE(DFTI_DESCRIPTOR), POINTER      :: H            ! FFT DESCRIPTOR
C OPEN FILE FOR READING
      OPEN(UNIT       = 10,
     +     FILE       = "INPUT.TXT",
     +     STATUS     = "OLD",
     +     ACTION     = "READ",
     +     POSITION   = "REWIND",
     +     IOSTAT     = OPENSTATUS)
C STOP PROGRAM IF FAIL      
      IF(OPENSTATUS > 0) THEN
          STOP "CANNOT OPEN FILE FOR READING."
      END IF
C READ NUMBER OF ELEMENTS IN THE ARRAY
      READ(10,'(I5)') N
C ALLOCATE MEMORY FOR THE ARRAYS
      ALLOCATE(DR(N),STAT=ARRAYSTAT)
      ALLOCATE(DI(N),STAT=ARRAYSTAT)
      ALLOCATE(D(N),STAT=ARRAYSTAT)
C READ REAL AND IMAGINARY PARTS
      DO I = 1,N,1
          READ(10,'(E10.3,E10.3)') DR(I), DI(I)          
      END DO
C CONVERT TO COMPLEX NUMBER AND ASSIGN TO DATA
      DO I = 1,N,1
          D(I) = CMPLX(DR(I),DI(I))
      END DO
C CLOSE FILE
      CLOSE(10)
C DO FFT
      FFTSTATUS = DFTICREATEDESCRIPTOR(H,DFTI_SINGLE,DFTI_COMPLEX,1,N)
      FFTSTATUS = DFTICOMMITDESCRIPTOR(H)
      FFTSTATUS = DFTICOMPUTEFORWARD(H,D)
      FFTSTATUS = DFTICOMPUTEBACKWARD(H,D)
      FFTSTATUS = DFTIFREEDESCRIPTOR(H)
C OPEN FILE FOR WRITTING
      OPEN(UNIT       = 20,
     +     FILE       = "OUTPUT.TXT",
     +     STATUS     = "REPLACE",
     +     ACTION     = "WRITE",
     +     POSITION   = "REWIND",
     +     IOSTAT     = OPENSTATUS)
C STOP PROGRAM IF FAIL      
      IF(OPENSTATUS > 0) THEN
          STOP "CANNOT OPEN FILE FOR WRITTING."
      END IF
C WRITE NUMBER OF ELEMENTS
      WRITE(20,'(I5)') N
C PARSE
      DO I = 1,N,1
          DR(I) = REAL(D(I))
          DI(I) = AIMAG(D(I))
      END DO
C WRITE DATA
      DO I = 1,N,1
          WRITE(20,'(E10.3,",",E10.3)') DR(I), DI(I)          
      END DO
C CLOSE FILE
      CLOSE(20)

C FREE MEMORY
      DEALLOCATE(DR)
      DEALLOCATE(DI)
      DEALLOCATE(D)
      
      END PROGRAM DOFFT