/*
 * $VER: ged4indent 1.1 (11.6.97)
 *
 * ged4indent - indent a C sourcefile 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=4'                    /* lock GUI, gain access   */
OPTIONS FAILAT 6                            /* ignore warnings         */
SIGNAL ON SYNTAX                            /* ensure clean exit       */

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

/* compute temporary filename */
tmpfname = 't:ged4indent.' || PRAGMA('ID')

/* save file, remember current position */
'SAVE ALL'
'PING 0'

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

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

IF (RC = 0) THEN DO

    /* copy temporary file to input filename */
    copyCommand = 'copy CLONE QUIET "' || tmpfname || '" "' || filename || '"'
    ADDRESS COMMAND copyCommand

    /* reload indented file, restore position */
    IF (RC = 0) THEN DO
        'OPEN AGAIN FORCE'
        'PONG 0'
    END

    /* remove temporary file */
    IF Exists(tmpfname) THEN DO
        ADDRESS COMMAND 'delete QUIET "' || tmpfname || '"'
    END
END
ELSE DO

    /* tell user that indent was not successful */
    SAY ''
    SAY 'error calling indent; "' || filename || '" left untouched'
    IF Exists(tmpfname) THEN DO
        SAY '"' || tmpfname || '" contains output'
    END
    ELSE DO
        SAY 'no output file created'
    END
END

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

/*
 * handle syntax errors
 */
SYNTAX:

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

/*
 * 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

