#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/execbase.h>
#include <clib/exec_protos.h>

#include <stdio.h>

#include "global.h"
#include "break.h"
#include "libinfo.h"
#include "output.h"
#include "list.h"

extern struct ExecBase *SysBase;

/*
** List the specified library
*/
void ListLib(STRPTR LibName)
{
  /* Well, at least we don't have to flush the bloody thing... */
  struct Library *Library;
  struct LibInfo *LibInfoItem = NULL;
  
  Forbid();  /* Yeah, boring old system hoggery */
  
  Library = (struct Library *)FindName(&SysBase->LibList,LibName);
  if (Library)
  {
    /* Found ya! */
    LibInfoItem = AddLibInfoItem(NULL,Library);  /* Save the relevent info */
  }
      
  Permit();
  
  if (Library)
  {
    /* Library exists, so must the LibInfoItem... */
    if (LibInfoItem)
    {
      OutputLibInfo(LibInfoItem);
      FreeVec((APTR)LibInfoItem);
    }
    
    /* And if it doesn't, our friend the memory error is here */
    else
    {
      fputs("Error: Not enough memory.\n",stderr);
      clean_exit(20);
    }
  }
  else
    /* The library was not present in memory */
    OutputLibNotFound(LibName);
}
    
/*
** List all libraries in memory
*/
void ListLibs(void)
{
  /* Finally, the LAST ONE!!! */
  struct List *LibInfoList;
  struct LibInfo *LibInfoItem;
  
  /* Cool, Deep Purple J-File */
  
  LibInfoList = BuildLibInfoList();
  
  if (!LibInfoList)
  {
    /* This can't happen.  Must be a memory problem... */
    /* (woa, Deja Vu!) */
    fputs("Error: No more memory.\n",stderr);
    clean_exit(20);
  }

  OutputLibInfoHeader();
  LibInfoItem = (struct LibInfo *)LibInfoList->lh_Head;  
  while (LibInfoItem->li_Node.ln_Succ)
  {
    OutputLibInfo(LibInfoItem);
    LibInfoItem = (struct LibInfo *)LibInfoItem->li_Node.ln_Succ;
    if (CTRL_C)
    {
      fputs(BREAK_TXT,stderr);
      break;
    }
  }
  
  KillLibInfoList(LibInfoList);
}
