/*                                                               -*- C -*-
 *  MAIN.C
 *
 *  (c)Copyright 1994,95 by Tobias Ferber,  ukjg@rz.uni-karlsruhe.de
 *
 *  This file is part of the AMan distribution
 *
 *  AMan is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published
 *  by the Free Software Foundation; either version 1 of the License,
 *  or (at your option) any later version.
 *
 *  AMan is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; see the file COPYING.  If not, write to
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* $VER: $Id: main.c,v 1.1 1995/07/21 20:56:12 tf Exp $ */

#include "version.h"

#include <clib/muimaster_protos.h>
#include <clib/alib_protos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>

#include <stdlib.h>
#include <stdio.h>

#include "aman.h"

extern BOOL MatchPatternNoCase(STRPTR, STRPTR);

struct Library *MUIMasterBase;

/*
 *  Insert all docs matching `expr' into the listview `lv'
 */

static int fdb(APTR lv, char *negpat, char *dbase, char *expr)
{
  int err= 0;
  char strbuf[1024],fname[80];

  sprintf(fname,"T:AMan.%ld",FindTask(NULL));
  sprintf(strbuf,"FDB NH F DB \"%s\" P \"%s\" > \"%s\"",dbase,expr,fname);

#ifdef DEBUG
  printf("system(%s)\n",strbuf);
#endif

  if( (err= system(strbuf)) == 0 )
  {
    FILE *fp= fopen(fname,"r");

    if(fp)
    {
      while( !feof(fp) )
      {
        int len= strlen( fgets(strbuf,sizeof(strbuf),fp) ) - 1;
        strbuf[(len >= 0) ? len : 0]= '\0';

        if( !feof(fp) && strbuf[0] && (!negpat || (negpat && !MatchPatternNoCase(negpat,strbuf))) )
          DoMethod( lv, MUIM_List_InsertSingle, strbuf, MUIV_List_Insert_Sorted );
      }
      fclose(fp);
    }
    else err= 1;
  }

  return err + unlink(fname);
}

/**/

struct RDArgs *StrReadArgs(STRPTR template, LONG *array, STRPTR str)
{
  static struct RDArgs rdargs;

  rdargs.RDA_Source.CS_Buffer = str;
  rdargs.RDA_Source.CS_Length = strlen(str);
  rdargs.RDA_Source.CS_CurChr = 0;
  rdargs.RDA_DAList = 0;
  rdargs.RDA_Buffer = NULL;
  rdargs.RDA_BufSiz = 0;
  rdargs.RDA_ExtHelp = NULL;
  rdargs.RDA_Flags = RDAF_NOPROMPT;

  return ReadArgs(template,array,&rdargs);
}

/**/

int aman(char *fname)
{
  int done= 0;
  char strbuf[1024];

  FILE *fp= fopen("ENV:AMan.config","r");

  if(fp)
  {
    while( !done && !feof(fp) )
    {
      int len= strlen( fgets(strbuf,sizeof(strbuf),fp) ) - 1;
      strbuf[(len >= 0) ? len : 0]= '\0';

      if( !feof(fp) && strbuf[0] )
      {
        long args[2]= { 0,0 };
        struct RDArgs *a;

        if( (a= StrReadArgs("PATTERN/A,COMMAND/A",args,strbuf)) )
        {
          char pattern[80];
          ParsePatternNoCase( (char *)(args[0]), pattern, sizeof(pattern) );

          if( MatchPatternNoCase(pattern,fname) )
          {
            sprintf(strbuf,(char *)args[1],fname);
            done= 1;
          }
          FreeArgs(a);
        }
        /*else done= -1;*/  /* !StrReadArgs() */
      }
    }
    fclose(fp);
  }

  if(!done)
    sprintf(strbuf,"Run <NIL: >NIL: MultiView \"%s\"",fname);

  return (done < 0) ? 1 : system(strbuf);
}

/**/

int newargs(struct ObjApp *app, LONG *args)
{
  int err= RETURN_OK;

  char *str= (char *)(args[1]);
  char *pat= (char *)0;

  char *db= args[0] ? (char *)(args[0]) : "aman";

  if(str)
  {
    size_t len= 2*strlen(str)+2;

    if( (pat= (char *)malloc(len)) )
      ParsePatternNoCase( str, pat, len );
    else
      err= ERROR_NO_FREE_STORE;
  }

  if(err == RETURN_OK)
  {
    char **expr= (char **)(args[2]);

    if(expr) while(*expr)
      fdb( app->LV_aman, pat, db, *expr++ );

    set( app->LV_aman, MUIA_List_Active, MUIV_List_Active_Top );
    set( app->WI_aman, MUIA_Window_ActiveObject, app->LV_aman );
  }

  if(pat)
    free(pat);

  return err;
}

