<?php


require_once LIBRERIA_FPDF;

class RPTablaEfectividadAtencionUsuarios extends FPDF{

    var $widths;
    var $aligns;
    var $desde,$hasta,$datosFiltrados =false;



    function Header(){

            $this->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'logos' . DS . "CES.jpg", 19, 11, 18);
            $this->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'logos' . DS . "SNCF_GRIS.png", 245, 12, 16);

            $this->SetDrawColor(0, 0, 0); $this->SetFillColor(200, 200, 200); $this->SetTextColor(0, 0, 0);
            $this->SetFont('Arial', 'B', 6);


// Fila 1
            /*Col #1*/        $this->Cell(38, 20, utf8_decode(''), 1, 0, 'C', 0);
            /*Col #2*/        $this->Cell(110, 10, utf8_decode('FORMATOS DE RENDIMIENTO INTERNO'), 1, 0, 'C', 1);
            /*Col #3*/        $this->Cell(45, 5, utf8_decode('Página'), 1, 0, 'C', 1);
            /*Col #4*/        $this->Cell(35, 5, utf8_decode('Desde'), 1, 0, 'C', 1);
            /*Col #5*/        $this->Cell(30, 20, utf8_decode(''), 1, 0, 'C', 0);
            /*Col #6*/        $this->Cell(38, 5, utf8_decode(''), 0, 0, 'r', 0);
            /*NewLine*/       $this->Ln();

