; $Id: $SSW/proba2/swap/idl/prep/p2sw_pmcdiv.pro#1 $
;
; Copyright (c) Trinity College Dublin. All rights reserved.
;+
; NAME:
;	P2SW_PMCDIV
;
; PURPOSE:
;	This function returns PROBA2/SWAP images corrected for onboard 
;   	processing (i.e., multiplication by 2 or 4).
;
; CATEGORY:
;	PROBA2/SWAP calibration.
;
; CALLING SEQUENCE:
; 
;	Result = P2SW_PMCDIV( Index, Image [, CALDIR=caldir, VERSION=version, $
;    	    	    	    	RUNID=runid, /VERBOSE, /LMAT, _EXTRA=ex ] )
;
; INPUTS:
;	Index:	FITS header in structure format for PROBA2/SWAP image 
;               to be processed.
;
;	Image:	PROBA2/SWAP image to be processed.
;
; OPTIONAL INPUTS:
;    	CALDIR:  File system pathway to PROBA2/SWAP calibration files. 
;    	    	 DEFAULT: local SSWIDL folder ('$SSW/proba2/swap/caldb')
;
;	VERSION: Master P2SW_PREP code version number for LMAT logging 
;   	    	 and HISTORY tag entries.
;
;    	RUNID:	 Unique processing run identifier for P2SC pipeline 
;   	    	 operations. Used only if LMAT is set.
;
; KEYWORD PARAMETERS:
;	VERBOSE: Set this keyword to print run-status information to 
;                standard output
;
;	LMAT:    Set this keyword to enable default reporting mode for 
;                P2SC pipeline operations. Not for use via SSW.
;
; OUTPUTS:
;	This function returns the input image with pixels identified as 
;       having undergone onboard-satellite mulitplication modifications 
;       returned to their originally measured onboard values. Input Index 
;   	structure is updated during processing - e.g., HISTORY appended.
;
; PROCEDURE:
;	The input image undergoes division of pixel values by factors 
;    	of 2 or 4 for those pixels multiplied onboard by the respective 
;   	factors. This correction is performed using the closest-in-time 
;   	pixel map correction FITS file supplied in the SSW-distributed 
;   	caldb directory or a user-defined directory (optional input 
;   	CALDIR). Correction is not applied if image was binned 2x2 
;   	onboard.
;
; MODIFICATION HISTORY:
; 	Written by:	D. Shaun Bloomfield, 24-Jan-2009.
;	Apr 2009	Added IDL-format description.
;	Jun 2009	Added ROB calls to send2lmat.pro for logging.
;   	    	    	Moved FITS history updating into sub-routines.
;   	    	    	Added option to supply calibration file dir.
;   	Jul 2009    	Added handling of sub-fielded images.
;	Aug 2009    	Added rebinning of native resolution 
;   	    	    	  calibration files for rebinned images.
;   	Mar 2010    	Split from p2sw_pmcorr.pro for p2sw_prep.pro at 
;   	    	    	  to perform separate division and replacement 
;   	    	    	  at the beginning and end of calibration.
;   	May 2010    	Finalized IDL-format description.
;-

