CREATE OR REPLACE PROCEDURE MENSAL_PROX_DATA_ENTREGA
  (P_CDFILIAL     IN VARCHAR2,
   P_CDPERIENTR   IN VARCHAR2,
   P_DTINICIAL    IN DATE,
   P_IDDIANUTIL   IN VARCHAR2,
   P_DTDIAENTR    OUT DATE)

 IS

   V_CONTAUXI   NUMBER;         
   V_DIENTREGA  VARCHAR2(2);   
   V_DTDIAENTR  DATE;
   V_IDDIASEM   NUMBER;
   V_DTENTRAUX  DATE;
   V_PRIMVEZ    NUMBER;
   V_DIPRIMVEZ  VARCHAR2(2);
  

BEGIN
    SELECT MIN(DIENTREGA) INTO V_DIENTREGA
    FROM DIASENTR
    WHERE
     CDPERIENTR = P_CDPERIENTR;
    
     V_DTDIAENTR := LAST_DAY(P_DTINICIAL) + V_DIENTREGA;
     IF V_DTDIAENTR > LAST_DAY(LAST_DAY(P_DTINICIAL) + 1) THEN
        V_DTDIAENTR := LAST_DAY(LAST_DAY(P_DTINICIAL) + 1);
     END IF; 
    
/*- CALCULA UMA DATA DE ENTREGA ANTERIOR A UMA DATA NAO UTIL -*/
    IF P_IDDIANUTIL = 'S' THEN
       V_CONTAUXI := 1;
        WHILE V_CONTAUXI > 0 LOOP
          SELECT COUNT(*) INTO V_CONTAUXI
          FROM FERICOMP


          WHERE
          CDFILIAL = P_CDFILIAL AND 
          DTFERICOMP = V_DTDIAENTR;
          IF V_CONTAUXI > 0 THEN
             V_DTDIAENTR := V_DTDIAENTR - 1;
          END IF;
        END LOOP;
      END IF;
      V_DTDIAENTR := V_DTDIAENTR - 1;
   
   P_DTDIAENTR := V_DTDIAENTR;
END;
/