/**/

int main(int argc, char *argv[])
{
  static char *template= "DB=DataBase/K,H=Hide/K,P=Pattern/A/M";
  struct RDArgs *a= (struct RDArgs *)0;
  LONG args[3] = { 0,0,0 };  /* args array */
  int rc= RETURN_OK;

  if( (argc==0) || (a= ReadArgs(template, args, NULL)) )
  {
    if( (MUIMasterBase = OpenLibrary(MUIMASTER_NAME, MUIMASTER_VMIN)) )
    {
      struct ObjApp *app;

      BOOL running;
      ULONG signal;

      if( (running= (app= CreateApp()) ? TRUE : FALSE) )
      {
        if(argc > 0) running= ( (rc= newargs(app,args)) == RETURN_OK ) ? TRUE : FALSE;
        else set( app->WI_aman, MUIA_Window_ActiveObject, app->STR_pattern );

        while(running)
        {
          switch( DoMethod(app->App, MUIM_Application_Input, &signal) )
          {
            case MUIV_Application_ReturnID_Quit:
              running = 0;
              break;

            case ID_SELECT:
              set( app->WI_aman, MUIA_Window_Sleep, TRUE);
              {
                char *fname;
                DoMethod( app->LV_aman, MUIM_List_GetEntry, MUIV_List_GetEntry_Active, &fname );
                running= aman(fname) ? FALSE : TRUE;
              }
              set( app->WI_aman, MUIA_Window_Sleep, FALSE);
              break;

            case ID_SUBJECT:
               set( app->WI_aman, MUIA_Window_Sleep, TRUE);
               {
                 char *str, *buf;
                 get( app->STR_pattern, MUIA_String_Contents, &str );

                 if(str && *str)
                 {
                   if( (buf= (char *)malloc(strlen(str)+2)) )
                   {
                     sprintf(buf,"%s ",str);
                     FreeArgs(a);
                     if( (a= StrReadArgs(template, args, buf)) )
                       running= ( (rc= newargs(app,args)) == RETURN_OK ) ? TRUE : FALSE;
                     /*else PrintFault(rc= IoErr(), "Subject"), running= FALSE;*/
                     free(buf);
                   }
                   else rc= ERROR_NO_FREE_STORE, running= FALSE;
                 }
               }
               set( app->WI_aman, MUIA_Window_Sleep, FALSE);
               break;

            case ID_ABOUT:
              MUI_Request(app->App, app->WI_aman, 0, NULL, "OK", MUIX_C
                "AMan (compiled " __DATE__ ", " __TIME__ ")\n"
                "Copyright ©1994,95 by Tobias Ferber, ukjg@rz.uni-karlsruhe.de\n"
                "\nThis is a MUI-Application.\n"
                "MUI is copyrighted by Stefan Stuntz.",
                TAG_END);
              break;
          }

          if(running && signal)
            Wait(signal);
        }

        DisposeApp(app);
      }

      CloseLibrary(MUIMasterBase);
    }
    else /* !MUIMasterBase */
    {
      sprintf(stderr,"You need %s V%ld+\n",MUIMASTER_NAME,MUIMASTER_VMIN);
      rc= RETURN_FAIL;
    }

    if(a)
      FreeArgs(a);
  }
  else /* !ReadArgs() */
  {
    if(argc == 1)
      puts( "AMan Version " VERSION " (compiled " __DATE__ ", " __TIME__ ")\n"
            "(c)Copyright 1994,95 by Tobias Ferber, ukjg@rz.uni-karlsruhe.de\n"
            "\n"
            "AMan is free software; you can redistribute it and/or modify\n"
            "it under the terms of the GNU General Public License as published\n"
            "by the Free Software Foundation; either version 2 of the License,\n"
            "or (at your option) any later version.\n"
            "\n"
            "AMan is distributed in the hope that it will be useful,\n"
            "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
            "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
            "GNU General Public License for more details.\n"
            "\n"
            "You should have received a copy of the GNU General Public License\n"
            "along with this program; see the file COPYING.  If not, write to the\n"
            "Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n" );
    else
      PrintFault(rc= IoErr(), NULL);
  }

  return rc;
}      


#ifdef _DCC
int brkfunc(void) { return(0); }

int wbmain(struct WBStartup *wb_startup)
{
  /*extern int main(int argc, char *argv[]);*/
  return (main(0, (char **)wb_startup));
}
#endif /* _DCC */


#ifdef __SASC
int CXBRK(void) { return(0); }
int _CXBRK(void) { return(0); }
void chkabort(void) {}
#endif /* __SASC */

LONG __stack = 8192;
