
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dos/rdargs.h>
#include <dos/stdio.h>
#include <proto/dos.h>
#include <proto/utility.h>

#define NODEBUG 1

#ifdef DEBUG
#   define Dputs puts
#else
#   define Dputs(x)
#endif

const char cont_template[] = "REST/M,IF/S,ENDIF/S,FI/S";

/* This structure is used to filter the body of the else */
struct ContStruct
{
    char ** rest;
    ULONG is_if;
    ULONG is_endif;
    ULONG is_fi;
};

int main (int argc, char ** argv)
{
    struct ContStruct cont_struct;
    struct RDArgs * cont_rda;
    int level;
    BPTR old_in, current_input;
    int cond = 0;
    LONG current_pos;
    int c;

    level = 0;

    current_input = Cli()->cli_CurrentInput;
    old_in = Input ();
    SelectInput (current_input);

    c = FGetC (current_input);
    Flush (current_input);
    UnGetC (current_input, c);

    memset (&cont_struct, 0, sizeof(cont_struct));

    for (;;)
    {
	if (!(cont_rda = ReadArgs ((char *)cont_template,
	    (LONG *)&cont_struct, NULL)) )
	{
	    PrintFault (IoErr(), "ContReadArgs");
	    cond = 10;
	    break;
	}

	if (cont_struct.is_if)
	{
	    Dputs ("Found if");
	    level ++;
	}
	else if (cont_struct.is_endif || cont_struct.is_fi)
	{
	    Dputs ("Found endif/fi");
	    if (!level)
		break;

	    level --;
	}
	else
	{
	    Dputs ("Line ignored");
	}

	memset (&cont_struct, 0, sizeof(cont_struct));
	FreeArgs (cont_rda);
    }

    if (level)
    {
	fprintf (stderr, "Missing ELSE or ENDIF");
	cond = 10;
    }

    SelectInput (old_in);

    if (cont_rda)
	FreeArgs (cont_rda);

    return (cond < 5) ? 0 : cond;
} /* main */

