program remove_duplicates
    implicit none
    integer, parameter :: nmax = 30000
    integer :: n, i, j
    real :: lon(nmax), lat(nmax), prec(nmax)
    logical :: remove(nmax), mark_all(nmax)
    character(len=50) :: id(nmax), orgao(nmax)
    character(len=100) :: reason(nmax)
    real, parameter :: threshold = 0.02 ! Aproximadamente 2000 metros em graus
    character(len=200) :: input_file, output_file, removed_file
    
    ! Obter nomes dos arquivos
    call get_command_argument(1, input_file)
    call get_command_argument(2, output_file)
    call get_command_argument(3, removed_file)
    
    ! Abrir o arquivo de entrada
    open(10, file=trim(input_file), status='old')
    n = 0
    do while (.true.)
        read(10, *, end=100) id(n+1), orgao(n+1), lon(n+1), lat(n+1), prec(n+1)
!        write(*,*)id(n+1), orgao(n+1), lon(n+1), lat(n+1), prec(n+1)
        n = n + 1
    end do
100 close(10)
    
    ! Inicializar vetores de remocao
    remove = .false.
    mark_all = .false.
    reason = ''
    
    ! Verificar duplicatas e marcar para remocao
    do i = 1, n-1
        if (.not. remove(i)) then
            do j = i+1, n
                if (.not. remove(j)) then
                    if (id(i) == id(j) .and. lon(i) == lon(j) .and. lat(i) == lat(j) .and. prec(i) == prec(j)) then
                        remove(j) = .true.
                        reason(j) = 'Duplicata exata'                    
                    else if (id(i) == id(j) .and. lon(i) == lon(j) .and. lat(i) == lat(j) .and. prec(i) /= prec(j)) then
                        remove(i) = .true.
                        remove(j) = .true.
                        reason(i) = 'IDs iguais, locais iguais, precipitacao diferente'
                        reason(j) = 'IDs iguais, locais iguais, precipitacao diferente'
                        mark_all(i) = .true.
                        mark_all(j) = .true.                    
                    else if (id(i) /= id(j) .and. lon(i) == lon(j) .and. lat(i) == lat(j) .and. prec(i) == prec(j)) then
                        remove(j) = .true.
                        reason(j) = 'IDs diferentes, local e precipitacao iguais'
                    else if (id(i) == id(j) .and. prec(i) == prec(j) .and. &
                             sqrt((lon(i) - lon(j))**2 + (lat(i) - lat(j))**2) < threshold) then
                        remove(j) = .true.
                        reason(j) = 'Distancia menor que 2000m'
                    else if (id(i) /= id(j) .and. prec(i) /= prec(j) .and. lon(i) == lon(j) .and. lat(i) == lat(j)) then
                        remove(i) = .true.
                        remove(j) = .true.
                        reason(j) = 'IDs diferentes, locais iguais e precipitacao diferente'
                        reason(i) = 'IDs diferentes, locais iguais e precipitacao diferente'
                    else if (id(i) == id(j) .and. prec(i) == prec(j) .and. lon(i) /= lon(j) .and. &
                        lat(i) /= lat(j) .and. sqrt((lon(i) - lon(j))**2 + (lat(i) - lat(j))**2) < threshold  )then
                        remove(j) = .true.
                        reason(j) = 'IDs e precipitacao iguais ,lat e lon diferentes e distancia menor que 2000m'
                    else if (id(i) == id(j) .and. prec(i) /= prec(j) .and. &
                        sqrt((lon(i) - lon(j))**2 + (lat(i) - lat(j))**2) < threshold  )then
                        remove(i) = .true.
                        remove(j) = .true.
                        reason(j) = 'IDs iguais, precipitacao, lat e lon diferentes e distancia menor que 2000m'
                    end if
                end if
            end do
        end if
    end do
    
    ! Se alguma estacao foi marcada para remocao total, remover todas com o mesmo ID
    do i = 1, n
        if (mark_all(i)) then
            do j = 1, n
                if (id(i) == id(j)) then
                    remove(j) = .true.
                end if
            end do
        end if
    end do
    
    ! Escrever os dados filtrados
    open(20, file=trim(output_file), status='unknown')
    do i = 1, n
        if (.not. remove(i)) then
            write(20, '(A,2X,A,2X,F12.6,2X,F12.6,2X,F8.2)') trim(id(i)), trim(orgao(i)), lon(i), lat(i), prec(i)
        end if
    end do
    close(20)
    
    ! Escrever as estacoes removidas com motivo
    open(30, file=trim(removed_file), status='unknown')
    write(30, *) 'ID ', ' ORGAO ', ' LONGITUDE ', ' LATITUDE ', ' PRECIP ', ' MOTIVO'
    do i = 1, n
      if (remove(i)) then
       write(30, '(A,2X,A,2X,F10.6,2X,F10.6,2X,F8.2,2X,A)') trim(id(i)), trim(orgao(i)), lon(i), lat(i), prec(i), trim(reason(i))
      end if
    end do
    close(30)
    
    print *, trim(output_file), '  e  ', trim(removed_file)
end program remove_duplicates
