Clean up FIXME - adding more information to the warning message.
[debian/openrocket] / core / src / net / sf / openrocket / file / openrocket / importt / OpenRocketLoader.java
index ab8ef8de2e58085601c190d8b9675af0a24a9a72..39845c7f3733075cc9316ab0707824ed1348a71f 100644 (file)
@@ -7,6 +7,7 @@ import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -20,12 +21,14 @@ import net.sf.openrocket.document.StorageOptions;
 import net.sf.openrocket.file.AbstractRocketLoader;
 import net.sf.openrocket.file.MotorFinder;
 import net.sf.openrocket.file.RocketLoadException;
+import net.sf.openrocket.file.simplesax.AbstractElementHandler;
 import net.sf.openrocket.file.simplesax.ElementHandler;
 import net.sf.openrocket.file.simplesax.PlainTextHandler;
 import net.sf.openrocket.file.simplesax.SimpleSAX;
 import net.sf.openrocket.logging.LogHelper;
 import net.sf.openrocket.material.Material;
 import net.sf.openrocket.motor.Motor;
+import net.sf.openrocket.preset.ComponentPreset;
 import net.sf.openrocket.rocketcomponent.BodyComponent;
 import net.sf.openrocket.rocketcomponent.BodyTube;
 import net.sf.openrocket.rocketcomponent.Bulkhead;
@@ -64,6 +67,7 @@ import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
 import net.sf.openrocket.rocketcomponent.Transition;
 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
 import net.sf.openrocket.rocketcomponent.TubeCoupler;
+import net.sf.openrocket.simulation.customexpression.CustomExpression;
 import net.sf.openrocket.simulation.FlightData;
 import net.sf.openrocket.simulation.FlightDataBranch;
 import net.sf.openrocket.simulation.FlightDataType;
