DECLARE V_VRPARCELAS  FLOAT;
        V_VRACUMULADO FLOAT;
        V_NRCONTADOR  NUMBER;
        V_NRPARCELAS  NUMBER;
BEGIN
   FOR C IN (
      SELECT C.*, N.CDFILIRECE
      FROM CONTAPAGAR C, NOTAFISCAL N
      WHERE N.CDFILIAL = C.CDFILIAL
        AND N.NRLANCTONF = C.NRLANCTONF
        AND C.DTATUAVENPAG >= '01/01/2008'
        AND N.IDSISTEMA <> 'PAG')
   LOOP
      DELETE RATCTPAGAR
      WHERE CDFILIAL    = C.CDFILIAL
        AND NRLANCTONF  = C.NRLANCTONF
        AND NRSEQVENPAG = C.NRSEQVENPAG;

      V_NRCONTADOR  := 1;
      V_NRPARCELAS  := 0;
      V_VRPARCELAS  := 0;
      V_VRACUMULADO := 0;

      SELECT COUNT(*)
      INTO V_NRPARCELAS
      FROM RATTPCTP
      WHERE CDTPCTPAGAR = C.CDTPCTPAGAR;

      FOR C_RATTPCTR IN (SELECT CDTPCTPAGAR, CDCENTCUST,
                                NVL(LTRIM(REPLACE(CDFIRATTPCTP, '----', C.CDFILIRECE)), C.CDFILIRECE) AS CDFIRATTPCTP,
                                CDFILIAL, VRPERATTPCTP
                         FROM RATTPCTP
                         WHERE CDTPCTPAGAR = C.CDTPCTPAGAR) LOOP

         V_VRPARCELAS  := ROUND(C.VRATUAPAG * (C_RATTPCTR.VRPERATTPCTP/100),2);
         V_VRACUMULADO := V_VRACUMULADO + V_VRPARCELAS;

         IF V_NRPARCELAS = V_NRCONTADOR THEN
            IF V_VRACUMULADO > C.VRATUAPAG THEN
               V_VRPARCELAS := ROUND(V_VRPARCELAS - (ABS(C.VRATUAPAG - V_VRACUMULADO)),2);
            ELSE
               IF V_VRACUMULADO < C.VRATUAPAG THEN
                  V_VRPARCELAS := ROUND(V_VRPARCELAS + (ABS(C.VRATUAPAG - V_VRACUMULADO)),2);
               END IF;
            END IF;
         END IF;

         INSERT INTO RATCTPAGAR
            (CDFILIAL, NRLANCTONF, NRSEQVENPAG, NRPARCELAPAG,
             CDCENTCUST, CDFIRATCTPAG, VRRATCCCTPAG)
         VALUES
            (C.CDFILIAL, C.NRLANCTONF, C.NRSEQVENPAG, C.NRPARCELAPAG,
             C_RATTPCTR.CDCENTCUST, C_RATTPCTR.CDFIRATTPCTP, V_VRPARCELAS);

         V_NRCONTADOR := V_NRCONTADOR + 1;
      END LOOP;
      COMMIT;
   END LOOP;
END;
/
