-- ================================================================================
-- E.Gallas - May 2, 2007
--
-- Changes from the July 12, 2006 version (060712_f_GetCorrectedLum.sql)
--   Early Run 2b will have the same correction as end of Run 2A(period 'Run 2A:E')
--
-- Function getCorrectedLum calculates the corrected luminosity 
-- in any of the 6 allowed Run 2 data taking periods.
-- INPUT:  inLum  - the input Luminosity (based on previous lum constant)
--         inLum0 - a tick0 luminosity which is used to calculate ffactor
--         inPERIOD - the input PERIOD (obtain using function getLumPeriod)
--           allowed values of inPeriod are
--           ('Run 2A:E','Run 2A:D','Run 2A:C','Run 2A:B','Run 2A:A','Run 2B')
-- OUTPUT: outLum - the corrected Luminosity
-- 
-- The final correction uses a 'back propigation' method:
-- Each of the 6 periods has its own set of multiplicative constants
-- Note: earlier periods adopt additional factors for each of the later periods.
-- 
-- ================================================================================

CREATE OR REPLACE FUNCTION getCorrectedLum 
	(inLum IN NUMBER,
	inLum0 IN NUMBER,
	inPERIOD IN VARCHAR2 := 'Run 2A:G' )
	RETURN NUMBER IS outLum NUMBER;

-- note: I had to give the inPERIOD a default value rather than a varchar2 length

  ffactor NUMBER := 1.000      ;

  C2AA0  NUMBER :=  1.0207092  ; 

  C2AB0  NUMBER :=  0.9985864  ;   
  C2AB1  NUMBER :=  7.02555e-4  ;
  C2AB2  NUMBER :=  8.361414e-6 ;
  C2AB3  NUMBER := -1.880188e-7 ;

  C2ACc  NUMBER :=  0.9924228   ;
  C2ACe2 NUMBER :=  1.49528e-5  ;

  C2AD0  NUMBER :=  1.0130096    ;
  C2AD1  NUMBER := -9.307741e-4  ;
  C2AD2  NUMBER :=  7.380316e-6  ;

  C2AE0  NUMBER :=  1.125        ;
  C2AE1  NUMBER := -1.9181475e-4 ;
  C2AE2  NUMBER := 2.79903375e-7 ;

  BEGIN

    IF inLum > 0. then

-- Run 2A:E (and earlier periods)
      IF inPERIOD <= 'Run 2A:E' THEN
        ffactor := ffactor * (C2AE0 + C2AE1*inLum0 + C2AE2*inLum0**2);
      END IF;

-- Run 2A:D (and earlier periods)
      IF inPERIOD <= 'Run 2A:D' THEN
        ffactor := ffactor * (C2AD0 + C2AD1*inLum0 + C2AD2*inLum0**2);
      END IF;

-- Run 2A:C (and earlier periods)
      IF inPERIOD <= 'Run 2A:C' THEN
        ffactor := ffactor * (C2ACc * EXP( C2ACe2 * (inLum0**2) ));
      END IF;

-- Run 2A:B (and earlier periods)
      IF inPERIOD <= 'Run 2A:B' THEN
        ffactor := ffactor * (C2AB0 + C2AB1*inLum0 + C2AB2*inLum0**2 + C2AB3*inLum0**3);
      END IF;

-- Run 2A:A
      IF inPERIOD <= 'Run 2A:A' THEN
        ffactor := ffactor * C2AA0;
      END IF;

      outLum := ffactor * inLum;

    ELSE

      outLum := inLum;

    END IF;

   RETURN outLum; 

  EXCEPTION 
    WHEN OTHERS THEN
        dbms_output.put_line ('Function getCorrectedLum exception ----------');
        dbms_output.put_line ('Other Error');
        dbms_output.put_line ('ERROR '||sqlerrm);

 END;
/
