function ueplTabsToSpaces() {
    /* Conditions and Error Handaling are prefixed with appropiate keyWork */

    /* ----------------------------- Error Handling ------------------------------- */
    // Check if there are documents on editor and check if they are active
    // if not active show error and stop the process.
    if (UltraEdit.document.length < 1 || !UltraEdit.activeDocument.path) {
        handleError("Tabs (leading) to Spaces Plugin Error", "There is no active document to convert leading tabs to spaces");
        return;
    };
    //check if lines are selected
    if (!UltraEdit.activeDocument.isSel()) {
        handleError("Tabs (leading) to Spaces Plugin Error", "No Text Selected");
        return;
    }
    /* ---------------------------------------------------------------------------- */


    /* -------------------------Tabs(leading) to spaces----------------------------- */
    const selectedString = UltraEdit.activeDocument.selection
    let spacesPerTab = 2;                     // As UltraEdit Team requested we have hard coded it , should get the value from application configuration later.

    const lines = selectedString.split('\n');
    const convertedLines = lines.map(line => {
        line = line.replace(/^( |\t)+/, (match) => {
            return match.replace(/\t/g, ' '.repeat(spacesPerTab));
        });
        return line;
    });
    const convertedString = convertedLines.join('\n');
    UltraEdit.activeDocument.write(convertedString);

}

function OnInit() {
    UltraEdit.processPIOnInit(`{
        "guid": "6cfdb9e2-3eb5-4055-b644-46a429fd124b",
        "ueplTabsToSpaces": {
            "type": "Execute",
            "display name": "Convert Tabs to Spaces (leading)",
            "short description": "Tabs (leading) to spaces",
            "icon": "",
            "hotkey": "Ctrl + [",
            "chord": "Ctrl + T",
            "ribbonCategoryID": "200171",
            "ribbonPanelID": "200176",
            "ribbonElementID": "200182"
        }
    }`);
}

/**
 * Helper function to show formated error to a user.
 * It shows a dialog box and shows error in output window if provided
 * @param {string} title 
 * @param {string} titleDesc 
 * @param {string} outputText 
 */
function handleError(title, titleDesc, outputText = `Tabs (leading) to Spaces Plugin Error -> ${titleDesc}`) {
    UltraEdit.messageBox(titleDesc, title);
    UltraEdit.outputWindow.write(outputText);
}
