#include <exec/types.h>
#include <libraries/dos.h>
#include <workbench/workbench.h>
#include <workbench/startup.h>

#include <clib/alib_protos.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/icon_protos.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BUFF_SIZE 128

void cleanexit(UBYTE *s);

struct Library *IconBase = NULL;
LONG olddir = -1;
struct DiskObject *dobj;


void main(int argc, char **argv)
{
  struct WBStartup *WBMsg;
  struct WBArg *wbarg;
  SHORT i;
  char buff[BUFF_SIZE];
  BOOL ret;

  /* apro la icon.library */
  if(!(IconBase = OpenLibrary("icon.library",33)))
    cleanexit("Non posso aprire la icon.library\n");

  if (argc==0) {
    /* lanciato da Workbench; recupero l'array di  */
    /* WBArg e posiziono "wbarg sul secondo (il    */
    /* primo è relativo al programma stesso)       */
    WBMsg = (struct WBStartup *)argv;
    wbarg = WBMsg->sm_ArgList+1;

    /* elaboro tutti gli elementi dell'array       */
    for ( i = 1; i<WBMsg->sm_NumArgs; i++, wbarg++) {
      if (wbarg->wa_Name[0] == '\0')
        /* è una directory: ne cerco il nome  */
        NameFromLock(wbarg->wa_Lock,buff,BUFF_SIZE);
      else {
        /* è un file: vado nella sua dir. */
        strcpy(buff,wbarg->wa_Name);
        olddir = CurrentDir(wbarg->wa_Lock);
      }
      /* leggo l'icona */
      dobj = GetDiskObjectNew(buff);
      if (! dobj)
        cleanexit("non trovo l'oggetto\n");
      /* e la riscrivo */
      ret = PutDiskObject(buff,dobj);
      FreeDiskObject(dobj);
      if (! ret)
        cleanexit("non posso scrivere l'icona\n");
      if (olddir != -1) {
        /* se era un file e ho cambiato dir. */
        /* ritorno sulla precedente          */
        CurrentDir(olddir);
        olddir = -1;
      }
    }
    cleanexit(NULL);
  }
}

void cleanexit(UBYTE *s)
{
 if(*s) printf(s);
  if(IconBase)  CloseLibrary(IconBase);
  exit(0);
}