// Fila 2
            /*Col #1*/        $this->Cell(38, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #2*/        $this->Cell(110, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #3*/        $this->Cell(45, 5, utf8_decode(' '.$this->PageNo().'/{nb}'), 1, 0, 'C', 1);
            /*Col #4*/        $this->Cell(35, 5, utf8_decode(date('d-m-Y', strtotime($this->desde))), 1, 0, 'C', 1);
            /*Col #5*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/        $this->Cell(38, 5, utf8_decode(''), 0, 0, 'C', 0);
            /*NewLine*/       $this->Ln();

// Fila 3
            /*Col #1*/        $this->Cell(38, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #2*/        $this->Cell(110, 10, utf8_decode('TABLA DE EFECTIVIDAD DE ATENCIÓN A LOS USUARIOS FINALES'), 1, 0, 'C', 0);
            /*Col #3*/        $this->Cell(45, 5, utf8_decode('División de Automatización, '), 0, 0, 'C', 0);
            /*Col #4*/        $this->Cell(35, 5, utf8_decode('Hasta'), 1, 0, 'C', 0);
            /*Col #5*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/        $this->Cell(38, 5, utf8_decode(''), 0, 0, 'C', 0);
            /*NewLine*/       $this->Ln();

// Fila 4
            /*Col #1*/       $this->Cell(38, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #2*/       $this->Cell(110, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #3*/       $this->Cell(45, 5, utf8_decode('Informática y Telecomunicaciones'), 1, 0, 'C', 0);
            /*Col #4*/       $this->Cell(35, 5, utf8_decode(date('d-m-Y', strtotime($this->hasta))), 1, 0, 'C', 0);
            /*Col #5*/       $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/       $this->Cell(38, 5, utf8_decode(''), 0, 0, 'C', 0);
            $this->Ln();

        $this->drawTittle();
    }

    function drawTittle(){

        $this->ln(10);
        $this->SetDrawColor(0, 0, 0); $this->SetFillColor(200, 200, 200); $this->SetTextColor(0, 0, 0);
        $this->SetFont('Arial', 'B', 6);


// Fila 1
        /*Col #1*/        $this->Cell(8, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #2*/        $this->Cell(15, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #3*/        $this->Cell(10, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #4*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #5*/        $this->Cell(25, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #6*/        $this->Cell(10, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #7*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #8*/        $this->Cell(30, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #9*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #10*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #11*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*Col #Categoria*/        $this->Cell(25, 5, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #12*/        $this->Cell(35, 5, utf8_decode('SOLO PARA USO DEL USUARIO'), 1, 0, 'C', 0);
        /*Col #13*/        $this->Cell(20, 5, utf8_decode(''), 0, 0, 'C', 0);
        /*NewLine*/       $this->Ln();

// Fila 2
        /*Col #2*/        $this->Cell(8, 5, utf8_decode('N°'), 1, 0, 'C', 0);
        /*Col #3*/        $this->Cell(15, 5, utf8_decode('FECHA NOT.'), 1, 0, 'C', 0);
        /*Col #4*/        $this->Cell(10, 5, utf8_decode('PRIOR.'), 1, 0, 'C', 0);
        /*Col #5*/        $this->Cell(25, 5, utf8_decode('DEPENDENCIA'), 1, 0, 'C', 0);
        /*Col #6*/        $this->Cell(10, 5, utf8_decode('FUENTE'), 1, 0, 'C', 0);
        /*Col #7*/        $this->Cell(20, 5, utf8_decode('FUNCIONARIO'), 1, 0, 'C', 0);
        /*Col #8*/        $this->Cell(30, 5, utf8_decode('DETALLE'), 1, 0, 'C', 0);
        /*Col #9*/        $this->Cell(20, 5, utf8_decode('SOLUCIONADO'), 1, 0, 'C', 0);
        /*Col #10*/        $this->Cell(20, 5, utf8_decode('SOPORTE'), 1, 0, 'C', 0);
        /*Col #11*/        $this->Cell(20, 5, utf8_decode('OBSERVACIONES'), 1, 0, 'C', 0);
        /*Col #Categoria*/        $this->Cell(25, 5, utf8_decode('CATEGORÍA'), 1, 0, 'C', 0);
        /*Col #12*/        $this->Cell(20, 5, utf8_decode('TIEMPO'), 1, 0, 'C', 0);
        /*Col #13*/        $this->Cell(15, 5, utf8_decode('VALORACIÓN'), 1, 0, 'C', 0);
        /*Col #13*/        $this->Cell(20, 5, utf8_decode('FIRMA'), 1, 0, 'C', 0);
        /*NewLine*/       $this->Ln();


    }
    //Dibujamos el contenido del reporte.
    function drawContent(){
        $num=0;
        $this->SetFillColor(255, 255, 255);
        $this->SetFont('Arial', '', 7);


        foreach ( $this->datosFiltrados as $dato ){
            $this->SetWidths(array(8,15,10,25,10,20,30,20,20,20,25,20,15,20));
            $this->SetAligns(array('M','C','C','C','C','C','C','C','C','C','C','C','C','C'));

            //Hace lo mismo que el código de abajo pero con foreach
            //$dato['personas_asignadas'] es un array con los funcionarios asignados al ticket (activos e inactivos)
            /*foreach($dato['personas_asignadas'] as $asignado){
                if($asignado['estado_asignacion'] == 'Activo' &&  $asignado['is_Soporte'] == 1){
                    $soporte = $asignado['nombre_Persona'];
                    break;
                }
            }*/

            /*
             *   Buscamos el primer funcionario Soporte dentro de las personas asignadas al ticket.
                 Según el requerimiento del JEFE AIT se coloca el primer Soporte asignado al mismo como responsable,
                 si se desea colocar todos aquellos que sean soporte, usar el foreach anterior y eliminar el break
            */

            $niveles_prioridad = array(
                '1' => 'Normal',
                '2' => 'Alta',
                '3' => 'Critica',
            );

            $soporte = array_reduce($dato['personas_asignadas'], function ($soporte, $asignado) {
                // Detenemos el filtro si encontramos un resultado, debido a que solo queremos el primer soporte asignado
                if ($asignado['estado_asignacion'] == 'Activo' && $asignado['is_Soporte'] == 1) {
                    return $asignado['nombre_Persona'];
                }
                return $soporte;
            }, 'Sin Encargado');


            $fecha_inicial = !isset($dato['fecha_reactivacion'])
                                ? new DateTime ($dato['fecha_creacion'])
                                : new DateTime($dato['fecha_reactivacion']);

            $fecha_final = new DateTime($dato['fecha_cierre']);

            //$diferencia = $fecha_inicial->diff($fecha_final);
            $diferencia = $fecha_final->diff($fecha_inicial);

            if(isset($dato['fecha_cierre'])){
                if ($diferencia->d > 0){
                    if($diferencia->d == 1){
                        if ($diferencia->h > 0){
                            $duracion = $diferencia->d .' dia con ' . $diferencia->h .' hora(s) y '. $diferencia->i .' minutos(s)';
                        }else{
                            $duracion = $diferencia->d .' dia con ' . $diferencia->i .' minutos(s)';
                        }
                    }else{
                        if ($diferencia->h > 0){
                            $duracion = $diferencia->d .' dia(s) con ' . $diferencia->h .' hora(s) y '. $diferencia->i .' minutos(s)';
                        }else{
                            $duracion = $diferencia->d .' dia(s) con ' . $diferencia->i .' minutos(s)';
                        }
                    }
                }else{
                    if ($diferencia->h > 0){
                        if($diferencia->h == 1){
                            $duracion =  $diferencia->h .' hora y ' . $diferencia->i .' minutos(s)';
                        }else{
                            $duracion =  $diferencia->h .' hora(s) y ' . $diferencia->i .' minutos(s)';
                        }

                    }else{
                        $duracion = $diferencia->i .' minutos(s)';
                    }
                }
            }else{
                $duracion = 'Ticket sin Cerrar';
            }


            /*$duracion = isset($dato['fecha_cierre']) //Si Posee una fecha de Cierre colocamos su duración con dias y horas
                            ?  $diferencia->d > 0  //Si posee al menos 1 día de diferencía
                                    ?  $diferencia->d . ' día(s) con ' .  $diferencia->h . ' hora(s)' //se incluye
                                    :  $diferencia->h . ' hora(s)' // De lo contrario se asigna solo las horas
                            : 'Ticket sin Cerrar'; // si no posee fecha cierre, indicamos que está sin cerrar*/


            $this->Row(array(
                ++$num,
                utf8_decode(date('d-m-Y H:i:s', strtotime($dato['fecha_creacion']))    ),
                utf8_decode($niveles_prioridad[$dato['nivel_prioridad']]),
                utf8_decode($dato['dependencia_afectada_Ticket']),
                utf8_decode($dato['fuente_solicitud']),
                utf8_decode($dato['nombre_Funcionario_Emisor']),
                utf8_decode($dato['observacion']),
                utf8_decode($dato['estado']),
                utf8_decode($soporte),
                utf8_decode(strlen($dato['observacion_Cierre_Ticket'])==0?'Sin observación':$dato['observacion_Cierre_Ticket']),
                utf8_decode($dato['codigo_categoria'] .' => '. $dato['descripcion']),
                utf8_decode($duracion),
                utf8_decode($dato['respuesta_evaluacion']),
                utf8_decode(''),
            ));
        }
        $this->ln();
    }


    function Footer(){

        $año_actual = date("Y");
            $this->SetFont('Arial', '', 6); $this->SetXY(95, 190); $this->Cell(200, 5,utf8_decode( 'La información contenida en este documento es propiedad intelectual de la Contraloría del Estado Sucre'), 0, 0, 'L');
            $this->SetFont('Arial', '', 6); $this->SetXY(90, 193); $this->Cell(200, 5,utf8_decode( 'Se prohíbe la reproducción total o parcial del mismo, sin consentimiento explícito de la Contraloría del Estado Sucre'), 0, 0, 'L');
            $this->SetFont('Arial', 'B', 6); $this->SetXY(105, 196); $this->Cell(200, 5,utf8_decode( 'CONTRALORÍA DEL ESTADO SUCRE - Todos los derechos reservados '.$año_actual), 0, 0, 'L');
            $this->SetFont('Arial', 'B', 6); $this->SetXY(125, 199); $this->Cell(200, 5,utf8_decode( 'direccion.tecnica@cgesucre.gob.ve'), 0, 0, 'L');

     }

    function setDesde($desde){
        $this->desde = $desde;
    }
    function setHasta($hasta){
        $this->hasta = $hasta;
    }
    function setDatosFiltrados($datosFiltrados){
        $this->datosFiltrados=$datosFiltrados;
    }
    function SetWidths($w){
        //Set the array of column widths
        $this->widths=$w;
    }


    function CheckPageBreak($h)
    {
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }
    function NbLines($w,$txt)
    {
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }



}

class RPInformeMensualSoporte extends FPDF{
    var $desde,$hasta,$datosFiltrados,$jefe,$director;


    function Header(){

            $this->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'logos' . DS . "CES.jpg", 17, 11, 18);
            $this->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'logos' . DS . "SNCF_GRIS.png", 167, 12, 16);
        //$this->SetFont('Arial', '', 10); $this->SetXY(10, 10); $this->Cell(200, 5,utf8_decode( 'Contraloria Del estado Sucre'), 0, 0, 'L');

        $this->SetDrawColor(0, 0, 0); $this->SetFillColor(200, 200, 200); $this->SetTextColor(0, 0, 0);
            $this->SetFont('Arial', 'B', 6);



// Fila 1
            /*Col #1*/        $this->Cell(30, 20, utf8_decode(''), 1, 0, 'C', 0);
        $this->SetFont('Arial', 'B', 10);
            /*Col #2*/        $this->Cell(80, 10, utf8_decode('DIRECCIÓN TÉCNICA'), 1, 0, 'C', 0);
        $this->SetFont('Arial', 'B', 6);
            /*Col #3*/        $this->Cell(20, 5, utf8_decode('Pagina'), 1, 0, 'C', 0);
            /*Col #4*/        $this->Cell(20, 5, utf8_decode('Elaboración'), 1, 0, 'C', 0);
            /*Col #5*/        $this->Cell(30, 20, utf8_decode(''), 1, 0, 'C', 0);
            /*Col #6*/        $this->Cell(30, 5, utf8_decode(''), 0, 0, 'r', 0);
            /*NewLine*/       $this->Ln();

// Fila 2
            /*Col #1*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #2*/        $this->Cell(80, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #3*/        $this->Cell(20, 5, utf8_decode(' '.$this->PageNo().'/{nb}'), 1, 0, 'C', 0);
            /*Col #4*/        $this->Cell(20, 5, utf8_decode($this->desde), 1, 0, 'C', 0);
            /*Col #5*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/        $this->Cell(30, 5, utf8_decode(''), 0, 0, 'C', 0);
            /*NewLine*/       $this->Ln();

// Fila 3
            /*Col #1*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
        $this->SetFont('Arial', 'B', 8);
            /*Col #2*/        $this->Cell(80, 10, utf8_decode('INFORME ACTIVIDADES DE SOPORTE A USUARIOS'), 1, 0, 'C', 0);
        $this->SetFont('Arial', 'B', 6);
            /*Col #3*/        $this->Cell(20, 5, utf8_decode('Versión: '), 0, 0, 'C', 0);
            /*Col #4*/        $this->Cell(20, 5, utf8_decode('Actualización'), 1, 0, 'C', 0);
            /*Col #5*/        $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/        $this->Cell(30, 5, utf8_decode(''), 0, 0, 'C', 0);
            /*NewLine*/       $this->Ln();

// Fila 4
            /*Col #1*/       $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #2*/       $this->Cell(80, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #3*/       $this->Cell(20, 5, utf8_decode('1.0'), 1, 0, 'C', 0);
            /*Col #4*/       $this->Cell(20, 5, utf8_decode($this->hasta), 1, 0, 'C', 0);
            /*Col #5*/       $this->Cell(30, 0, utf8_decode(''), 0, 0, 'C', 0);
            /*Col #6*/       $this->Cell(30, 5, utf8_decode(''), 0, 0, 'C', 0);
            $this->Ln();


    }
    function Footer(){
            $this->SetFont('Arial', '', 10); $this->SetXY(56, 220); $this->Cell(200, 5,utf8_decode( $this->jefe), 0, 0, 'L');
            $this->SetFont('Arial', '', 10); $this->SetXY(121, 220); $this->Cell(200, 5,utf8_decode( $this->director), 0, 0, 'L');
            $this->SetFont('Arial', 'B', 10); $this->SetXY(53, 225); $this->Cell(200, 5,utf8_decode( 'JEFE DE DIVISIÓN AIT'), 0, 0, 'L');
            $this->SetFont('Arial', 'B', 10); $this->SetXY(120, 225); $this->Cell(200, 5,utf8_decode( 'DIRECTORA TÉCNICA'), 0, 0, 'L');
    }
    function drawTittle(){

        $this->SetFont('Arial','',10);
        $this->SetXY(10, 40);
        $this->MultiCell(190, 7, utf8_decode('     Por medio del presente me dirijo a usted, a los fines de informarle sobre las actividades de soporte técnico realizadas por esta Dirección, las cuales están relacionadas a continuación:'));

        /* $this->ln(8);
        $this->SetWidths(200);
        $this->SetFillColor(255, 255, 255);
        $this->SetFont('Arial', '', 9);
        $this->SetAligns('J');
        $this->Set
        $this->Row(array(utf8_decode('     Por medio del presente me dirijo a usted, a los fines de informarle sobre las actividades de soporte técnico realizadas por esta Dirección, las cuales están relacionadas a continuación:')));
        */$this->ln(10);
    }
    function drawContent(){
        $numResultados=0;


            $positionYPadre = 68;
        foreach ($this->datosFiltrados as $dato){
            $positionYHijo = $positionYPadre +5;
            //Impresión del Titulo de cada Falla registrada con su Total
            $this->SetFont('Arial', 'B', 10); $this->SetXY(15, $positionYPadre); $this->Cell(200, 5,utf8_decode( $dato['codigo'].') '.$dato['nombre'].': ('.$dato['cantidad'].' casos) '), 0, 0, 'L');
            //Impresión del texto que resumirá sus hijos
            $this->SetFont('Arial', '', 9); $this->SetXY(15, $positionYHijo); $this->Cell(200, 5,utf8_decode( 'En las Dependencias:'), 0, 0, 'L');

            $positionXHijo = 47;
            $detalleDependencias ="";
            foreach ($dato['dependencias'] as $dependencia){
                //Llena String con las abreviaciones de la dependencia y la cantidad de cada una
                $detalleDependencias .= $dependencia['Nombre'].' ('.$dependencia['Cantidad'].') ';
                $numResultados += $dependencia['Cantidad'];
            }
            $this->SetFont('Arial', '', 9); $this->SetXY($positionXHijo, $positionYHijo); $this->Cell(200, 5,utf8_decode( $detalleDependencias), 0, 0, 'L');

            $positionYPadre = $positionYHijo+8;
        }


        $this->SetFont('Arial','',10);
        $this->SetXY(15, $positionYPadre+5);
        //$formato = new NumberFormatter("en", NumberFormatter::SPELLOUT);
        $this->MultiCell(190, 7, utf8_decode('        Registrándose un total de'.''.' ('.$numResultados.') casos de los cuales se anexan a la presente los Formatos con la Tabla de Efectividad de Atención a los Usuarios, debidamente firmadas por los funcionarios de este Organismo Contralor atendidos. '));


        $this->ln();
    }
    function setDesde($desde){
        $this->desde = $desde;
    }
    function setHasta($hasta){
        $this->hasta = $hasta;
    }
    function setJefe($jefe){
        $this->jefe=$jefe;
    }
    function setDirector($director){
        $this->director=$director;
    }
    function setDatosFiltrados($datosFiltrados){
        $this->datosFiltrados=$datosFiltrados;
    }
    function SetWidths($w){
        //Set the array of column widths
        $this->widths=$w;
    }
    function SetAligns($a){
        //Set the array of column alignments
        $this->aligns=$a;
    }
    /*function Row($data)
    {
        //Calculate the height of the row
        $nb=0;
        for($i=0;$i<count($data);$i++)
            $nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
        $h=5*$nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for($i=0;$i<count($data);$i++)
        {
            $w=$this->widths[$i];
            $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x=$this->GetX();
            $y=$this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h);
            //Print the text
            $this->MultiCell($w,5,$data[$i],0,$a);
            //Put the position to the right of the cell
            $this->SetXY($x+$w,$y);
        }
        //Go to the next line
        $this->Ln($h);
    }*/
    function CheckPageBreak($h)
    {
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }
    function NbLines($w,$txt)
    {
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }
}


