module metadata_module

  implicit none
  !
  integer, parameter :: metadata_field_length   = 50
  integer, parameter :: metadata_value_length   = 100
  integer, parameter :: NMetadataFields         = 50

  type Tmetadata
    character(len=metadata_field_length)   :: fieldname
    character(len=metadata_value_length)   :: value
    integer                                :: numvalue
    logical                                :: used
  end type Tmetadata
 
contains
 
subroutine copy_metadata(metadata,file_metadata)
  implicit none
  type(Tmetadata),dimension(NMetadataFields)  :: metadata,file_metadata
  integer                                     :: i,j,n1,n2,first_inputpointer
  character(len=metadata_value_length)        :: dumstr1,dumstr2,dumstr
  logical                                     :: found

  n1=0 ; n2=0
  do i=1,NMetadataFields
    if (metadata(i)%used)      n1=n1+1
    if (file_metadata(i)%used) n2=n2+1      
  end do

  ! if there are no new metadata exit
  if (n2 < 1) return
  
  ! if this is the first call, just copy input metadata to the output metadata
  if (n1 ==0 ) then
    do i=1,n2
      write(metadata(i)%fieldname,'(a)') trim(file_metadata(i)%fieldname)
      write(metadata(i)%value,'(a)') trim(file_metadata(i)%value)
      metadata(i)%used=.true.
    end do
    return
  end if

  ! find the first occurrence of Input_pointer in the metadatalist. 
  ! I implicitly assume that the number of general metadata entries is identical for metadata and file_metadata
  do i=1,NMetadataFields
    if (index(metadata(i)%fieldname,'Input_pointer') > 0) exit
  end do
  first_inputpointer=i

  ! first copy. Unique entries only
  do i=first_inputpointer,n2
    write(dumstr,'(a)') '                                                     '
    write(dumstr,'(a)') trim(file_metadata(i)%value)
    found=.false.
    do j=first_inputpointer,n1
      if (index(trim(metadata(j)%value),trim(dumstr)) > 0) found=.true.
    end do
    if (.not. found) then
      n1=n1+1
      write(metadata(n1)%value,'(a)') trim(file_metadata(i)%value)
      write(metadata(n1)%fieldname,'(a)') trim(file_metadata(i)%fieldname)
      metadata(n1)%used=.true.
    end if
  end do

  ! sort the entries
  j=first_inputpointer 
  do i=first_inputpointer,n1
    if (.not. metadata(i)%used) cycle
    write(dumstr1,'(a)') trim(metadata(i)%value)
    if (index(trim(dumstr1),'OMI') < 1) cycle
    write(dumstr2,'(a)') trim(metadata(j)%value)
    write(metadata(j)%value,'(a)') trim(dumstr1)
    write(metadata(i)%value,'(a)') trim(dumstr2)
    j=j+1 
  end do
  
  j=1
  do i=first_inputpointer,n1
    if (.not. metadata(i)%used) cycle
    write(dumstr,'(i2)') j
    write(metadata(i)%fieldname,'(2a)') 'Input_pointer_',trim(adjustl(dumstr))
    j=j+1
  end do

end subroutine copy_metadata

 
end module metadata_module
