!#########################################################################
!		
!    Copyright (C) 2003-2012 Department of Physics and Astronomy,
!                            University of Rochester,
!                            Rochester, NY
!
!    io_ppm.f90 is part of AstroBEAR.
!
!    AstroBEAR is free software: you can redistribute it and/or modify	  
!    it under the terms of the GNU General Public License as published by 
!    the Free Software Foundation, either version 3 of the License, or    
!    (at your option) any later version.
!
!    AstroBEAR is distributed in the hope that it will be useful, 
!    but WITHOUT ANY WARRANTY; without even the implied warranty of
!    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!    GNU General Public License for more details.
!
!    You should have received a copy of the GNU General Public License
!    along with AstroBEAR.  If not, see <http://www.gnu.org/licenses/>.
!
!#########################################################################
!> @file io_ppm.f90
!! @brief Main file for module IOPPM

!> @defgroup IOPPM IO PPM
!! @brief Writes PPM files for viewing data in visit
!! @ingroup IO

!> Writes PPM files for viewing particle data in visit
!! @ingroup IOPPM
MODULE IOPPM
   USE GlobalDeclarations
   IMPLICIT NONE

CONTAINS

   SUBROUTINE WritePPM(Filename, colormap, data, cmin, cmax)
      CHARACTER(LEN=*) :: Filename
!      CHARACTER(LEN=210) :: system_cmd
      REAL(KIND=qPREC), DIMENSION(:,:) :: data
      REAL(KIND=qPREC) :: cmin, cmax
      INTEGER, DIMENSION(:,:) :: colormap
      INTEGER :: i,j
      OPEN(UNIT=PPM_DATA_HANDLE, FILE=TRIM(FileName), status="unknown")
      write(PPM_DATA_HANDLE,'(A,3I6)') 'P3 ',shape(data), 255
      DO j=size(data,2),1,-1
         DO i=1,size(data,1)
            write(PPM_DATA_HANDLE,'(3I5)') RGBInterp(data(i,j),cmin, cmax,colormap)
         END DO
      END DO
      CLOSE(PPM_DATA_HANDLE)
 !     j=len(trim(FileName))
!      write(system_cmd,'(A8,A,A1,A,A12,A)') 'convert ',TRIM(FileName), ' ', FileName(1:j-4), '.jpeg && rm ', TRIM(FILENAME)
!      write(*,*) system_cmd
!      CALL SYSTEM(system_cmd)

   END SUBROUTINE WritePPM

   FUNCTION RGBInterp(x,cmin,cmax,colormap)
      REAL(KIND=qPREC) :: x,dx,f,cmin,cmax
      INTEGER :: i2,i1
      INTEGER, DIMENSION(:,:) :: colormap
      INTEGER, DIMENSION(3) :: RGBInterp
      dx=(cmax-cmin)/real(size(colormap,1)-1)
      i2=min(size(colormap,1),max(ceiling((x-cmin)/dx)+1,2))
      i1=i2-1
      f=(x-cmin)/dx+1-i1
      RGBInterp=NINT(colormap(i1,:)*(1d0-f)+f*colormap(i2,:))
      RGBInterp=max((/0,0,0/),min((/255,255,255/),RGBInterp))

!      IF (x /= 0d0) THEN
!         write(*,*) dx, cmin, cmax, RGBInterp
!         STOP
!      END IF
   END FUNCTION RGBInterp

END MODULE IOPPM


