/*
 * $VER: ged6indent 1.3 (5.8.99)
 *
 * ged4indent - indent a C source file in GoldEd, using GNUindent
 *
 * Written by Thomas Aglassinger <agi@giga.or.at>
 *
 * This is Public Domain, refer to ReadMe for usage.
 */

OPTIONS RESULTS                             /* enable return codes     */

if (LEFT(ADDRESS(), 6) ~= "GOLDED") then    /* not started by GoldEd ? */
    address 'GOLDED.1'

'LOCK CURRENT RELEASE=6'                    /* lock GUI, gain access   */
OPTIONS FAILAT 6                            /* ignore warnings         */
SIGNAL ON SYNTAX                            /* ensure clean exit       */


/* name of temporary outputfile used by `indent' */
indfname = 't:ged6indent.' || PRAGMA('ID')

/* Give some feedback to the user */
'REQUEST STATUS="Reformatting..."'

/* obtain current filename */
'QUERY DOC VAR=filename'
filename = RESULT

/* save file, remember current position */
'SAVE ALL'
'QUERY ABSLINE VAR oldLine'

/* determine which options to use for indent:
 * tries to read the environmental variable `ged6indent.prefs';
 * if it can't be found, default options matching the style of
 * GoldEd will be used */
indentOpts = GetEnv('ged6indent.prefs')
IF indentOpts = '' THEN DO
    indentOpts = '-br -ce -i4 -sob -sc -npsl -npcs -lp'
END

/* invoke indent */
indentCommand = 'indent' indentOpts  '"' || filename || '"  -o "' || indfname || '"'
ADDRESS COMMAND indentCommand

IF (RC = 0) THEN DO
    /* copy temporary file to input filename */
    copyCommand = 'copy CLONE QUIET "' || indfname || '" "' || filename || '"'
    ADDRESS COMMAND copyCommand

    /* reload indented file */
    IF (RC = 0) THEN DO
        'OPEN AGAIN FORCE'
    END
END
ELSE DO
    /* tell user that indent was not successful */
    SAY ''
    SAY 'error calling indent; "' || filename || '" left untouched'
END

/* restore position */
'GOTO LINE=' || oldLine
'GOTO INDENT'

/* remove temporary file */
CALL DelFileExists(indfname)

'REQUEST STATUS=""'

'UNLOCK' /* VERY important: unlock GUI */
EXIT

/*
 * handle syntax errors
 */
SYNTAX:

SAY "Sorry, error line" SIGL ":" ERRORTEXT(RC) ":-("
'UNLOCK'
EXIT


/***************
 * subroutines *
 ***************/

/*
 * GetEnv(): return the value of an environmental variable
 */
GetEnv: procedure
    IF Open(Env, 'env:' || arg(1), 'R') THEN DO
        EnvVar = ReadLn(Env)
        CALL Close Env
    END
    ELSE DO
        EnvVar = ''
    END
    RETURN EnvVar

/*
 * DelFileExists(): delete a file if it exists
 */
DelFileExists: procedure
    IF Exists(arg(1)) THEN DO
        ADDRESS COMMAND 'delete QUIET "' || arg(1) || '"'
    END
    RETURN


