Simulate pen tool behaviour with code

Hello :). I am wondering how I can simulate pen tool functionality with code. The problem is that if I use this simple code

var pencilDraw:Shape = new Shape();
var firstPointX:int;
var firstPointY:int;
var firstPoint:Boolean = false;
var pointsX:Array = new Array();
var pointsY:Array = new Array();
addChild(pencilDraw);




stage.addEventListener(MouseEvent.CLICK, drawLine);



function drawLine(event:MouseEvent):void {
    trace("x " ,mouseX, "Y ", mouseY);
    if (!firstPoint) {
        firstPointX = mouseX;
        firstPointY = mouseY;
        pencilDraw.graphics.lineStyle(1, 0x000000, 1);
        pencilDraw.graphics.moveTo(mouseX, mouseY);
        pencilDraw.graphics.lineTo(mouseX, mouseY);
        firstPoint = true;
        pointsX.push(firstPointX);
        pointsY.push(firstPointY);
    } else {
        if (((firstPointX - 3) < mouseX) && (firstPointX <  (firstPointX + 3)) && ((firstPointY - 3) < mouseY) && (mouseY < (firstPointY + 3))) {
            colorize();
        } else {
            pointsX.push(mouseX);
            pointsY.push(mouseY);
            pencilDraw.graphics.lineTo(mouseX, mouseY);
        }
        
    }
}

function colorize():void {
    pencilDraw.graphics.beginFill(0x000000, 1);
    pencilDraw.graphics.moveTo(firstPointX, firstPointY);
    for (var i:int=0; i < pointsX.length; i++) {
        
        pencilDraw.graphics.lineTo(pointsX*, pointsY*);
        if (i == pointsX.length - 1) {
            pencilDraw.graphics.endFill();
        }
    }
}

then I don’t know how to fill the shape or manipulate the borders.