#include "MP.h"
#include "patchdata.h"

//#define DEBUG
#include <debug.h>
//#define ADD_DEBUG_CODE

extern BOOL   V39;
extern struct MPSem *MPSem;


void PreCloseOpenNode(struct OpenNode *on)
{
  if(V39)
  {
    LONG l;
    struct ColorMap *cm;
    
    cm=on->Screen->ViewPort.ColorMap;
    
    for(l=0;l<MAX_ONPENS;l++)
    {
     
      if(on->ObtainedPens[l])
      {
        ReleasePen(cm,l);
      }
    }
  }
}

void FreeOpenNode(struct OpenNode *on)
{
#ifdef ADD_DEBUG_CODE  
  if(MPSem->Debug)
  {
    KP("--------------------------------\nFreeOpenNode(%8lx)\n",on);
  }
#endif
  if(on) 
  { 
    /* All these are safe to call with NULL */
    FreeVec(on->TA.tta_Name);
    FreeVec(on->TA.tta_Tags);
    DeleteCxObjAll(on->Cx);
    FreeVec(on->HotKey);
    FreeVec(on->ScreenTitle);
    if(V39)
    {
      //LONG l; // 4.55 @2 Comment out
      FreeBitMap(on->BitMap);
     
     // Commented out in 4.50 duplicate from above
     /*
      for(l=0;l<MAX_ONPENS;l++)
      {
        struct ColorMap *cm;
      
        cm=on->Screen->ViewPort.ColorMap;

        if(on->ObtainedPens[l])
        {
          ReleasePen(cm,l);
        }
      }
      */
    }
    
    FreeDNode(on->DN);
    FreeVec(on);

#ifdef ADD_DEBUG_CODE  
    if(MPSem->Debug)
    {
      KP("  Freed\n");
    }
#endif
  }
}

void FreeWBOpenNode(void)
{
  struct OpenNode *on;

#ifdef ADD_DEBUG_CODE  
  if(MPSem->Debug)
  {
    KP("--------------------------------\nFreeWBOpenNode()\n");
  }
#endif

  on=(struct OpenNode *)MPSem->OpenList.lh_Head;
  while(on->on_Node.ln_Succ)
  {
    if((on->Flags & ON_WORKBENCH))
    {
      Remove((struct Node *)on);
      FreeOpenNode(on);
      return;
    }
    on=(struct OpenNode *)on->on_Node.ln_Succ;
  }
#ifdef ADD_DEBUG_CODE  
  if(MPSem->Debug)
  {
    KP("  Not Freed\n");
  }
#endif
}


void PreCloseWBOpenNode(void)
{
  struct OpenNode *on;

  on=(struct OpenNode *)MPSem->OpenList.lh_Head;
  while(on->on_Node.ln_Succ)
  {
    if((on->Flags & ON_WORKBENCH))
    {
      PreCloseOpenNode(on);
      return;
    }
    on=(struct OpenNode *)on->on_Node.ln_Succ;
  }
}

// 4.53 @2
// NOTE: doesn't obtain sem
struct OpenNode *FindOpenNode(struct Screen *Scr)
{
  struct OpenNode *on;
  
  on=(struct OpenNode *)MPSem->OpenList.lh_Head;
  while(on->on_Node.ln_Succ)
  {
    if(on->Screen==Scr)
    {
      return(on);
    }
    on=(struct OpenNode *)on->on_Node.ln_Succ;
  }

  return(0);
}