FUNCTION p2sw_pmcdiv, index, image, $
    	    	    	caldir=caldir, version=version, runid=runid, $
			verbose=verbose, lmat=lmat, _extra=ex

    prognam = 'p2sw_pmcdiv.pro'
    delim = get_delim()
    
    ;---  Check keyword inputs and set keyword-dependencies
    IF KEYWORD_SET(caldir) THEN caldir = caldir ELSE caldir = STRCOMPRESS(GETENV('SSW'), /remove_all) + '/proba2/swap/caldb'
    IF KEYWORD_SET(version) THEN version = version ELSE version = ''
    IF KEYWORD_SET(runid) THEN runid = LONG(runid) ELSE runid = 0
    verbose = KEYWORD_SET(verbose)
    lmat = KEYWORD_SET(lmat)
    
    ;---  Check whether or not 2x2 binning was applied onboard
    IF ( STRMID( STRUPCASE( index.rebin ), 0, 2 ) NE 'ON' ) THEN BEGIN
    	
    	;---  Check for most recent onboard pixel map
    	pmc_files = FILE_SEARCH( caldir+'/swap_pmc_????????_??????.fits', COUNT=pmc_cnt )
    	
    	image1 = image
    	IF (pmc_cnt GT 0) THEN BEGIN
    	    
    	    pmc_tdiff = ANYTIM( index.DATE_OBS ) - $
	    	    	ANYTIM( FILE2TIME( pmc_files ) )
	    pmc_older = WHERE( pmc_tdiff GT 0., n_pmc_older )
	    IF (n_pmc_older GT 0) THEN BEGIN
	    	pmc_valid = pmc_files[ ( REVERSE(pmc_older) )[0] ]
	    	pmc_used = ( REVERSE( STRSPLIT( pmc_valid, delim, /EXTRACT ) ) )[0]
	    ENDIF ELSE BEGIN
	    	pmc_valid = pmc_files[0]
	    	pmc_used = ( REVERSE( STRSPLIT( pmc_valid, delim, /EXTRACT ) ) )[0]
	    	
	    	err_num = 4208L
	    	err_msg = 'No pixel map FITS files older than image - using '+pmc_used
	    	IF ~(lmat) THEN BEGIN
	    	    IF (verbose) THEN MESSAGE, '** '+err_msg+' **', /CONTINUE
	    	ENDIF ELSE SEND2LMAT, 'SWBSDG', version, runid, err_msg, err_num, prognam+', line: ', '/p2sc/temp/swbsdg'
	    	
	    ENDELSE
	    
	    ;---  Read in pixel map image
    	    MREADFITS, pmc_valid, pmc_ind, pmc_tmp, /SILENT, _EXTRA=ex
	    ;---  Embed detector sub-field region of interest in array of 1's
	    ;---  Ensures that out-of-sub-field pixels are treated as read-out normally onboard
	    pmc_img = INTARR( index.naxis1, index.naxis2 )+1
	    pmc_img[ index.firstcol-1:index.last_col-1, index.firstrow-1:index.last_row-1 ] = $
	    	pmc_tmp[ index.firstcol-1:index.last_col-1, index.firstrow-1:index.last_row-1 ]
	    
	    ;---  Locate pixels previously multiplied by 2
    	    pix2 = WHERE( pmc_img EQ 2, n_pix2 )
    	    ;---  If pixels exist then divide by 2
    	    IF (n_pix2 GT 0 ) THEN image1[pix2] /= 2.
	    
    	    ;---  Locate pixels previously multiplied by 4
    	    pix3 = WHERE( pmc_img EQ 3, n_pix3 )
    	    ;---  If pixels exist then divide by 4
    	    IF (n_pix3 GT 0 ) THEN image1[pix3] /= 4.
	    
    	    ;---  Collate numbers of pixels corrected
    	    n_pmc_pix = n_pix2 + n_pix3
    	    
    	    ;---  Set HISTORY update text
;   	    tagval = STRING('Corrected ', n_pmc_pix, ' pixels for onboard modification using '+pmc_used, FORMAT='(a,i7,a)')
    	    tagval = 'Reverted wrt '+pmc_used
    	    ;---  Report if requested
    	    IF (verbose) THEN MESSAGE, 'HISTORY record updated:  '+tagval, /CONTINUE
    	    ;---  Add update text into HISTORY field of index structure
    	    UPDATE_HISTORY, index, tagval, CALLER='P2SW_PMCDIV '+version
	    
    	;---  If no onboard pixel map files then report ERROR
    	ENDIF ELSE BEGIN
    	    
    	    err_num = 4207L
    	    err_msg = 'No pixel map FITS files found in '+caldir
    	    IF ~(lmat) THEN BEGIN
               MESSAGE, '** '+err_msg+' **', /CONTINUE
	    ENDIF ELSE SEND2LMAT, 'SWBSDG', version, runid, err_msg, err_num, prognam+', line: ', '/p2sc/temp/swbsdg'
	    
	    RETURN, err_msg
	    
    	ENDELSE
	
    ;---  If 2x2 binning was applied onboard then skip pixel map division correction
    ENDIF ELSE BEGIN
    	
       image1 = image

	IF (verbose) THEN MESSAGE, '** No pixel map division correction applied due to onboard binning **', /CONTINUE
	
    ENDELSE
    
    RETURN, image1
    
END
