Index: trunk/src/org/expeditee/gui/FrameUtils.java
===================================================================
--- trunk/src/org/expeditee/gui/FrameUtils.java	(revision 1407)
+++ trunk/src/org/expeditee/gui/FrameUtils.java	(revision 1415)
@@ -60,4 +60,5 @@
 import org.expeditee.core.bounds.AxisAlignedBoxBounds;
 import org.expeditee.core.bounds.PolygonBounds;
+import org.expeditee.encryption.items.surrogates.Label;
 import org.expeditee.gio.EcosystemManager;
 import org.expeditee.gio.gesture.StandardGestureActions;
@@ -384,5 +385,5 @@
 		}
 
-		for (Item i : current.getItems()) {
+		for (Item i : current.getSortedItems()) {
 			i.setHighlightMode(Item.HighlightMode.None);
 			i.setHighlightColorToDefault();
@@ -642,5 +643,5 @@
 	 * @return True if the image was created successfully, false otherwise
 	 */
-	private static boolean createPicture(Frame frame, Text txt) {
+	private static boolean createPicture(Frame frame, Text txt, ItemsList items) {
 		// attempt to create the picture
 		Picture pic = ItemUtils.CreatePicture(txt);
@@ -659,7 +660,11 @@
 			return false;
 		}
-		frame.addItem(pic);
+		frame.addItem(pic, true, items);
 
 		return true;
+	}
+	
+	private static boolean createPictureInBody(Frame frame, Text txt) {
+		return createPicture(frame, txt, frame.getBody());
 	}
 
@@ -678,5 +683,5 @@
 	 * @author Brook Novak
 	 */
-	private static boolean createWidget(Frame frame, Text txt) {
+	private static boolean createWidget(Frame frame, Text txt, ItemsList list) {
 
 		if (frame == null) {
@@ -713,9 +718,13 @@
 		}
 
-		frame.removeItem(txt);
-
-		frame.addAllItems(iw.getItems());
+		frame.removeItem(txt, true, list);
+
+		frame.addAllItems(iw.getItems(), list);
 
 		return true;
+	}
+	
+	private static boolean createWidgetInBody(Frame frame, Text txt) {
+		return createWidget(frame, txt, frame.getBody());
 	}
 
@@ -857,40 +866,9 @@
 		return dirsToAdd;
 	}
-
-	public static void Parse(Frame toParse) {
-		Parse(toParse, false);
-	}
-
-	/**
-	 * Checks for any special Annotation items and updates the display as necessary.
-	 * Special Items: Images, overlays, sort.
-	 * 
-	 */
-	public static void Parse(Frame toParse, boolean firstParse) {
-		Parse(toParse, firstParse, false);
-	}
-
-	/**
-	 * 
-	 * @param toParse
-	 * @param firstParse
-	 * @param ignoreAnnotations
-	 *            used to prevent infinate loops such as when performing TDFC with
-	 *            an ao tag linked to a frame with an frameImage of a frame which
-	 *            also has an ao tag on it.
-	 */
-	public static void Parse(Frame toParse, boolean firstParse, boolean ignoreAnnotations) {
-		// TODO check why we are getting toParse == null... when profile frame
-		// is being created and change the lines below
-		if (toParse == null) {
-			return;
-		}
-
-		if (firstParse) {
-			ItemUtils.EnclosedCheck(toParse.getItems());
-		}
-
-		List<Item> items = toParse.getItems();
-
+	
+	private static void transformOutOfPlaceItems(Frame toParse, ItemsList toTransform) {
+		// Get all items from toTransform that have not been marked as deleted.
+		List<Item> items = toParse.getItems(false, toTransform);
+		
 		// if XRayMode is on, replace pictures with their underlying text
 		if (DisplayController.isXRayMode()) {
@@ -901,5 +879,5 @@
 			for (Item i : items) {
 				if (i instanceof XRayable) {
-					toParse.removeItem(i);
+					toParse.removeItem(i, true, toTransform);
 					// Show the items
 					for (Item item : ((XRayable) i).getConnected()) {
@@ -908,7 +886,7 @@
 					}
 				} else if (i instanceof WidgetCorner) {
-					toParse.removeItem(i);
+					toParse.removeItem(i, true, toTransform);
 				} else if (i instanceof WidgetEdge) {
-					toParse.removeItem(i);
+					toParse.removeItem(i, true, toTransform);
 				} else if (i.hasFormula()) {
 					i.setText(i.getFormula());
@@ -920,13 +898,8 @@
 
 			for (Widget iw : widgets) {
-				toParse.addItem(iw.getSource());
-			}
-		}
-
-		// Text title = null;
-		// Text template = UserSettingsTemplate.copy();
-
-		List<Overlay> overlays = new ArrayList<Overlay>();
-		List<Vector> vectors = new ArrayList<Vector>();
+				toParse.addItem(iw.getSource(), true, toTransform);
+			}
+		}
+
 
 		// disable reading of cached overlays if in twinframes mode
@@ -935,16 +908,10 @@
 		}
 
-		// DotType pointtype = DotType.square;
-		// boolean filledPoints = true;
-
-		UserAppliedPermission permission = toParse.getUserAppliedPermission();
 		toParse.clearAnnotations();
 
 		// check for any new overlay items
-		for (Item i : toParse.getItems()) {
+		items = toParse.getItems(false, toTransform);
+		for (Item i : items) {
 			try {
-				// reset overlay permission
-				i.setOverlayPermission(null);
-				// i.setPermission(permission);
 				if (i instanceof WidgetCorner) {
 					// TODO improve efficiency so it only updates once... using
@@ -952,29 +919,105 @@
 					i.update();
 				} else if (i instanceof Text) {
+					if (!DisplayController.isXRayMode() && i.isAnnotation()) {
+						if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IMAGE, true)) {
+							if (!i.hasEnclosures()) {
+								createPicture(toParse, (Text) i, toTransform);
+							}
+							// check for frame images
+						} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_FRAME_IMAGE) && i.getLink() != null
+								&& !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
+							XRayable image = null;
+							if (i.hasEnclosures()) {
+								// i.setHidden(true);
+								// image =
+								// i.getEnclosures().iterator().next();
+								// image.refresh();
+							} else {
+								image = new FrameImage((Text) i, null);
+							}
+							// TODO Add the image when creating new
+							// FrameImage
+							toParse.addItem(image, true, toTransform);
+						} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_BITMAP_IMAGE) && i.getLink() != null
+								&& !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
+							XRayable image = null;
+							if (i.hasEnclosures()) {
+								// image =
+								// i.getEnclosures().iterator().next();
+								// image.refresh();
+								// i.setHidden(true);
+							} else {
+								// If a new bitmap is created for a
+								// frame which already has a bitmap dont
+								// recreate the bitmap
+								image = new FrameBitmap((Text) i, null);
+							}
+							toParse.addItem(image, true, toTransform);
+						} else if (ItemUtils.startsWithTag(i, "@c")) {
+							// Can only have a @c
+							if (!i.hasEnclosures() && i.getLines().size() == 1) {
+								Circle circle = new Circle((Text) i);
+								toParse.addItem(circle, true, toTransform);
+							}
+							// Check for JSItem
+						} else if (ItemUtils.startsWithTag(i, "@js")) {
+							JSItem jsItem = new JSItem((Text) i);
+							toParse.addItem(jsItem, true, toTransform);
+							// Check for interactive widgets
+						} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IWIDGET)) {
+							createWidget(toParse, (Text) i, toTransform);
+						}
+
+						// TODO decide exactly what to do here!!
+						toParse.addAnnotation((Text) i);
+					} else if (!DisplayController.isXRayMode() && i.hasFormula()) {
+						i.calculate(i.getFormula());
+					}
+				}
+			} catch (Exception e) {
+				Logger.Log(e);
+				e.printStackTrace();
+				System.err
+						.println("**** Have temporarily supressed MessageBay call, as resulted in infinite recursion");
+				// MessageBay.warningMessage("Exception occured when loading " +
+				// i.getClass().getSimpleName() + "(ID: "
+				// + i.getID() + ") " + e.getMessage() != null ? e.getMessage() : "");
+			}
+		}
+
+		/*
+		 * for (Item i : items) { if (i instanceof Dot) { ((Dot)
+		 * i).setPointType(pointtype); ((Dot) i).useFilledPoints(filledPoints); } }
+		 */
+
+		if (DisplayController.isTwinFramesOn()) {
+			FrameIO.ResumeCache();
+		}
+
+
+	}
+	
+	private static void generatingSupportingItems(Frame toParse, 
+			ItemsList toBuildOff, boolean ignoreAnnotations) {
+		// Get all items from toBuildOff that have not been marked as deleted.
+		List<Item> items = toParse.getItems(false, toBuildOff);
+
+		List<Overlay> overlays = new ArrayList<Overlay>();
+		List<Vector> vectors = new ArrayList<Vector>();
+
+		// disable reading of cached overlays if in twinframes mode
+		if (DisplayController.isTwinFramesOn()) {
+			FrameIO.SuspendCache();
+		}
+
+		UserAppliedPermission permission = toParse.getUserAppliedPermission();
+		// check for any new overlay items
+		for (Item i : items) {
+			try {
+				// reset overlay permission
+				i.setOverlayPermission(null);
+				if (i instanceof Text) {
 					if (i.isAnnotation()) {
-						if (ItemUtils.startsWithTag(i, ItemUtils.TAG_POINTTYPE)) {
-							Text txt = (Text) i;
-							String line = txt.getFirstLine();
-							line = ItemUtils.StripTag(line, ItemUtils.GetTag(ItemUtils.TAG_POINTTYPE));
-
-							if (line != null) {
-								line = line.toLowerCase();
-								if (line.indexOf(" ") > 0) {
-									String fill = line.substring(line.indexOf(" ") + 1);
-									if (fill.startsWith("nofill")) {
-										// filledPoints = false;
-									} else {
-										// filledPoints = true;
-									}
-								}
-
-								if (line.startsWith("circle")) {
-									// pointtype = DotType.circle;
-								} else {
-									// pointtype = DotType.square;
-								}
-							}
-						} // check for new VECTOR items
-						else if (!DisplayController.isXRayMode() && ItemUtils.startsWithTag(i, ItemUtils.TAG_VECTOR)
+						if (!DisplayController.isXRayMode() && ItemUtils.startsWithTag(i, ItemUtils.TAG_VECTOR)
 								&& i.getLink() != null) {
 							if (!i.getAbsoluteLink().equals(toParse.getName())) {
@@ -1047,59 +1090,5 @@
 							}
 						}
-						// check for Images and widgets
-						else {
-							if (!DisplayController.isXRayMode()) {
-								if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IMAGE, true)) {
-									if (!i.hasEnclosures()) {
-										createPicture(toParse, (Text) i);
-									}
-									// check for frame images
-								} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_FRAME_IMAGE) && i.getLink() != null
-										&& !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
-									XRayable image = null;
-									if (i.hasEnclosures()) {
-										// i.setHidden(true);
-										// image =
-										// i.getEnclosures().iterator().next();
-										// image.refresh();
-									} else {
-										image = new FrameImage((Text) i, null);
-									}
-									// TODO Add the image when creating new
-									// FrameImage
-									toParse.addItem(image);
-								} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_BITMAP_IMAGE) && i.getLink() != null
-										&& !i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
-									XRayable image = null;
-									if (i.hasEnclosures()) {
-										// image =
-										// i.getEnclosures().iterator().next();
-										// image.refresh();
-										// i.setHidden(true);
-									} else {
-										// If a new bitmap is created for a
-										// frame which already has a bitmap dont
-										// recreate the bitmap
-										image = new FrameBitmap((Text) i, null);
-									}
-									toParse.addItem(image);
-								} else if (ItemUtils.startsWithTag(i, "@c")) {
-									// Can only have a @c
-									if (!i.hasEnclosures() && i.getLines().size() == 1) {
-										toParse.addItem(new Circle((Text) i));
-									}
-									// Check for JSItem
-								} else if (ItemUtils.startsWithTag(i, "@js")) {
-									toParse.addItem(new JSItem((Text) i));
-									// Check for interactive widgets
-								} else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IWIDGET)) {
-									createWidget(toParse, (Text) i);
-								}
-							}
-							// TODO decide exactly what to do here!!
-							toParse.addAnnotation((Text) i);
-						}
-					} else if (!DisplayController.isXRayMode() && i.hasFormula()) {
-						i.calculate(i.getFormula());
+						
 					}
 				}
