/********************************************************************
                         DelLines

   Description: Deletes empty lines
   Syntax:      DelLines
   Version:     2

   This script can also be used for other purpuses. For example if
   you want to delete all lines that begins with "#include", just
   replace EMPTYLINE_REGEXP to:

   #define EMPTYLINE_REGEXP " *#include"

   Author: Vedran Gaco
********************************************************************/

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <editor/doc.h>
#include <editor/macros.h>

#define EMPTYLINE_REGEXP  "^ *$"

// function prototypes
void ScriptMain(HDOC);


/*-------------------------------------------------------------------
                    main function
-------------------------------------------------------------------*/

int main(int argc, char *argv[])
{
   HDOC hDoc;

   hDoc = Gte_GetActiveDocument();
   if(hDoc == NULL) {
      MsgBox("Cannot get handle of the active document!", MB_OK);
      return 1;
   }
   // check if document is read only
   if(Gte_IsReadOnly(hDoc)) {
      MsgBox("Document is read only!", MB_OK);
      return 1;
   }
   // turn off line drawing and/or selecting mode
   GM_EndLineDraw(hDoc);
   GM_EndSelect(hDoc);

   // call main script function
   ScriptMain(hDoc);

   return 0;
}


/*-------------------------------------------------------------------
                         ScriptMain

  Main script function.

  PARAMETERS

     hDoc - Handle of the active document.
-------------------------------------------------------------------*/

void ScriptMain(HDOC hDoc)
{
   long nLine;

   WaitCursor();
   Gte_LockUpdate(hDoc);
   GM_SaveCursorPos(hDoc);

   nLine = 1;
   while(nLine < Gte_GetNumberOfLines(hDoc))
   {
      Gte_SetCursorPos(hDoc, 1, nLine, FALSE);
      if(Gte_FindInLine(hDoc, EMPTYLINE_REGEXP, 1, nLine, FALSE, FALSE, TRUE, TRUE) == 0)
      {
          GM_Delete(hDoc);
      }
      else {            // Else clause added to delete ALL lines -RFS
         nLine++;
      }
   }

   if(nLine == Gte_GetNumberOfLines(hDoc))
   {
      if(Gte_FindInLine(hDoc, EMPTYLINE_REGEXP, 1, nLine, FALSE, FALSE, TRUE, TRUE) == 0)
      {
          GM_Delete(hDoc);
      }
   }
   GM_SaveCursorPos(hDoc);
   Gte_UnlockUpdate(hDoc);
   RestoreCursor();
}
