/** Update the panel state. */
  public void updatePanel() {
    UIMaster master = UIMaster.getInstance();
    MasterMgrClient client = master.acquireMasterMgrClient();
    try {
      pPrivilegeDetails = client.getPrivilegeDetails();
    } catch (PipelineException ex) {
      showErrorDialog(ex);
    } finally {
      master.releaseMasterMgrClient(client);
    }

    updateButtons();
  }
 private void jcheckOut(
     MasterMgrClient mclient,
     String user,
     String view,
     String name,
     VersionID id,
     CheckOutMode mode,
     CheckOutMethod method)
     throws PipelineException {
   if (id == null) id = mclient.getCheckedInVersionIDs(name).last();
   if (id == null) throw new PipelineException("BAD BAD BAD");
   mclient.checkOut(user, view, name, id, mode, method);
 }
  /** @return The path of a node */
  private Path getNodePath(String nodeName) throws PipelineException {

    NodeID targetID = new NodeID(w.user, w.view, nodeName);
    NodeStatus targetStat = mclient.status(targetID);
    NodeMod targetMod = targetStat.getHeavyDetails().getWorkingVersion();
    if (targetMod == null)
      throw new PipelineException(
          "No working version of the Target Scene Node ("
              + nodeName
              + ") exists "
              + "in the ("
              + w.view
              + ") working area owned by ("
              + PackageInfo.sUser
              + ")!");

    Path targetPath;

    FileSeq fseq = targetMod.getPrimarySequence();
    String suffix = fseq.getFilePattern().getSuffix();
    if (!fseq.isSingle() || (suffix == null) || (!suffix.equals("ma") && !suffix.equals("mb")))
      throw new PipelineException("The target node (" + nodeName + ") must be a maya scene!");
    targetPath =
        new Path(PackageInfo.sProdPath, targetID.getWorkingParent() + "/" + fseq.getFile(0));

    // System.err.println("$WORKING"+nodeName+"."+suffix);
    return targetPath;
  } // end getNodePath(String)
    @Override
    public void run() {
      UIMaster master = UIMaster.getInstance();
      if (master.beginPanelOp(pGroupID, "Reverting Files...")) {
        MasterMgrClient client = master.acquireMasterMgrClient();
        try {
          client.revertFiles(pAuthor, pView, pStatus.getName(), pFiles);
        } catch (PipelineException ex) {
          master.showErrorDialog(ex);
          return;
        } finally {
          master.releaseMasterMgrClient(client);
          master.endPanelOp(pGroupID, "Done.");
        }

        updatePanels();
      }
    }
    @Override
    public void run() {
      UIMaster master = UIMaster.getInstance();
      MasterMgrClient client = master.acquireMasterMgrClient();
      try {
        MappedSet<String, VersionID> versions = pArchives.get(pIndex);
        String archiveName = null;
        String msg = ("Archiving Volume (" + (pIndex + 1) + " of " + pArchives.size() + ")...");
        long opID = master.beginDialogOp(msg);
        master.setDialogOpCancelClient(opID, client);
        long monitorID = client.addMonitor(new DialogOpMonitor(opID));
        try {
          archiveName = client.archive(pPrefix, versions, pArchiver, pToolset);
        } catch (PipelineException ex) {
          showErrorDialog(
              "Error:",
              ex.getMessage()
                  + "\n\n"
                  + "Archive operation aborted early without creating "
                  + "("
                  + (pArchives.size() - pIndex)
                  + " of "
                  + pArchives.size()
                  + ") archive "
                  + "volumes!");
          return;
        } finally {
          master.endDialogOp(opID, "Archived.");
          client.removeMonitor(monitorID);
        }

        SwingUtilities.invokeLater(new RemoveTask(versions));

        ManualArchiveConfirmTask task =
            new ManualArchiveConfirmTask(
                pParent, archiveName, pIndex + 1, pPrefix, pArchives, pToolset, pArchiver);
        SwingUtilities.invokeLater(task);
      } finally {
        master.releaseMasterMgrClient(client);
      }
    }
    @Override
    public void run() {
      UIMaster master = UIMaster.getInstance();
      MasterMgrClient client = master.acquireMasterMgrClient();
      long monitorID = -1L;
      try {
        DoubleMap<String, VersionID, Long> data = null;
        long opID = master.beginDialogOp("Calculating File Sizes...");
        master.setDialogOpCancelClient(opID, client);
        monitorID = client.addMonitor(new DialogOpMonitor(opID));
        try {
          data = client.getArchivedSizes(pVersions);
        } catch (PipelineException ex) {
          showErrorDialog(ex);
        } finally {
          master.endDialogOp(opID, "File Sizes Calculated.");
        }

        /* merge existing and new sizes */
        if (data != null) {
          for (String name : pData.keySet()) {
            TreeMap<VersionID, Long> oversions = pData.get(name);
            TreeMap<VersionID, Long> versions = data.get(name);
            if (versions == null) {
              data.put(name, oversions);
            } else {
              for (VersionID vid : oversions.keySet()) {
                if (versions.get(vid) == null) versions.put(vid, oversions.get(vid));
              }
            }
          }

          UpdateSizesTask task = new UpdateSizesTask(data);
          SwingUtilities.invokeLater(task);
        }
      } finally {
        client.removeMonitor(monitorID);
        master.releaseMasterMgrClient(client);
      }
    }
    @Override
    public void run() {
      UIMaster master = UIMaster.getInstance();
      ArrayList<ArchiveInfo> info = null;

      MasterMgrClient client = master.acquireMasterMgrClient();
      long opID = master.beginDialogOp("Searching for Candidate Versions...");
      master.setDialogOpCancelClient(opID, client);
      long monitorID = client.addMonitor(new DialogOpMonitor(opID));
      try {
        info = client.archiveQuery(pPattern, pMaxArchives);
      } catch (PipelineException ex) {
        showErrorDialog(ex);
      } finally {
        master.endDialogOp(opID, "Archive Search Complete.");
        client.removeMonitor(monitorID);
        master.releaseMasterMgrClient(client);
      }

      UpdateTask task = new UpdateTask(info);
      SwingUtilities.invokeLater(task);
    }
    @Override
    public void run() {
      UIMaster master = UIMaster.getInstance();
      MasterMgrClient client = master.acquireMasterMgrClient();
      try {
        DoubleMap<String, VersionID, Long> versionSizes = null;
        {
          long opID = master.beginDialogOp("Assigning Versions to Archives...");
          long monitorID = client.addMonitor(new DialogOpMonitor(opID));
          try {
            versionSizes = client.getArchivedSizes(pVersions);
          } catch (PipelineException ex) {
            showErrorDialog(ex);
          } finally {
            master.endDialogOp(opID, "Versions Assigned.");
            client.removeMonitor(monitorID);
          }
        }

        /* assign the maximum number of versions to each archive volume without
        exceeding its capacity */
        TreeMap<Integer, MappedSet<String, VersionID>> archives =
            new TreeMap<Integer, MappedSet<String, VersionID>>();
        if (versionSizes != null) {
          long capacity = pArchiver.getCapacity();
          int idx = 0;
          long total = 0L;
          boolean done = false;
          DoubleMap<String, VersionID, Long> skippedVersionSizes =
              new DoubleMap<String, VersionID, Long>();
          while (!done) {
            for (String name : versionSizes.keySet()) {
              for (VersionID vid : versionSizes.keySet(name)) {
                Long size = versionSizes.get(name, vid);
                if ((total + size) >= capacity) {
                  /* the version is too big to fit by itself in a volume */
                  if (total == 0L) {
                    showErrorDialog(
                        "Error:",
                        "The version ("
                            + vid
                            + ") of node ("
                            + name
                            + ") was larger than "
                            + "the capacity of an entire archive volume!  The capacity of the "
                            + "archive volume must be increased to at least "
                            + "("
                            + formatLong(size)
                            + ") in order to archive this version.");
                    return;
                  }

                  skippedVersionSizes.put(name, vid, size);
                }

                /* the version fits, add it to this volume */
                else {
                  MappedSet<String, VersionID> versions = archives.get(idx);
                  if (versions == null) {
                    versions = new MappedSet<String, VersionID>();
                    archives.put(idx, versions);
                  }

                  versions.put(name, vid);
                  total += size;
                }
              }
            }

            /* some versions wouldn't fit in the current volume,
            create a new volume and try again... */
            if (!skippedVersionSizes.isEmpty()) {
              idx++;
              total = 0L;
              versionSizes = skippedVersionSizes;
              skippedVersionSizes = new DoubleMap<String, VersionID, Long>();
            } else {
              if (total < pMinSize) {
                if (idx == 0) {
                  showErrorDialog(
                      "Error:",
                      "The total size ("
                          + formatLong(total)
                          + ") of all versions selected "
                          + "for archiving was less than the minimum archive volume size "
                          + "("
                          + formatLong(pMinSize)
                          + ")!  Either select enough versions to "
                          + "meet this minimum size or specify a smaller minimum size to create "
                          + "an archive volume.");
                  return;
                } else {
                  archives.remove(idx);
                }
              }

              break;
            }
          }
        }

        /* perform the archive operations */
        if (!archives.isEmpty()) {
          if (pArchiver.isManual()) {
            ManualArchiveConfirmTask task =
                new ManualArchiveConfirmTask(
                    pParent, null, 0, pPrefix, archives, pToolset, pArchiver);
            SwingUtilities.invokeLater(task);
          } else {
            long opID = master.beginDialogOp();
            master.setDialogOpCancelClient(opID, client);
            long monitorID = client.addMonitor(new DialogOpMonitor(opID));
            int lastIdx = 0;
            try {
              for (Integer idx : archives.keySet()) {
                master.updateDialogOp(
                    opID, "Archiving Volume (" + (idx + 1) + " of " + archives.size() + ")...");
                lastIdx = idx;
                client.archive(pPrefix, archives.get(idx), pArchiver, pToolset);
              }
            } catch (PipelineException ex) {
              showErrorDialog(
                  "Error:",
                  ex.getMessage()
                      + "\n\n"
                      + "Archive operation aborted early without creating "
                      + "("
                      + (archives.size() - lastIdx)
                      + " of "
                      + archives.size()
                      + ") archive "
                      + "volumes!");
              return;
            } finally {
              master.endDialogOp(opID, "Archived.");
              client.removeMonitor(monitorID);
            }

            RemoveAllTask task = new RemoveAllTask();
            SwingUtilities.invokeLater(task);
          } // else
        } // if(!archives.isEmpty()) {
      } finally {
        master.releaseMasterMgrClient(client);
      }
    }
  /**
   * Draws the GUI that allows a user to select assets to be updated.
   *
   * @return true if the user made a valid choice of assets to replace.
   * @throws PipelineException
   */
  private boolean buildUpdateGUI() throws PipelineException {
    Box finalBox = new Box(BoxLayout.Y_AXIS);
    top = new Box(BoxLayout.Y_AXIS);

    JScrollPane scroll;

    {
      scroll = new JScrollPane(finalBox);

      scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

      Dimension size = new Dimension(sVSize + sVSize + sTSize + 52, 500);
      scroll.setMinimumSize(size);
      scroll.setPreferredSize(size);
      scroll.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
    }

    /* query the user */
    diag = new JToolDialog("Propagate Asset", scroll, "Continue");

    areas = mclient.getWorkingAreas();
    {
      Box hbox = new Box(BoxLayout.X_AXIS);
      Component comps[] = UIFactory.createTitledPanels();
      JPanel tpanel = (JPanel) comps[0];
      JPanel vpanel = (JPanel) comps[1];
      {
        userField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "User:"******"The user whose area the node is being created in.");
        userField.setActionCommand("user");
        userField.setSelected(PackageInfo.sUser);
        userField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);
      {
        viewField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "View:",
                sTSize,
                vpanel,
                areas.get(PackageInfo.sUser),
                diag,
                sVSize,
                "The working area to create the nodes in.");
        viewField.setActionCommand("wrap");
        viewField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);
      {
        toolsetField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "Toolset:",
                sTSize,
                vpanel,
                mclient.getActiveToolsetNames(),
                diag,
                sVSize,
                "The toolset to set on all the nodes.");
        toolsetField.setSelected(mclient.getDefaultToolsetName());
        toolsetField.setActionCommand("wrap");
        toolsetField.addActionListener(this);
      }
      UIFactory.addVerticalSpacer(tpanel, vpanel, 3);

      w =
          new Wrapper(
              userField.getSelected(),
              viewField.getSelected(),
              toolsetField.getSelected(),
              mclient);

      charList = SonyConstants.getAssetList(w, project, AssetType.CHARACTER);
      setsList = SonyConstants.getAssetList(w, project, AssetType.SET);
      propsList = SonyConstants.getAssetList(w, project, AssetType.PROP);

      {
        projectField =
            UIFactory.createTitledCollectionField(
                tpanel,
                "Project:",
                sTSize,
                vpanel,
                Globals.getChildrenDirs(w, "/projects"),
                diag,
                sVSize,
                "All the projects in pipeline.");
        projectField.setActionCommand("proj");
        projectField.addActionListener(this);
      }
      hbox.add(comps[2]);
      top.add(hbox);
    }

    {
      Box vbox = new Box(BoxLayout.Y_AXIS);
      Box hbox = new Box(BoxLayout.X_AXIS);
      JButton button = new JButton("Propagate Additional Asset");
      button.setName("ValuePanelButton");
      button.setRolloverEnabled(false);
      button.setFocusable(false);
      Dimension d = new Dimension(sVSize, 25);
      button.setPreferredSize(d);
      button.setMinimumSize(d);
      button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 25));

      vbox.add(Box.createRigidArea(new Dimension(0, 5)));
      hbox.add(button);
      hbox.add(Box.createRigidArea(new Dimension(4, 0)));
      vbox.add(hbox);
      vbox.add(Box.createRigidArea(new Dimension(0, 5)));

      button.setActionCommand("add");
      button.addActionListener(this);

      top.add(vbox);
    }

    list = new Box(BoxLayout.Y_AXIS);
    test = new JDrawer("Propagate Additional Asset", list, false);

    top.add(test);
    list.add(assetChoiceBox());

    finalBox.add(top);

    {
      JPanel spanel = new JPanel();
      spanel.setName("Spacer");
      spanel.setMinimumSize(new Dimension(sTSize + sVSize, 7));
      spanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
      spanel.setPreferredSize(new Dimension(sTSize + sVSize, 7));
      finalBox.add(spanel);
    }

    diag.setVisible(true);
    if (diag.wasConfirmed()) {
      // get list of things to change.
      for (Component comp : list.getComponents()) {
        if (comp instanceof Box) {
          Box can = (Box) comp;
          JCollectionField oldOne = (JCollectionField) can.getComponent(2);
          JCollectionField newOne = (JCollectionField) can.getComponent(4);

          TreeMap<String, String> assetList = new TreeMap<String, String>();
          assetList.putAll(charList);
          assetList.putAll(propsList);
          assetList.putAll(setsList);

          String key = assetList.get(oldOne.getSelected()) + lr;
          String value = assetList.get(newOne.getSelected()) + lr;
          if (!key.equals(value)) {
            potentialUpdates.add(key);
            pAssetManager.put(key, new AssetInfo(key, value));
          }
          // System.err.println("bUG: "+pAssetManager.get(key).getHiLoResShots());
        }
      }

      if (!pAssetManager.isEmpty()) return true;
    }
    return false;
  } // end buildReplacementGUI
  /**
   * Get list of each asset to be replaced, and the shots it's in.
   *
   * @return
   * @throws PipelineException
   */
  private boolean getShotsUsingAssets() throws PipelineException {
    ArrayList<ArchiveInfo> archive = mclient.archiveQuery(shotPattern, null);

    logLine("Looking for shots using lo-res assets.");
    for (ArchiveInfo curArc : archive) {
      String name = curArc.getName();
      VersionID vid = curArc.getVersionID();
      TreeSet<VersionID> allVers = mclient.getCheckedInVersionIDs(name);
      if (!vid.equals(allVers.last())) continue;

      NodeVersion ver = mclient.getCheckedInVersion(name, vid);
      Set<String> srcs = ver.getSourceNames();

      for (String loResAsset : pAssetManager.keySet()) {
        if (srcs.contains(loResAsset)) {
          // TODO chec if latest.

          logLine("\t" + getShortName(loResAsset) + ": " + getShortName(name));

          AssetInfo tempInfo = pAssetManager.get(loResAsset);

          if (!tempInfo.getLoHiResShots().containsKey(name))
            tempInfo.getLoHiResShots().put(name, null);
        } // end if
      } // end for
    } // end for

    logLine("Looking for shots using hi-res assets");
    /* - Populate lo-res */
    for (ArchiveInfo curArc : archive) {
      String name = curArc.getName();
      VersionID vid = curArc.getVersionID();
      TreeSet<VersionID> allVers = mclient.getCheckedInVersionIDs(name);
      if (!vid.equals(allVers.last())) continue;

      NodeVersion ver = mclient.getCheckedInVersion(name, vid);
      Set<String> srcs = ver.getSourceNames();

      for (String updateAsset : pAssetManager.keySet()) {
        String hiResAsset = updateAsset.replace(lr, "");
        if (srcs.contains(hiResAsset)) {
          logLine("\t" + getShortName(hiResAsset) + ": " + getShortName(name));
          AssetInfo tempInfo = pAssetManager.get(updateAsset);

          String loRes = tempInfo.getMatchingLoResShot(name);
          if (loRes == null) {
            logLine(
                "!!!\nWARNING:"
                    + getShortName(hiResAsset)
                    + " is used in the "
                    + getShortName(name)
                    + " node which has no matching lo-res model in an anim node."
                    + " So it will not be changed\n!!!");
            continue;
          }

          tempInfo.getLoHiResShots().put(loRes, name);
        } // end if
      } // end for
    } // end for(ArchiveInfo)

    logLine("");

    for (String updateAsset : potentialUpdates) {
      TreeMap<String, String> shots = pAssetManager.get(updateAsset).getLoHiResShots();
      if (shots.isEmpty()) {
        logLine(getShortName(updateAsset) + " is not used in any shots");
        pAssetManager.remove(updateAsset);
      }
      for (String loRes : shots.keySet()) {
        if (shots.get(loRes) == null)
          logLine(
              getShortName(updateAsset)
                  + " is in a hi-res shot, "
                  + getShortName(loRes)
                  + ", but doesn't have a matching hi-res"
                  + "model in the lgt node.");
      }
    }

    if (pAssetManager.isEmpty()) return false;

    return true;
  } // end getShotsUsingAssets
  /**
   * Updates the asset references for a shot within Maya and then in pipeline.
   *
   * @param shotName The name of the shot being processed.
   * @param pRemoveRef The list of assets being dereferenced from the shot.
   * @param pReplaceRef The list of assets being referenced into the shot.
   * @param nameMap
   */
  private void editShotReferences(
      String shotName,
      NodeMod targetMod,
      TreeSet<String> pRemoveRef,
      TreeSet<String> pReplaceRef,
      TreeMap<String, String> nameMap)
      throws PipelineException {
    logLine("Editing shot: " + shotName);
    boolean anim = !shotName.matches(lgtPattern);

    /* writing the mel script */
    if (anim) {
      File script = null;
      try {
        script = File.createTempFile("UpdateAssetGUI.", ".mel", PackageInfo.sTempPath.toFile());
        FileCleaner.add(script);
      } // end try
      catch (IOException ex) {
        throw new PipelineException(
            "Unable to create the temporary MEL script used to collect "
                + "texture information from the Maya scene!");
      } // end catch

      try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(script)));

        for (String asset : pReplaceRef) {
          String nameSpace;
          if (asset.endsWith(lr))
            nameSpace = nameMap.get(getShortName(asset.substring(0, asset.length() - 3)));
          else {
            System.err.println("This should not be happening, a hi res asset in a lo-res node.");
            continue;
            // nameSpace = nameMap.get(getShortName(asset));
          }
          out.println("print (\"referencing file: $WORKING" + asset + ".ma\");");
          out.println(
              "file -reference -namespace \"" + nameSpace + "\" \"$WORKING" + asset + ".ma\";");
        } // end for

        for (String asset : pRemoveRef) {
          out.println("print (\"dereferencing file: $WORKING" + asset + ".ma\");");
          out.println("file -rr \"$WORKING" + asset + ".ma\";");
        } // end for

        out.println("// SAVE");
        out.println("file -save;");

        out.close();
      } // end try
      catch (IOException ex) {
        throw new PipelineException(
            "Unable to write the temporary MEL script(" + script + ") used add the references!");
      } // end catch

      NodeID targetID = new NodeID(w.user, w.view, shotName);
      // NodeStatus targetStat = mclient.status(targetID);

      /* run Maya to collect the information */
      try {

        Path targetPath = getNodePath(shotName);
        ArrayList<String> args = new ArrayList<String>();
        args.add("-batch");
        args.add("-script");
        args.add(script.getPath());
        args.add("-file");
        args.add(targetPath.toOsString());

        Path wdir = new Path(PackageInfo.sProdPath.toOsString() + targetID.getWorkingParent());

        TreeMap<String, String> env =
            mclient.getToolsetEnvironment(
                w.user, w.view, targetMod.getToolset(), PackageInfo.sOsType);

        Map<String, String> nenv = env;
        String midefs = env.get("PIPELINE_MI_SHADER_PATH");
        if (midefs != null) {
          nenv = new TreeMap<String, String>(env);
          Path dpath = new Path(new Path(wdir, midefs));
          nenv.put("MI_CUSTOM_SHADER_PATH", dpath.toOsString());
        }

        String command = "maya";
        if (PackageInfo.sOsType.equals(OsType.Windows)) command += ".exe";

        SubProcessLight proc =
            new SubProcessLight("UpdateAssetGUI", command, args, env, wdir.toFile());
        try {
          proc.start();
          proc.join();
          if (!proc.wasSuccessful()) {
            throw new PipelineException(
                "Did not correctly edit the reference due to a maya error.!\n\n"
                    + proc.getStdOut()
                    + "\n\n"
                    + proc.getStdErr());
          } // end if
        } // end try
        catch (InterruptedException ex) {
          throw new PipelineException(ex);
        } // end catch
      } // end try
      catch (Exception ex) {
        throw new PipelineException(ex);
      } // end catch
    }

    /*-edit the references in pipeline once they are done in the file-*/
    BaseAction targetAction = targetMod.getAction();
    for (String asset : pReplaceRef) {
      mclient.link(
          w.user, w.view, shotName, asset, LinkPolicy.Reference, LinkRelationship.All, null);
      if (anim) {
        /*Set the namespaces*/
        String nameSpace = nameMap.get(getShortName(asset.substring(0, asset.length() - 3)));
        System.err.println(nameSpace);
        targetAction.initSourceParams(asset);
        targetAction.setSourceParamValue(asset, "PrefixName", nameSpace);
        targetMod.setAction(targetAction);
      }
    }
    w.mclient.modifyProperties(w.user, w.view, targetMod);

    for (String asset : pRemoveRef) mclient.unlink(w.user, w.view, shotName, asset);

    if (!anim) {
      System.err.println("Queuing the switchLgt node " + shotName);
      mclient.submitJobs(w.user, w.view, shotName, null);
    }
  } // end editShotReferences
  /**
   * Using a list of shots and the assets to be changed per shot, gets each shot node and modifies
   * the references as needed.
   */
  private void processNodes() throws PipelineException {
    /*each asset, its replacement and the lo-res versions*/
    for (String asset : pAssetManager.keySet()) {
      String newAsset = pAssetManager.get(asset).getNewAsset();
      String hrAsset = asset.replace(lr, "");
      String newHrAsset = newAsset.replace(lr, "");
      logLine(
          "Checking out nodes:\n\t"
              + asset
              + "\n\t"
              + hrAsset
              + "\n\t"
              + newAsset
              + "\n\t"
              + newHrAsset);

      mclient.checkOut(w.user, w.view, asset, null, over, froz);
      mclient.checkOut(w.user, w.view, newAsset, null, over, froz);
      mclient.checkOut(w.user, w.view, hrAsset, null, over, froz);
      mclient.checkOut(w.user, w.view, newHrAsset, null, over, froz);
    } // end for

    TreeMap<String, TreeSet<String>> shotBased = convertListToShotBased();
    TreeMap<String, String> nameMap = SonyConstants.getCustomNamespaces(project);
    TreeSet<String> oldRef = new TreeSet<String>();
    TreeSet<String> newRef = new TreeSet<String>();

    for (String shot : shotBased.keySet()) {
      // check out the shot

      if (shot.endsWith("anim")) mclient.checkOut(w.user, w.view, shot, null, keep, frozU);
      else {
        continue;
        // mclient.checkOut(w.user, w.view, shot, null, keep, pFroz);
      }
      logLine("Checking out: " + shot);

      NodeMod targetMod = mclient.getWorkingVersion(w.user, w.view, shot);
      if (!shot.matches(lgtPattern)) {

        if (targetMod.isActionEnabled()) {
          System.err.println("Anim node with action enabled");
          FileSeq fseq = targetMod.getPrimarySequence();
          VersionID targetID = targetMod.getWorkingID();
          TreeMap<String, VersionID> files = new TreeMap<String, VersionID>();
          files.put(fseq.getFile(0).getPath(), targetID);
          mclient.revertFiles(w.user, w.view, shot, files);
          targetMod.setActionEnabled(false);
        }

        w.mclient.modifyProperties(w.user, w.view, targetMod);
      }

      /*--checking the shot to be modified---*/

      for (String assetToReplace : shotBased.get(shot)) {
        if (assetToReplace.endsWith(lr)) {
          AssetInfo temp = pAssetManager.get(assetToReplace);
          oldRef.add(assetToReplace);
          newRef.add(temp.getNewAsset());
        } else {
          String hiRes = assetToReplace.replace(lr, "");
          AssetInfo temp = pAssetManager.get(hiRes);
          if (temp == null) continue;
          oldRef.add(assetToReplace);
          newRef.add(temp.getNewAsset() + lr);
        } // end else
      } // end for

      if (oldRef.isEmpty() || newRef.isEmpty()) {
        logLine("Shot " + shot + " somehow does not need any changes.");
        continue;
      } // end if

      editShotReferences(shot, targetMod, oldRef, newRef, nameMap);
    } // end for

    /*for(String shot: shotBased.keySet()){
    	//TODO: Check in nodes
    	String msg = "Checked in with UpdateAssetGUI. Removed:\n\t";
    	for(String asset: oldRef)
    		msg+= (asset + " ");

    	msg+="\nAdded:\n\t";
    	for(String asset: newRef)
    		msg+= (asset + " ");

    	mclient.checkIn(w.user, w.view,shot, msg, VersionID.Level.Major);
    }*/

  } // end processShots
  /**
   * Perform execution of the tool.
   *
   * <p>
   *
   * @param mclient The network connection to the plmaster(1) daemon.
   * @param qclient The network connection to the plqueuemgr(1) daemon.
   * @return Whether to continue and collect user input for the next phase of the tool.
   * @throws PipelineException If unable to sucessfully execute this phase of the tool.
   */
  public synchronized boolean executePhase(MasterMgrClient mclient, QueueMgrClient qclient)
      throws PipelineException {
    boolean newCheckOut = false;
    String matName = null;
    String texName = null;

    {
      /*find out if it is a fresh checkout*/
      JToolDialog tool = new JToolDialog("MaterialsCheckOut", new JPanel(), "Continue");
      JConfirmDialog dialog = new JConfirmDialog(tool, "Do you want a completely fresh checkout");
      dialog.setVisible(true);
      newCheckOut = dialog.wasConfirmed();
    }

    {
      /*-check out the asset and mat nodes-*/
      jcheckOut(mclient, pUser, pView, pPrimary, null, keep, pFroz);
      NodeMod assetMod = mclient.getWorkingVersion(pUser, pView, pPrimary);
      {
        JobReqs jreqs = assetMod.getJobRequirements();
        jreqs.addSelectionKey("LinuxOnly");
        assetMod.setJobRequirements(jreqs);
        mclient.modifyProperties(pUser, pView, assetMod);
      }

      Set<String> assetSrcs = assetMod.getSourceNames();
      err.println("The asset sources are: ");

      for (String src : assetSrcs) {
        err.println(src);

        if (src.matches(matPattern)) {
          matName = src;
          err.println("Found mat node:\n\t " + src);
          if (newCheckOut) {
            err.println("Clean mat checkout");
            jcheckOut(mclient, pUser, pView, src, null, over, frozU);
          } else {

            OverallNodeState state =
                mclient.status(pUser, pView, src).getHeavyDetails().getOverallNodeState();

            if (!state.equals(OverallNodeState.Modified)) {
              err.println("Mat node has not been modified");
              jcheckOut(mclient, pUser, pView, src, null, keep, pFroz);
            }
          }
        } else if (src.matches(matPattern + "Exp")) {
          err.println("Matexp is:\n\t" + src);
          jcheckOut(mclient, pUser, pView, src, null, keep, modi);
          {
            NodeMod expMod = mclient.getWorkingVersion(pUser, pView, src);
            JobReqs jreqs = expMod.getJobRequirements();
            jreqs.addSelectionKey("LinuxOnly");
            expMod.setJobRequirements(jreqs);
            mclient.modifyProperties(pUser, pView, expMod);
          }
        } else {
          jcheckOut(mclient, pUser, pView, src, null, over, froz);
        }
      } // end for
      err.println("mat node: " + matName);
      if (matName == null)
        throw new PipelineException("This asset node does not have an " + "attached mat node");
    }

    {
      /*find the texture node and check out so it can be changed. If new checkout, fresh textures*/
      NodeMod matMod = mclient.getWorkingVersion(pUser, pView, matName);
      TreeSet<String> matSrcs = new TreeSet<String>(matMod.getSourceNames());
      for (String src : matSrcs) {
        if (src.matches(texPattern)) {
          texName = src;
          err.println("Found tex node:\n\t " + src);
          if (newCheckOut) {
            err.println("Clean");
            jcheckOut(mclient, pUser, pView, src, null, over, frozU);
          } else {
            err.println("Old stuff");
            jcheckOut(mclient, pUser, pView, src, null, keep, pFroz);
            jcheckOut(mclient, pUser, pView, src, null, keep, modi);
          }
          continue;
        } // end if
        jcheckOut(mclient, pUser, pView, src, null, over, froz);
      } // end for
      err.println("tex node: " + texName);
      if (texName == null)
        throw new PipelineException(
            "This asset node does not have an associated " + "texture node");
    }

    err.println("Checked out the asset, mat and texture nodes");

    {
      /*check out finalise scripts*/
      jcheckOut(
          mclient,
          pUser,
          pView,
          "/projects/lr/assets/tools/mel/finalize-character",
          null,
          over,
          froz);
      jcheckOut(
          mclient, pUser, pView, "/projects/lr/assets/tools/mel/finalize-set", null, over, froz);
      jcheckOut(
          mclient, pUser, pView, "/projects/lr/assets/tools/mel/finalize-prop", null, over, froz);
    }

    err.close();

    return false;
  } // end executePhase
  @Override
  public void run(String[] args) {
    try {
      TreeMap<String, LinkedList<String>> parsedArgs = argParser(args);
      if (!checkArgsAndSetParams(parsedArgs)) {
        return;
      }
    } catch (PipelineException ex) {
      System.err.println("There was a problem reading the arguments.\n" + ex.getMessage());
      printHelp();
      return;
    }

    for (String turntableName : turntables) {
      logLine("Doing turntable: " + turntableName);
      for (String passName : passes) {
        logLine("\tDoing pass: "******"\t\tDoing asset: " + as.assetName);
            LairTurntable tt = new LairTurntable(as, turntableName, passName);
            w = new Wrapper(user, view, toolset, client);

            logLine("\t\tFreezing all the textures");
            getLatest(w, as.texGroup, over, froz);

            logLine("\t\tChecking out the final model scene");
            getNewest(w, as.finalScene, keep, pFroz);
            getNewest(w, as.lr_finalScene, keep, pFroz);

            logLine("\t\tChecking out the shader scene.");
            getNewest(w, as.shdScene, keep, pFroz);

            logLine("\t\tChecking out the turntable scene.");
            getNewest(w, tt.turntableScene, keep, pFroz);

            logLine("\t\tChecking out the overRide scene.");
            getNewest(w, tt.ttCamOverMI, keep, pFroz);

            logLine("\t\tChecking out the options scene.");
            getNewest(w, tt.ttOptionsMI, keep, pFroz);

            logLine("\t\tChecking out the camera MI node.");
            getNewest(w, tt.ttCamMI, keep, pFroz);

            logLine("\t\tChecking out the light MI node.");
            getNewest(w, tt.ttLightMI, keep, pFroz);

            logLine("\t\tChecking out the shade MI node.");
            getNewest(w, tt.ttShadeMI, keep, pFroz);

            logLine("\t\tChecking out the geo MI node.");
            getNewest(w, tt.ttGeoMI, keep, pFroz);

            logLine("\t\tChecking out the images node.");
            getNewest(w, tt.ttImages, keep, pFroz);

            logLine("\t\tFixing the turntable node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.turntableScene);
              if (toolset != null) mod.setToolset(toolset);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the camera override node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttCamOverMI);
              if (toolset != null) mod.setToolset(toolset);
              BaseAction act = mod.getAction();
              act.setSingleParamValue("ImageWidth", 1280);
              act.setSingleParamValue("ImageHeight", 720);
              act.setSingleParamValue("AspectRatio", 1.777);
              act.setSingleParamValue("Aperture", 1.41732);
              act.setSingleParamValue("OverrideFocal", false);
              act.setSingleParamValue("OverrideClipping", false);
              mod.setAction(act);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the camera node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttCamMI);
              if (toolset != null) mod.setToolset(toolset);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the light node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttLightMI);
              if (toolset != null) mod.setToolset(toolset);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the geo node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttGeoMI);
              if (toolset != null) mod.setToolset(toolset);
              BaseAction act = mod.getAction();
              act.setSingleParamValue("CustomText", true);
              mod.setAction(act);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the shader node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttShadeMI);
              if (toolset != null) mod.setToolset(toolset);
              BaseAction act = mod.getAction();
              BaseAction act2 = LairConstants.actionMayaMiShader();
              act2.setSingleParamValues(act);
              mod.setAction(act2);
              JobReqs req = mod.getJobRequirements();
              req.addSelectionKey("MentalRay");
              mod.setJobRequirements(req);
              mod.setExecutionMethod(ExecutionMethod.Parallel);
              mod.setBatchSize(100);
              client.modifyProperties(user, view, mod);
            }

            logLine("\t\tFixing the images node");
            {
              NodeMod mod = client.getWorkingVersion(user, view, tt.ttImages);
              if (toolset != null) mod.setToolset(toolset);
              BaseAction act = mod.getAction();
              act.setSingleParamValue("TexturePath", "$WORKING");
              mod.setAction(act);
              JobReqs req = mod.getJobRequirements();
              req.addSelectionKey("MentalRay");
              mod.setJobRequirements(req);
              mod.setExecutionMethod(ExecutionMethod.Parallel);
              mod.setBatchSize(5);
              client.modifyProperties(user, view, mod);
            }

            logLine(
                "All Done.  Remember to set your export set on the mod node "
                    + "if you want to export a custom part of the body");
          } catch (PipelineException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
    }
  }