@@ -1118,5 +1107,7 @@
 		 */
 
-		FrameIO.ResumeCache();
+		if (DisplayController.isTwinFramesOn()) {
+			FrameIO.ResumeCache();
+		}
 
 		toParse.clearOverlays();
@@ -1124,5 +1115,63 @@
 		toParse.addAllOverlays(overlays);
 		toParse.addAllVectors(vectors);
-
+	}
+
+	public static void Parse(Frame toParse) {
+		Parse(toParse, false);
+	}
+
+	/**
+	 * Checks for any special Annotation items and updates the display as necessary.
+	 * Special Items: Images, overlays, sort.
+	 * 
+	 */
+	public static void Parse(Frame toParse, boolean firstParse) {
+		Parse(toParse, firstParse, false);
+	}
+
+	/**
+	 * 
+	 * @param toParse
+	 * @param firstParse
+	 * @param ignoreAnnotations
+	 *            used to prevent infinate loops such as when performing TDFC with
+	 *            an ao tag linked to a frame with an frameImage of a frame which
+	 *            also has an ao tag on it.
+	 */	
+	public static void Parse(Frame toParse, boolean firstParse, boolean ignoreAnnotations) { 
+		List<String> accessList = Label.getAccessibleLabelsNames(new ItemsList(toParse.getPrimaryBody()));
+		
+		ItemsList primaries = toParse.getPrimaryBody();
+		ItemsList surrogates = toParse.getSurrogateBody();
+		
+		transformOutOfPlaceItems(toParse, primaries);
+		transformOutOfPlaceItems(toParse, surrogates);
+		
+		toParse.getInteractableItems().clear();
+		List<Item> newBody = parseFromPrimary(primaries, accessList);
+		toParse.getBody().clear();
+		toParse.getBody().addAll(newBody);
+		generatingSupportingItems(toParse, toParse.getBody(), ignoreAnnotations);
+		
+		if (firstParse) {
+			ItemUtils.EnclosedCheck(toParse.getSortedItems());
+		}
+	}
+
+	private static List<Item> parseFromPrimary(ItemsList primaryBody, List<String> access) {
+		List<Item> parsedBody = new ArrayList<Item>();
+		
+		for (Item item: primaryBody) {
+			String encryptionLabel = item.getEncryptionLabel();
+			if (encryptionLabel == null || encryptionLabel.isEmpty()) {
+				parsedBody.add(item);
+			} else if (access.contains(encryptionLabel)) {
+				parsedBody.add(item);
+			} else {
+				parsedBody.addAll(item.getSurrogates());
+			}
+		}
+		
+		return parsedBody;
 	}
 