@@ -95,30 +99,30 @@ import org.xml.sax.SAXException;
  */
 public class OpenRocketLoader extends AbstractRocketLoader {
        private static final LogHelper log = Application.getLogger();
-       
-       
+
+
        @Override
        public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
-                       IOException {
+       IOException {
                log.info("Loading .ork file");
                DocumentLoadingContext context = new DocumentLoadingContext();
                context.setMotorFinder(motorFinder);
-               
+
                InputSource xmlSource = new InputSource(source);
                OpenRocketHandler handler = new OpenRocketHandler(context);
-               
-               
+
+
                try {
                        SimpleSAX.readXML(xmlSource, handler, warnings);
                } catch (SAXException e) {
                        log.warn("Malformed XML in input");
                        throw new RocketLoadException("Malformed XML in input.", e);
                }
-               
-               
+
+
                OpenRocketDocument doc = handler.getDocument();
                doc.getDefaultConfiguration().setAllStages();
-               
+
                // Deduce suitable time skip
                double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
                for (Simulation s : doc.getSimulations()) {
@@ -135,7 +139,7 @@ public class OpenRocketLoader extends AbstractRocketLoader {
                        List<Double> list = branch.get(FlightDataType.TYPE_TIME);
                        if (list == null)
                                continue;
-                       
+
                        double previousTime = Double.NaN;
                        for (double time : list) {
                                if (time - previousTime < timeSkip)
@@ -145,33 +149,33 @@ public class OpenRocketLoader extends AbstractRocketLoader {
                }
                // Round value
                timeSkip = Math.rint(timeSkip * 100) / 100;
-               
+
                doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
                doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
                doc.getDefaultStorageOptions().setExplicitlySet(false);
-               
+
                doc.clearUndo();
                log.info("Loading done");
                return doc;
        }
-       
+
 }
 
 
 
 class DocumentConfig {
-       
+
        /* Remember to update OpenRocketSaver as well! */
-       public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4" };
-       
+       public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4", "1.5" };
+
        /**
         * Divisor used in converting an integer version to the point-represented version.
         * The integer version divided by this value is the major version and the remainder is
         * the minor version.  For example 101 corresponds to file version "1.1".
         */
        public static final int FILE_VERSION_DIVISOR = 100;
-       
-       
+
+
        ////////  Component constructors
        static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
        static {
@@ -184,29 +188,29 @@ class DocumentConfig {
                        constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
                        constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
                        constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
-                       
+
                        // Internal components
                        constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
                        constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
                        constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
                        constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
                        constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
-                       
+
                        constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
                        constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
                        constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
                        constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
-                       
+
                        // Other
                        constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
-                       
+
                } catch (NoSuchMethodException e) {
                        throw new BugException(
                                        "Error in constructing the 'constructors' HashMap.");
                }
        }
-       
-       
+
+
        ////////  Parameter setters
        /*
         * The keys are of the form Class:param, where Class is the class name and param
@@ -234,7 +238,9 @@ class DocumentConfig {
                                Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
                setters.put("RocketComponent:comment", new StringSetter(
                                Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
-               
+               setters.put("RocketComponent:preset", new ComponentPresetSetter(
+                               Reflection.findMethod(RocketComponent.class, "loadPreset", ComponentPreset.class)));
+
                // ExternalComponent
                setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
                                Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
@@ -242,23 +248,23 @@ class DocumentConfig {
                setters.put("ExternalComponent:material", new MaterialSetter(
                                Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
                                Material.Type.BULK));
-               
+
                // BodyComponent
                setters.put("BodyComponent:length", new DoubleSetter(
                                Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
-               
+
                // SymmetricComponent
                setters.put("SymmetricComponent:thickness", new DoubleSetter(
                                Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
                                "filled",
                                Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
-               
+
                // BodyTube
                setters.put("BodyTube:radius", new DoubleSetter(
                                Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
                                "auto",
                                Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
-               
+
                // Transition
                setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
                                Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
@@ -267,7 +273,7 @@ class DocumentConfig {
                                Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
                setters.put("Transition:shapeparameter", new DoubleSetter(
                                Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
-               
+
                setters.put("Transition:foreradius", new DoubleSetter(
                                Reflection.findMethod(Transition.class, "setForeRadius", double.class),
                                "auto",
@@ -276,7 +282,7 @@ class DocumentConfig {
                                Reflection.findMethod(Transition.class, "setAftRadius", double.class),
                                "auto",
                                Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
-               
+
                setters.put("Transition:foreshoulderradius", new DoubleSetter(
                                Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
                setters.put("Transition:foreshoulderlength", new DoubleSetter(
@@ -285,7 +291,7 @@ class DocumentConfig {
                                Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
                setters.put("Transition:foreshouldercapped", new BooleanSetter(
                                Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
-               
+
                setters.put("Transition:aftshoulderradius", new DoubleSetter(
                                Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
                setters.put("Transition:aftshoulderlength", new DoubleSetter(
@@ -294,14 +300,14 @@ class DocumentConfig {
                                Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
                setters.put("Transition:aftshouldercapped", new BooleanSetter(
                                Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
-               
+
                // NoseCone - disable disallowed elements
                setters.put("NoseCone:foreradius", null);
                setters.put("NoseCone:foreshoulderradius", null);
                setters.put("NoseCone:foreshoulderlength", null);
                setters.put("NoseCone:foreshoulderthickness", null);
                setters.put("NoseCone:foreshouldercapped", null);
-               
+
                // FinSet
                setters.put("FinSet:fincount", new IntSetter(
                                Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
@@ -319,7 +325,7 @@ class DocumentConfig {
                setters.put("FinSet:tablength", new DoubleSetter(
                                Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
                setters.put("FinSet:tabposition", new FinTabPositionSetter());
-               
+
                // TrapezoidFinSet
                setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
                                Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
@@ -329,15 +335,15 @@ class DocumentConfig {
                                Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
                setters.put("TrapezoidFinSet:height", new DoubleSetter(
                                Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
-               
+
                // EllipticalFinSet
                setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
                                Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
                setters.put("EllipticalFinSet:height", new DoubleSetter(
                                Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
-               
+
                // FreeformFinSet points handled as a special handler
-               
+
                // LaunchLug
                setters.put("LaunchLug:radius", new DoubleSetter(
                                Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
@@ -348,14 +354,14 @@ class DocumentConfig {
                setters.put("LaunchLug:radialdirection", new DoubleSetter(
                                Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
                                Math.PI / 180.0));
-               
+
                // InternalComponent - nothing
-               
+
                // StructuralComponent
                setters.put("StructuralComponent:material", new MaterialSetter(
                                Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
                                Material.Type.BULK));
-               
+
                // RingComponent
                setters.put("RingComponent:length", new DoubleSetter(
                                Reflection.findMethod(RingComponent.class, "setLength", double.class)));
@@ -364,23 +370,23 @@ class DocumentConfig {
                setters.put("RingComponent:radialdirection", new DoubleSetter(
                                Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
                                Math.PI / 180.0));
-               
+
                // ThicknessRingComponent - radius on separate components due to differing automatics
                setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
                                Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
-               
+
                // EngineBlock
                setters.put("EngineBlock:outerradius", new DoubleSetter(
                                Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
                                "auto",
                                Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
-               
+
                // TubeCoupler
                setters.put("TubeCoupler:outerradius", new DoubleSetter(
                                Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
                                "auto",
                                Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
-               
+
                // InnerTube
                setters.put("InnerTube:outerradius", new DoubleSetter(
                                Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
@@ -390,9 +396,9 @@ class DocumentConfig {
                setters.put("InnerTube:clusterrotation", new DoubleSetter(
                                Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
                                Math.PI / 180.0));
-               
+
                // RadiusRingComponent
-               
+
                // Bulkhead
                setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
                                Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
@@ -400,7 +406,7 @@ class DocumentConfig {
                                Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
                                "auto",
                                Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
-               
+
                // CenteringRing
                setters.put("CenteringRing:innerradius", new DoubleSetter(
                                Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
@@ -410,8 +416,8 @@ class DocumentConfig {
                                Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
                                "auto",
                                Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
-               
-               
+
+
                // MassObject
                setters.put("MassObject:packedlength", new DoubleSetter(
                                Reflection.findMethod(MassObject.class, "setLength", double.class)));
@@ -422,18 +428,18 @@ class DocumentConfig {
                setters.put("MassObject:radialdirection", new DoubleSetter(
                                Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
                                Math.PI / 180.0));
-               
+
                // MassComponent
                setters.put("MassComponent:mass", new DoubleSetter(
                                Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
-               
+
                // ShockCord
                setters.put("ShockCord:cordlength", new DoubleSetter(
                                Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
                setters.put("ShockCord:material", new MaterialSetter(
                                Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
                                Material.Type.LINE));
-               
+
                // RecoveryDevice
                setters.put("RecoveryDevice:cd", new DoubleSetter(
                                Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
@@ -449,7 +455,7 @@ class DocumentConfig {
                setters.put("RecoveryDevice:material", new MaterialSetter(
                                Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
                                Material.Type.SURFACE));
-               
+
                // Parachute
                setters.put("Parachute:diameter", new DoubleSetter(
                                Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
@@ -460,13 +466,13 @@ class DocumentConfig {
                setters.put("Parachute:linematerial", new MaterialSetter(
                                Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
                                Material.Type.LINE));
-               
+
                // Streamer
                setters.put("Streamer:striplength", new DoubleSetter(
                                Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
                setters.put("Streamer:stripwidth", new DoubleSetter(
                                Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
-               
+
                // Rocket
                // <motorconfiguration> handled by separate handler
                setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
@@ -478,9 +484,17 @@ class DocumentConfig {
                                Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
                setters.put("Rocket:revision", new StringSetter(
                                Reflection.findMethod(Rocket.class, "setRevision", String.class)));
+
+               // Stage
+               setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
+                               Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
+                               Stage.SeparationEvent.class));
+               setters.put("Stage:separationdelay", new DoubleSetter(
+                               Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
+
        }
-       
-       
+
+
        /**
         * Search for a enum value that has the corresponding name as an XML value.  The current
         * conversion from enum name to XML value is to lowercase the name and strip out all 
@@ -494,19 +508,19 @@ class DocumentConfig {
         */
        public static <T extends Enum<T>> Enum<T> findEnum(String name,
                        Class<? extends Enum<T>> enumClass) {
-               
+
                if (name == null)
                        return null;
                name = name.trim();
                for (Enum<T> e : enumClass.getEnumConstants()) {
-                       if (e.name().toLowerCase().replace("_", "").equals(name)) {
+                       if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) {
                                return e;
                        }
                }
                return null;
        }
-       
-       
+
+
        /**
         * Convert a string to a double including formatting specifications of the OpenRocket
         * file format.  This accepts all formatting that is valid for 
@@ -537,14 +551,14 @@ class DocumentConfig {
  * The starting point of the handlers.  Accepts a single <openrocket> element and hands
  * the contents to be read by a OpenRocketContentsHandler.
  */
-class OpenRocketHandler extends ElementHandler {
+class OpenRocketHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private OpenRocketContentHandler handler = null;
-       
+
        public OpenRocketHandler(DocumentLoadingContext context) {
                this.context = context;
        }
-       
+
        /**
         * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
         * has not been read yet.
@@ -554,24 +568,24 @@ class OpenRocketHandler extends ElementHandler {
        public OpenRocketDocument getDocument() {
                return handler.getDocument();
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                // Check for unknown elements
                if (!element.equals("openrocket")) {
                        warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
                        return null;
                }
-               
+
                // Check for first call
                if (handler != null) {
                        warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
                                        + "ones."));
                        return null;
                }
-               
+
                // Check version number
                String version = null;
                String creator = attributes.remove("creator");
@@ -591,18 +605,18 @@ class OpenRocketHandler extends ElementHandler {
                        str += ", attempting to read file anyway.";
                        warnings.add(str);
                }
-               
+
                context.setFileVersion(parseVersion(docVersion));
-               
+
                handler = new OpenRocketContentHandler(context);
                return handler;
        }
-       
-       
+
+
        private int parseVersion(String docVersion) {
                if (docVersion == null)
                        return 0;
-               
+
                Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
                if (m.matches()) {
                        int major = Integer.parseInt(m.group(1));
@@ -612,7 +626,7 @@ class OpenRocketHandler extends ElementHandler {
                        return 0;
                }
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
@@ -620,39 +634,39 @@ class OpenRocketHandler extends ElementHandler {
                attributes.remove("creator");
                super.closeElement(element, attributes, content, warnings);
        }
-       
-       
+
+
 }
 
 
 /**
  * Handles the content of the <openrocket> tag.
  */
-class OpenRocketContentHandler extends ElementHandler {
+class OpenRocketContentHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private final OpenRocketDocument doc;
        private final Rocket rocket;
-       
+
        private boolean rocketDefined = false;
        private boolean simulationsDefined = false;
-       
+       private boolean datatypesDefined = false;
+
        public OpenRocketContentHandler(DocumentLoadingContext context) {
                this.context = context;
                this.rocket = new Rocket();
                this.doc = new OpenRocketDocument(rocket);
        }
-       
-       
+
        public OpenRocketDocument getDocument() {
                if (!rocketDefined)
                        return null;
                return doc;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (element.equals("rocket")) {
                        if (rocketDefined) {
                                warnings.add(Warning
@@ -664,6 +678,15 @@ class OpenRocketContentHandler extends ElementHandler {
                        return new ComponentParameterHandler(rocket, context);
                }
                
+               if (element.equals("datatypes")){
+                       if (datatypesDefined) {
+                               warnings.add(Warning.fromString("Multiple datatype blocks. Ignoring later ones."));
+                               return null;
+                       }
+                       datatypesDefined = true;
+                       return new DatatypeHandler(this, context);
+               }
+
                if (element.equals("simulations")) {
                        if (simulationsDefined) {
                                warnings.add(Warning
@@ -674,33 +697,117 @@ class OpenRocketContentHandler extends ElementHandler {
                        simulationsDefined = true;
                        return new SimulationsHandler(doc, context);
                }
-               
+
                warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
-               
+
                return null;
        }
 }
 
 
 
+class DatatypeHandler extends AbstractElementHandler {
+       private final DocumentLoadingContext context;
+       private final OpenRocketContentHandler contentHandler;
+       private CustomExpressionHandler customExpressionHandler = null;
+       
+       public DatatypeHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) {
+               this.context = context;
+               this.contentHandler = contentHandler;
+       }
+       
+       @Override
+       public ElementHandler openElement(String element,
+                       HashMap<String, String> attributes, WarningSet warnings)
+                       throws SAXException {
+               
+               if (element.equals("type") && attributes.get("source").equals("customexpression") ){
+                       customExpressionHandler = new CustomExpressionHandler(contentHandler, context);
+                       return customExpressionHandler;
+               }
+               else {
+                       warnings.add(Warning.fromString("Unknown datatype " + element + " defined, ignoring"));
+               }
+               
+               return this;
+       }
+       
+       @Override
+       public void closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) throws SAXException {
+               attributes.remove("source");
+               super.closeElement(element, attributes, content, warnings);
+               
+               if (customExpressionHandler != null){
+                       contentHandler.getDocument().addCustomExpression(customExpressionHandler.currentExpression);
+               }
+               
+       }
+       
+}
+
+class CustomExpressionHandler extends AbstractElementHandler{
+       private final DocumentLoadingContext context;
+       private final OpenRocketContentHandler contentHandler;
+       public CustomExpression currentExpression;
+       
+       public CustomExpressionHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) {
+               this.context = context;
+               this.contentHandler = contentHandler;
+               currentExpression = new CustomExpression(contentHandler.getDocument());
+
+       }
+       
+       @Override
+       public ElementHandler openElement(String element,
+                       HashMap<String, String> attributes, WarningSet warnings)
+                       throws SAXException {
+                               
+               return this;
+       }
+       
+       @Override
+       public void closeElement(String element, HashMap<String, String> attributes,
+               String content, WarningSet warnings) throws SAXException {
+                               
+               if (element.equals("type")) {
+                       contentHandler.getDocument().addCustomExpression(currentExpression);
+               }
+                       
+               if (element.equals("name")) {
+                       currentExpression.setName(content);
+               }
+                
+               if (element.equals("symbol")) {
+                       currentExpression.setSymbol(content);
+               }
+               
+               if (element.equals("unit") && attributes.get("unittype").equals("auto")) {
+                       currentExpression.setUnit(content);
+               }
+               
+               if (element.equals("expression")){
+                       currentExpression.setExpression(content);
+               }
+       }       
+}
 
 /**
  * A handler that creates components from the corresponding elements.  The control of the
  * contents is passed on to ComponentParameterHandler.
  */
-class ComponentHandler extends ElementHandler {
+class ComponentHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private final RocketComponent parent;
-       
+
        public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
                this.parent = parent;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                // Attempt to construct new component
                Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
                                .get(element);
@@ -708,7 +815,7 @@ class ComponentHandler extends ElementHandler {
                        warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
                        return null;
                }
-               
+
                RocketComponent c;
                try {
                        c = constructor.newInstance();
@@ -719,9 +826,9 @@ class ComponentHandler extends ElementHandler {
                } catch (InvocationTargetException e) {
                        throw Reflection.handleWrappedException(e);
                }
-               
+
                parent.addChild(c);
-               
+
                return new ComponentParameterHandler(c, context);
        }
 }
@@ -732,19 +839,19 @@ class ComponentHandler extends ElementHandler {
  * This uses the setters, or delegates the handling to another handler for specific
  * elements.
  */
-class ComponentParameterHandler extends ElementHandler {
+class ComponentParameterHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private final RocketComponent component;
-       
+
        public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
                this.component = c;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                // Check for specific elements that contain other elements
                if (element.equals("subcomponents")) {
                        return new ComponentHandler(component, context);
@@ -770,22 +877,22 @@ class ComponentParameterHandler extends ElementHandler {
                        }
                        return new MotorConfigurationHandler((Rocket) component, context);
                }
-               
-               
+
+
                return PlainTextHandler.INSTANCE;
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                if (element.equals("subcomponents") || element.equals("motormount") ||
                                element.equals("finpoints") || element.equals("motorconfiguration")) {
                        return;
                }
-               
+
                // Search for the correct setter class
-               
+
                Class<?> c;
                for (c = component.getClass(); c != null; c = c.getSuperclass()) {
                        String setterKey = c.getSimpleName() + ":" + element;
@@ -813,28 +920,28 @@ class ComponentParameterHandler extends ElementHandler {
  * A handler that reads the <point> specifications within the freeformfinset's
  * <finpoints> elements.
  */
-class FinSetPointHandler extends ElementHandler {
+class FinSetPointHandler extends AbstractElementHandler {
        @SuppressWarnings("unused")
        private final DocumentLoadingContext context;
        private final FreeformFinSet finset;
        private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
-       
+
        public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
                this.finset = finset;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
                return PlainTextHandler.INSTANCE;
        }
-       
-       
+
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
-               
+
                String strx = attributes.remove("x");
                String stry = attributes.remove("y");
                if (strx == null || stry == null) {
@@ -849,10 +956,10 @@ class FinSetPointHandler extends ElementHandler {
                        warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
                        return;
                }
-               
+
                super.closeElement(element, attributes, content, warnings);
        }
-       
+
        @Override
        public void endHandler(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
@@ -865,59 +972,59 @@ class FinSetPointHandler extends ElementHandler {
 }
 
 
-class MotorMountHandler extends ElementHandler {
+class MotorMountHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private final MotorMount mount;
        private MotorHandler motorHandler;
-       
+
        public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
                this.mount = mount;
                this.context = context;
                mount.setMotorMount(true);
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (element.equals("motor")) {
                        motorHandler = new MotorHandler(context);
                        return motorHandler;
                }
-               
+
                if (element.equals("ignitionevent") ||
                                element.equals("ignitiondelay") ||
                                element.equals("overhang")) {
                        return PlainTextHandler.INSTANCE;
                }
-               
+
                warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
                return null;
        }
-       
-       
-       
+
+
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
-               
+
                if (element.equals("motor")) {
                        String id = attributes.get("configid");
                        if (id == null || id.equals("")) {
                                warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
                                return;
                        }
-                       
+
                        Motor motor = motorHandler.getMotor(warnings);
                        mount.setMotor(id, motor);
                        mount.setMotorDelay(id, motorHandler.getDelay(warnings));
                        return;
                }
-               
+
                if (element.equals("ignitionevent")) {
                        MotorMount.IgnitionEvent event = null;
                        for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
-                               if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
+                               if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) {
                                        event = e;
                                        break;
                                }
@@ -929,7 +1036,7 @@ class MotorMountHandler extends ElementHandler {
                        mount.setIgnitionEvent(event);
                        return;
                }
-               
+
                if (element.equals("ignitiondelay")) {
                        double d;
                        try {
@@ -941,7 +1048,7 @@ class MotorMountHandler extends ElementHandler {
                        mount.setIgnitionDelay(d);
                        return;
                }
-               
+
                if (element.equals("overhang")) {
                        double d;
                        try {
@@ -953,7 +1060,7 @@ class MotorMountHandler extends ElementHandler {
                        mount.setMotorOverhang(d);
                        return;
                }
-               
+
                super.closeElement(element, attributes, content, warnings);
        }
 }
@@ -961,69 +1068,69 @@ class MotorMountHandler extends ElementHandler {
 
 
 
-class MotorConfigurationHandler extends ElementHandler {
+class MotorConfigurationHandler extends AbstractElementHandler {
        @SuppressWarnings("unused")
        private final DocumentLoadingContext context;
        private final Rocket rocket;
        private String name = null;
        private boolean inNameElement = false;
-       
+
        public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
                this.rocket = rocket;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (inNameElement || !element.equals("name")) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return null;
                }
                inNameElement = true;
-               
+
                return PlainTextHandler.INSTANCE;
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
                name = content;
        }
-       
+
        @Override
        public void endHandler(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
-               
+
                String configid = attributes.remove("configid");
                if (configid == null || configid.equals("")) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                if (!rocket.addMotorConfigurationID(configid)) {
                        warnings.add("Duplicate motor configuration ID used.");
                        return;
                }
-               
+
                if (name != null && name.trim().length() > 0) {
                        rocket.setMotorConfigurationName(configid, name);
                }
-               
+
                if ("true".equals(attributes.remove("default"))) {
                        rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
                }
-               
+
                super.closeElement(element, attributes, content, warnings);
        }
 }
 
 
-class MotorHandler extends ElementHandler {
+class MotorHandler extends AbstractElementHandler {
        /** File version where latest digest format was introduced */
        private static final int MOTOR_DIGEST_VERSION = 104;
-       
+
        private final DocumentLoadingContext context;
        private Motor.Type type = null;
        private String manufacturer = null;
@@ -1032,26 +1139,26 @@ class MotorHandler extends ElementHandler {
        private double diameter = Double.NaN;
        private double length = Double.NaN;
        private double delay = Double.NaN;
-       
+
        public MotorHandler(DocumentLoadingContext context) {
                this.context = context;
        }
-       
-       
+
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
                return PlainTextHandler.INSTANCE;
        }
-       
-       
+
+
        /**
         * Return the motor to use, or null.
         */
        public Motor getMotor(WarningSet warnings) {
                return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
        }
-       
+
        /**
         * Return the delay to use for the motor.
         */
@@ -1062,20 +1169,20 @@ class MotorHandler extends ElementHandler {
                }
                return delay;
        }
-       
-       
+
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
-               
+
                content = content.trim();
-               
+
                if (element.equals("type")) {
-                       
+
                        // Motor type
                        type = null;
                        for (Motor.Type t : Motor.Type.values()) {
-                               if (t.name().toLowerCase().equals(content.trim())) {
+                               if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) {
                                        type = t;
                                        break;
                                }
@@ -1083,26 +1190,26 @@ class MotorHandler extends ElementHandler {
                        if (type == null) {
                                warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
                        }
-                       
+
                } else if (element.equals("manufacturer")) {
-                       
+
                        // Manufacturer
                        manufacturer = content.trim();
-                       
+
                } else if (element.equals("designation")) {
-                       
+
                        // Designation
                        designation = content.trim();
-                       
+
                } else if (element.equals("digest")) {
-                       
+
                        // Digest is used only for file versions saved using the same digest algorithm
                        if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
                                digest = content.trim();
                        }
-                       
+
                } else if (element.equals("diameter")) {
-                       
+
                        // Diameter
                        diameter = Double.NaN;
                        try {
@@ -1113,22 +1220,22 @@ class MotorHandler extends ElementHandler {
                        if (Double.isNaN(diameter)) {
                                warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
                        }
-                       
+
                } else if (element.equals("length")) {
-                       
+
                        // Length
                        length = Double.NaN;
                        try {
                                length = Double.parseDouble(content.trim());
                        } catch (NumberFormatException ignore) {
                        }
-                       
+
                        if (Double.isNaN(length)) {
                                warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
                        }
-                       
+
                } else if (element.equals("delay")) {
-                       
+
                        // Delay
                        delay = Double.NaN;
                        if (content.equals("none")) {
@@ -1138,78 +1245,81 @@ class MotorHandler extends ElementHandler {
                                        delay = Double.parseDouble(content.trim());
                                } catch (NumberFormatException ignore) {
                                }
-                               
+
                                if (Double.isNaN(delay)) {
                                        warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
                                }
-                               
+
                        }
-                       
+
                } else {
                        super.closeElement(element, attributes, content, warnings);
                }
        }
-       
+
 }
 
 
 
-class SimulationsHandler extends ElementHandler {
+class SimulationsHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private final OpenRocketDocument doc;
        private SingleSimulationHandler handler;
-       
+
        public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
                this.doc = doc;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (!element.equals("simulation")) {
                        warnings.add("Unknown element '" + element + "', ignoring.");
                        return null;
                }
-               
+
                handler = new SingleSimulationHandler(doc, context);
                return handler;
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
                attributes.remove("status");
                super.closeElement(element, attributes, content, warnings);
        }
-       
-       
+
+
 }
 
-class SingleSimulationHandler extends ElementHandler {
+class SingleSimulationHandler extends AbstractElementHandler {
+
        private final DocumentLoadingContext context;
-       
+
        private final OpenRocketDocument doc;
-       
+
        private String name;
-       
+
        private SimulationConditionsHandler conditionHandler;
        private FlightDataHandler dataHandler;
        
        private final List<String> listeners = new ArrayList<String>();
-       
+
        public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
                this.doc = doc;
                this.context = context;
        }
-       
-       
+
+       public OpenRocketDocument getDocument(){
+               return doc;
+       }
        
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (element.equals("name") || element.equals("simulator") ||
                                element.equals("calculator") || element.equals("listener")) {
                        return PlainTextHandler.INSTANCE;
@@ -1217,18 +1327,18 @@ class SingleSimulationHandler extends ElementHandler {
                        conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
                        return conditionHandler;
                } else if (element.equals("flightdata")) {
-                       dataHandler = new FlightDataHandler(context);
+                       dataHandler = new FlightDataHandler(this, context);
                        return dataHandler;
                } else {
                        warnings.add("Unknown element '" + element + "', ignoring.");
                        return null;
                }
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                if (element.equals("name")) {
                        name = content;
                } else if (element.equals("simulator")) {
@@ -1242,20 +1352,20 @@ class SingleSimulationHandler extends ElementHandler {
                } else if (element.equals("listener") && content.trim().length() > 0) {
                        listeners.add(content.trim());
                }
-               
+
        }
-       
+
        @Override
        public void endHandler(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                String s = attributes.get("status");
                Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
                if (status == null) {
                        warnings.add("Simulation status unknown, assuming outdated.");
                        status = Simulation.Status.OUTDATED;
                }
-               
+
                SimulationOptions conditions;
                if (conditionHandler != null) {
                        conditions = conditionHandler.getConditions();
@@ -1263,41 +1373,39 @@ class SingleSimulationHandler extends ElementHandler {
                        warnings.add("Simulation conditions not defined, using defaults.");
                        conditions = new SimulationOptions(doc.getRocket());
                }
-               
+
                if (name == null)
                        name = "Simulation";
-               
+
                FlightData data;
                if (dataHandler == null)
                        data = null;
                else
                        data = dataHandler.getFlightData();
-               
+
                Simulation simulation = new Simulation(doc.getRocket(), status, name,
                                conditions, listeners, data);
-               
+                               
                doc.addSimulation(simulation);
        }
 }
-
-
-
-class SimulationConditionsHandler extends ElementHandler {
+       
+class SimulationConditionsHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
        private SimulationOptions conditions;
        private AtmosphereHandler atmosphereHandler;
-       
+
        public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
                this.context = context;
                conditions = new SimulationOptions(rocket);
                // Set up default loading settings (which may differ from the new defaults)
                conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
        }
-       
+
        public SimulationOptions getConditions() {
                return conditions;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
@@ -1307,18 +1415,18 @@ class SimulationConditionsHandler extends ElementHandler {
                }
                return PlainTextHandler.INSTANCE;
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                double d = Double.NaN;
                try {
                        d = Double.parseDouble(content);
                } catch (NumberFormatException ignore) {
                }
-               
-               
+
+
                if (element.equals("configid")) {
                        if (content.equals("")) {
                                conditions.setMotorConfigurationID(null);
@@ -1394,34 +1502,34 @@ class SimulationConditionsHandler extends ElementHandler {
 }
 
 
-class AtmosphereHandler extends ElementHandler {
+class AtmosphereHandler extends AbstractElementHandler {
        @SuppressWarnings("unused")
        private final DocumentLoadingContext context;
        private final String model;
        private double temperature = Double.NaN;
        private double pressure = Double.NaN;
-       
+
        public AtmosphereHandler(String model, DocumentLoadingContext context) {
                this.model = model;
                this.context = context;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
                return PlainTextHandler.INSTANCE;
        }
-       
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) throws SAXException {
-               
+
                double d = Double.NaN;
                try {
                        d = Double.parseDouble(content);
                } catch (NumberFormatException ignore) {
                }
-               
+
                if (element.equals("basetemperature")) {
                        if (Double.isNaN(d)) {
                                warnings.add("Illegal base temperature specified, ignoring.");
@@ -1436,8 +1544,8 @@ class AtmosphereHandler extends ElementHandler {
                        super.closeElement(element, attributes, content, warnings);
                }
        }
-       
-       
+
+
        public void storeSettings(SimulationOptions cond, WarningSet warnings) {
                if (!Double.isNaN(pressure)) {
                        cond.setLaunchPressure(pressure);
@@ -1445,7 +1553,7 @@ class AtmosphereHandler extends ElementHandler {
                if (!Double.isNaN(temperature)) {
                        cond.setLaunchTemperature(temperature);
                }
-               
+
                if ("isa".equals(model)) {
                        cond.setISAAtmosphere(true);
                } else if ("extendedisa".equals(model)) {
@@ -1455,32 +1563,34 @@ class AtmosphereHandler extends ElementHandler {
                        warnings.add("Unknown atmospheric model, using ISA.");
                }
        }
-       
+
 }
 
 
-class FlightDataHandler extends ElementHandler {
+class FlightDataHandler extends AbstractElementHandler {
        private final DocumentLoadingContext context;
-       
+
        private FlightDataBranchHandler dataHandler;
        private WarningSet warningSet = new WarningSet();
        private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
        
+       private SingleSimulationHandler simHandler;
        private FlightData data;
-       
-       
-       public FlightDataHandler(DocumentLoadingContext context) {
+
+
+       public FlightDataHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) {
                this.context = context;
+               this.simHandler = simHandler;
        }
-       
+
        public FlightData getFlightData() {
                return data;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (element.equals("warning")) {
                        return PlainTextHandler.INSTANCE;
                }
@@ -1489,20 +1599,21 @@ class FlightDataHandler extends ElementHandler {
                                warnings.add("Illegal flight data definition, ignoring.");
                                return null;
                        }
-                       dataHandler = new FlightDataBranchHandler(attributes.get("name"),
-                                       attributes.get("types"), context);
+                       dataHandler = new FlightDataBranchHandler(      attributes.get("name"),
+                                                                                                               attributes.get("types"), 
+                                                                                                               simHandler, context);
                        return dataHandler;
                }
-               
+
                warnings.add("Unknown element '" + element + "' encountered, ignoring.");
                return null;
        }
-       
-       
+
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                if (element.equals("databranch")) {
                        FlightDataBranch branch = dataHandler.getBranch();
                        if (branch.getLength() > 0) {
@@ -1512,12 +1623,12 @@ class FlightDataHandler extends ElementHandler {
                        warningSet.add(Warning.fromString(content));
                }
        }
-       
-       
+
+
        @Override
        public void endHandler(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                if (branches.size() > 0) {
                        data = new FlightData(branches.toArray(new FlightDataBranch[0]));
                } else {
@@ -1530,7 +1641,7 @@ class FlightDataHandler extends ElementHandler {
                        double groundHitVelocity = Double.NaN;
                        double launchRodVelocity = Double.NaN;
                        double deploymentVelocity = Double.NaN;
-                       
+
                        try {
                                maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
                        } catch (NumberFormatException ignore) {
@@ -1568,96 +1679,137 @@ class FlightDataHandler extends ElementHandler {
                                deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
                        } catch (NumberFormatException ignore) {
                        }
-                       
+
                        data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
                                        timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
                }
-               
+
                data.getWarningSet().addAll(warningSet);
                data.immute();
        }
-       
-       
+
+
 }
 
 
-class FlightDataBranchHandler extends ElementHandler {
+class FlightDataBranchHandler extends AbstractElementHandler {
        @SuppressWarnings("unused")
        private final DocumentLoadingContext context;
        private final FlightDataType[] types;
        private final FlightDataBranch branch;
        
-       public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) {
+       private static final LogHelper log = Application.getLogger();
+       private final SingleSimulationHandler simHandler;
+       
+       public FlightDataBranchHandler(String name, String typeList, SingleSimulationHandler simHandler, DocumentLoadingContext context) {
+               this.simHandler = simHandler;
                this.context = context;
                String[] split = typeList.split(",");
                types = new FlightDataType[split.length];
                for (int i = 0; i < split.length; i++) {
-                       types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
+                       String typeName = split[i];
+                       FlightDataType matching = findFlightDataType(typeName);
+                       types[i] = matching;
+                       //types[i] = FlightDataType.getType(typeName, matching.getSymbol(), matching.getUnitGroup());
                }
-               
+
                // TODO: LOW: May throw an IllegalArgumentException
                branch = new FlightDataBranch(name, types);
        }
        
+       // Find the full flight data type given name only
+       // Note: this way of doing it requires that custom expressions always come before flight data in the file,
+       // not the nicest but this is always the case anyway.
+       private FlightDataType findFlightDataType(String name){
+               
+        // Kevins version with lookup by key. Not using right now
+               /*
+               if ( key != null ) {
+                       for (FlightDataType t : FlightDataType.ALL_TYPES){
+                               if (t.getKey().equals(key) ){
+                                       return t;
+                               }
+                       }
+               }
+               */
+        
+               // Look in built in types
+               for (FlightDataType t : FlightDataType.ALL_TYPES){
+                       if (t.getName().equals(name) ){
+                               return t;
+                       }
+               }
+               
+               // Look in custom expressions
+               for (CustomExpression exp : simHandler.getDocument().getCustomExpressions()){
+                       if (exp.getName().equals(name) ){
+                               return exp.getType();
+                       }
+               }
+               
+               log.warn("Could not find the flight data type '"+name+"' used in the XML file. Substituted type with unknown symbol and units.");
+               return FlightDataType.getType(name, "Unknown", UnitGroup.UNITS_NONE);
+       }
+
        public FlightDataBranch getBranch() {
                branch.immute();
                return branch;
        }
-       
+
        @Override
        public ElementHandler openElement(String element, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (element.equals("datapoint"))
                        return PlainTextHandler.INSTANCE;
                if (element.equals("event"))
                        return PlainTextHandler.INSTANCE;
-               
+
                warnings.add("Unknown element '" + element + "' encountered, ignoring.");
                return null;
        }
-       
-       
+
+
        @Override
        public void closeElement(String element, HashMap<String, String> attributes,
                        String content, WarningSet warnings) {
-               
+
                if (element.equals("event")) {
                        double time;
                        FlightEvent.Type type;
-                       
+
                        try {
                                time = DocumentConfig.stringToDouble(attributes.get("time"));
                        } catch (NumberFormatException e) {
                                warnings.add("Illegal event specification, ignoring.");
                                return;
                        }
-                       
+
                        type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
                        if (type == null) {
                                warnings.add("Illegal event specification, ignoring.");
                                return;
                        }
-                       
+
                        branch.addEvent(new FlightEvent(type, time));
                        return;
                }
-               
+
                if (!element.equals("datapoint")) {
                        warnings.add("Unknown element '" + element + "' encountered, ignoring.");
                        return;
                }
-               
+
                // element == "datapoint"
-               
-               
+
+
                // Check line format
                String[] split = content.split(",");
                if (split.length != types.length) {
                        warnings.add("Data point did not contain correct amount of values, ignoring point.");
                        return;
                }
-               
+
                // Parse the doubles
                double[] values = new double[split.length];
                for (int i = 0; i < values.length; i++) {
@@ -1668,7 +1820,7 @@ class FlightDataBranchHandler extends ElementHandler {
                                return;
                        }
                }
-               
+
                // Add point to branch
                branch.addPoint();
                for (int i = 0; i < types.length; i++) {
@@ -1702,11 +1854,11 @@ interface Setter {
 ////  StringSetter - sets the value to the contained String
 class StringSetter implements Setter {
        private final Reflection.Method setMethod;
-       
+
        public StringSetter(Reflection.Method set) {
                setMethod = set;
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
@@ -1717,11 +1869,11 @@ class StringSetter implements Setter {
 ////  IntSetter - set an integer value
 class IntSetter implements Setter {
        private final Reflection.Method setMethod;
-       
+
        public IntSetter(Reflection.Method set) {
                setMethod = set;
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
@@ -1738,15 +1890,15 @@ class IntSetter implements Setter {
 //// BooleanSetter - set a boolean value
 class BooleanSetter implements Setter {
        private final Reflection.Method setMethod;
-       
+
        public BooleanSetter(Reflection.Method set) {
                setMethod = set;
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                s = s.trim();
                if (s.equalsIgnoreCase("true")) {
                        setMethod.invoke(c, true);
@@ -1767,7 +1919,7 @@ class DoubleSetter implements Setter {
        private final String specialString;
        private final Reflection.Method specialMethod;
        private final double multiplier;
-       
+
        /**
         * Set only the double value.
         * @param set   set method for the double value. 
@@ -1778,7 +1930,7 @@ class DoubleSetter implements Setter {
                this.specialMethod = null;
                this.multiplier = 1.0;
        }
-       
+
        /**
         * Multiply with the given multiplier and set the double value.
         * @param set   set method for the double value.
@@ -1790,7 +1942,7 @@ class DoubleSetter implements Setter {
                this.specialMethod = null;
                this.multiplier = mul;
        }
-       
+
        /**
         * Set the double value, or if the value equals the special string, use the
         * special setter and set it to true.
@@ -1806,20 +1958,20 @@ class DoubleSetter implements Setter {
                this.specialMethod = specialMethod;
                this.multiplier = 1.0;
        }
-       
-       
+
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                s = s.trim();
-               
+
                // Check for special case
                if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
                        specialMethod.invoke(c, true);
                        return;
                }
-               
+
                // Normal case
                try {
                        double d = Double.parseDouble(s);
@@ -1834,16 +1986,16 @@ class DoubleSetter implements Setter {
 class OverrideSetter implements Setter {
        private final Reflection.Method setMethod;
        private final Reflection.Method enabledMethod;
-       
+
        public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
                this.setMethod = set;
                this.enabledMethod = enabledMethod;
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                try {
                        double d = Double.parseDouble(s);
                        setMethod.invoke(c, d);
@@ -1858,22 +2010,22 @@ class OverrideSetter implements Setter {
 class EnumSetter<T extends Enum<T>> implements Setter {
        private final Reflection.Method setter;
        private final Class<T> enumClass;
-       
+
        public EnumSetter(Reflection.Method set, Class<T> enumClass) {
                this.setter = set;
                this.enumClass = enumClass;
        }
-       
+
        @Override
        public void set(RocketComponent c, String name, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
                if (setEnum == null) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                setter.invoke(c, setEnum);
        }
 }
@@ -1882,24 +2034,24 @@ class EnumSetter<T extends Enum<T>> implements Setter {
 ////  ColorSetter  -  sets a Color value
 class ColorSetter implements Setter {
        private final Reflection.Method setMethod;
-       
+
        public ColorSetter(Reflection.Method set) {
                setMethod = set;
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                String red = attributes.get("red");
                String green = attributes.get("green");
                String blue = attributes.get("blue");
-               
+
                if (red == null || green == null || blue == null) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                int r, g, b;
                try {
                        r = Integer.parseInt(red);
@@ -1909,100 +2061,166 @@ class ColorSetter implements Setter {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                Color color = new Color(r, g, b);
                setMethod.invoke(c, color);
-               
+
                if (!s.trim().equals("")) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                }
        }
 }
 
+////ComponentPresetSetter  -  sets a ComponentPreset value
+class ComponentPresetSetter implements Setter {
+private final Reflection.Method setMethod;
 
+public ComponentPresetSetter(Reflection.Method set) {
+       this.setMethod = set;
+}
 
-class MaterialSetter implements Setter {
-       private final Reflection.Method setMethod;
-       private final Material.Type type;
-       
-       public MaterialSetter(Reflection.Method set, Material.Type type) {
-               this.setMethod = set;
-               this.type = type;
+@Override
+public void set(RocketComponent c, String name, HashMap<String, String> attributes,
+               WarningSet warnings) {
+       String manufacturerName = attributes.get("manufacturer");
+       if ( manufacturerName == null ) {
+               warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no manufacturer specified.  Ignored"));
+               return;
        }
-       
-       @Override
-       public void set(RocketComponent c, String name, HashMap<String, String> attributes,
-                       WarningSet warnings) {
-               
-               Material mat;
-               
-               // Check name != ""
-               name = name.trim();
-               if (name.equals("")) {
-                       warnings.add(Warning.fromString("Illegal material specification, ignoring."));
-                       return;
-               }
-               
-               // Parse density
-               double density;
-               String str;
-               str = attributes.remove("density");
-               if (str == null) {
-                       warnings.add(Warning.fromString("Illegal material specification, ignoring."));
-                       return;
-               }
-               try {
-                       density = Double.parseDouble(str);
-               } catch (NumberFormatException e) {
-                       warnings.add(Warning.fromString("Illegal material specification, ignoring."));
-                       return;
+
+       String productNo = attributes.get("partno");
+       if ( productNo == null ) {
+               warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no partno specified.  Ignored"));
+               return;
+       }
+
+       String digest = attributes.get("digest");
+       if ( digest == null ) {
+               warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no digest specified."));
+       }
+
+       String type = attributes.get("type");
+       if ( type == null ) {
+               warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no type specified."));
+       }
+
+       List<ComponentPreset> presets = Application.getComponentPresetDao().find( manufacturerName, productNo );
+
+       ComponentPreset matchingPreset = null;
+
+       for( ComponentPreset preset: presets ) {
+               if ( digest != null && preset.getDigest().equals(digest) ) {
+                       // Found one with matching digest.  Take it.
+                       matchingPreset = preset;
+                       break;
                }
-               
-               // Parse thickness
-               //              double thickness = 0;
-               //              str = attributes.remove("thickness");
-               //              try {
-               //                      if (str != null)
-               //                              thickness = Double.parseDouble(str);
-               //              } catch (NumberFormatException e){
-               //                      warnings.add(Warning.fromString("Illegal material specification, ignoring."));
-               //                      return;
-               //              }
-               
-               // Check type if specified
-               str = attributes.remove("type");
-               if (str != null && !type.name().toLowerCase().equals(str)) {
-                       warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
-                       return;
+               if ( type != null && preset.getType().name().equals(type) && matchingPreset != null) {
+                       // Found the first one with matching type.
+                       matchingPreset = preset;
                }
-               
-               mat = Databases.findMaterial(type, name, density, false);
-               
-               setMethod.invoke(c, mat);
        }
+
+       // Was any found?
+       if ( matchingPreset == null ) {
+               warnings.add(Warning.fromString("No matching ComponentPreset for component " + c.getName() + " found matching " + manufacturerName + " " + productNo));
+               return;
+       }
+
+       if ( digest != null && !matchingPreset.getDigest().equals(digest) ) {
+               warnings.add(Warning.fromString("ComponentPreset for component " + c.getName() + " has wrong digest"));
+       }
+
+       setMethod.invoke(c, matchingPreset);
+}
 }
 
 
+////MaterialSetter  -  sets a Material value
+class MaterialSetter implements Setter {
+private final Reflection.Method setMethod;
+private final Material.Type type;
+
+public MaterialSetter(Reflection.Method set, Material.Type type) {
+       this.setMethod = set;
+       this.type = type;
+}
+
+@Override
+public void set(RocketComponent c, String name, HashMap<String, String> attributes,
+               WarningSet warnings) {
+
+       Material mat;
+
+       // Check name != ""
+       name = name.trim();
+       if (name.equals("")) {
+               warnings.add(Warning.fromString("Illegal material specification, ignoring."));
+               return;
+       }
+
+       // Parse density
+       double density;
+       String str;
+       str = attributes.remove("density");
+       if (str == null) {
+               warnings.add(Warning.fromString("Illegal material specification, ignoring."));
+               return;
+       }
+       try {
+               density = Double.parseDouble(str);
+       } catch (NumberFormatException e) {
+               warnings.add(Warning.fromString("Illegal material specification, ignoring."));
+               return;
+       }
+
+       // Parse thickness
+       //              double thickness = 0;
+       //              str = attributes.remove("thickness");
+       //              try {
+       //                      if (str != null)
+       //                              thickness = Double.parseDouble(str);
+       //              } catch (NumberFormatException e){
+       //                      warnings.add(Warning.fromString("Illegal material specification, ignoring."));
+       //                      return;
+       //              }
+
+       // Check type if specified
+       str = attributes.remove("type");
+       if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) {
+               warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
+               return;
+       }
+
+       String key = attributes.remove("key");
+
+       mat = Databases.findMaterial(type, key, name, density);
+
+       setMethod.invoke(c, mat);
+}
+}
+
+
+
 
 
 class PositionSetter implements Setter {
-       
+
        @Override
        public void set(RocketComponent c, String value, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
                                RocketComponent.Position.class);
                if (type == null) {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                double pos;
                try {
                        pos = Double.parseDouble(value);
@@ -2010,7 +2228,7 @@ class PositionSetter implements Setter {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                        return;
                }
-               
+
                if (c instanceof FinSet) {
                        ((FinSet) c).setRelativePosition(type);
                        c.setPositionValue(pos);
@@ -2023,34 +2241,34 @@ class PositionSetter implements Setter {
                } else {
                        warnings.add(Warning.FILE_INVALID_PARAMETER);
                }
-               
+
        }
 }
 
 
 class FinTabPositionSetter extends DoubleSetter {
-       
+
        public FinTabPositionSetter() {
                super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
        }
-       
+
        @Override
        public void set(RocketComponent c, String s, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (!(c instanceof FinSet)) {
                        throw new IllegalStateException("FinTabPositionSetter called for component " + c);
                }
-               
+
                String relative = attributes.get("relativeto");
                FinSet.TabRelativePosition position =
                                (TabRelativePosition) DocumentConfig.findEnum(relative,
                                                FinSet.TabRelativePosition.class);
-               
+
                if (position != null) {
-                       
+
                        ((FinSet) c).setTabRelativePosition(position);
-                       
+
                } else {
                        if (relative == null) {
                                warnings.add("Required attribute 'relativeto' not found for fin tab position.");
@@ -2058,25 +2276,25 @@ class FinTabPositionSetter extends DoubleSetter {
                                warnings.add("Illegal attribute value '" + relative + "' encountered.");
                        }
                }
-               
+
                super.set(c, s, attributes, warnings);
        }
-       
-       
+
+
 }
 
 
 class ClusterConfigurationSetter implements Setter {
-       
+
        @Override
        public void set(RocketComponent component, String value, HashMap<String, String> attributes,
                        WarningSet warnings) {
-               
+
                if (!(component instanceof Clusterable)) {
                        warnings.add("Illegal component defined as cluster.");
                        return;
                }
-               
+
                ClusterConfiguration config = null;
                for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
                        if (c.getXMLName().equals(value)) {
@@ -2084,12 +2302,12 @@ class ClusterConfigurationSetter implements Setter {
                                break;
                        }
                }
-               
+
                if (config == null) {
                        warnings.add("Illegal cluster configuration specified.");
                        return;
                }
-               
+
                ((Clusterable) component).setClusterConfiguration(config);
        }
 }