@@ -1225,5 +1274,5 @@
 				if (LastEdited.contains(x, y) && !FreeItems.getInstance().contains(LastEdited)
 						&& LastEdited.getParent() == DisplayController.getCurrentFrame()
-						&& LastEdited.getParent().getItems().contains(LastEdited)) {
+						&& LastEdited.getParent().getSortedItems().contains(LastEdited)) {
 					LastEdited.setOverlayPermission(UserAppliedPermission.full);
 					return LastEdited;
@@ -1412,5 +1461,5 @@
 			return null;
 		}
-		List<Item> items = current.getItems();
+		List<Item> items = current.getSortedItems();
 
 		// Remove all items that are connected to freeItems
@@ -1572,5 +1621,5 @@
 			MessageBay.suppressMessages(true);
 			int lastNumber = FrameIO.getLastNumber(defaultFrame.getFramesetName());
-			for (int i = 1; i <= lastNumber; i++) {
+			for (int i = 1; i <= lastNumber; i++) {				
 				// Load in next default, if it doesn't exist continue loop.
 				defaultFrame = FrameIO.LoadFrame(defaultFrame.getFramesetName() + i);
@@ -1670,5 +1719,5 @@
 						Frame indexFrame = FrameIO.LoadFrame(framesetName + '1');
 						// Look through the folder for help index pages
-						if (indexFrame != null && ItemUtils.FindTag(indexFrame.getItems(), "@HelpIndex") != null) {
+						if (indexFrame != null && ItemUtils.FindTag(indexFrame.getSortedItems(), "@HelpIndex") != null) {
 							// yPos += spacing;
 							yPos += 30;
