public static void Apply(AAProgram ast, FinalTransformations finalTrans)
        {
            //Build list of file dependacies
            Phase1 phase1 = new Phase1(finalTrans);
            ast.Apply(phase1);
            var dependancies = phase1.dependancies;
            if (dependancies.Keys.Count == 0) return;
            AASourceFile root = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry) ??
                                dependancies.Keys.FirstOrDefault(file => !file.GetName().Text.Contains("\\")) ??
                                dependancies.Keys.First(file => true);

            //Remove files unreachable from root
            //On second thought, dont. there might be static refferences the other way which needs to be included
            /*{
                List<AASourceFile> reachable = GetReachable(root, dependancies);
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                        dependancies.Remove(key);
                }
            }*/

            //Push common depancies up
            /*
             * root -> (item1 -> (item3), item2 -> (item4 -> (item3)))
             *
             * root -> (item3, item1, item2 -> (item4))
             */

            //Add unreachable to the root
            while (true)
            {
                List<AASourceFile> reachable = new List<AASourceFile>();
                GetReachable(root, dependancies, ref reachable);
                if (reachable.Count == dependancies.Count + (reachable.Contains(null) ? 1 : 0)) break;
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                    {
                        AASourceFile k = key;
                        //See if you can find another unreachable file which need this file
                        Dictionary<AASourceFile, int> decendantCounts = new Dictionary<AASourceFile, int>();
                        decendantCounts.Add(k, CountDecendants(k, dependancies, new List<AASourceFile>()));
                        while (true)
                        {
                            AASourceFile file = null;
                            foreach (KeyValuePair<AASourceFile, List<AASourceFile>> dependancy in dependancies)
                            {
                                if (decendantCounts.ContainsKey(dependancy.Key))
                                    continue;
                                if (!dependancy.Value.Contains(k))
                                    continue;
                                file = dependancy.Key;
                                break;
                            }

                            //AASourceFile file = dependancies.FirstOrDefault(item => item.Value.Contains(k)).Key;
                            if (file == null) break;
                            decendantCounts.Add(file, CountDecendants(file, dependancies, new List<AASourceFile>()));
                            k = file;
                        }
                        foreach (KeyValuePair<AASourceFile, int> decendantItem in decendantCounts)
                        {
                            if (decendantItem.Value > decendantCounts[k])
                                k = decendantItem.Key;
                        }

                        dependancies[root].Add(k);
                        break;
                    }
                }
            }
            //It is moved down here because cycles are not removed in unreachable
            RemoveCycles(root, dependancies, new List<AASourceFile> { root });

            //Convert to tree to make it easier
            List<Item> allItems = new List<Item>();
            IncludeItem rootIncludeItem = MakeTree(root, dependancies, allItems, null);
            bool[] removed = new bool[allItems.Count];
            for (int i = 0; i < removed.Length; i++)
                removed[i] = false;
            int removedCount = 0;

            //Ensure that each include is only included one place
            for (int i = 0; i < allItems.Count; i++)
            {
                if (removed[i])
                    continue;

                IncludeItem item1 = (IncludeItem)allItems[i];
                for (int j = i + 1; j < allItems.Count; j++)
                {
                    if (removed[j])
                        continue;
                    IncludeItem item2 = (IncludeItem)allItems[j];

                    if (item1.Current == item2.Current)
                    {
                        List<Item> path1 = item1.Path;
                        List<Item> path2 = item2.Path;

                        for (int k = 0; k < Math.Min(path1.Count, path2.Count); k++)
                        {
                            if (path1[k] != path2[k])
                            {

                                int insertAt = Math.Min(path1[k - 1].Children.IndexOf(path1[k]),
                                                        path2[k - 1].Children.IndexOf(path2[k]));

                                item1.Parent.Children.Remove(item1);
                                LinkedList<IncludeItem> toRemove = new LinkedList<IncludeItem>();
                                toRemove.AddLast(item2);
                                while (toRemove.Count > 0)
                                {
                                    IncludeItem item = toRemove.First.Value;
                                    toRemove.RemoveFirst();
                                    item.Parent.Children.Remove(item);
                                    //allItems.Remove(item);
                                    removedCount++;
                                    removed[item.ListIndex] = true;
                                    foreach (IncludeItem child in item.Children)
                                    {
                                        toRemove.AddLast(child);
                                    }
                                }
                                //j--;

                                path1[k - 1].Children.Insert(insertAt, item1);
                                item1.Parent = path1[k - 1];

                                break;
                            }
                        }
                    }
                }
            }

            List<Item> newAllItems = new List<Item>(allItems.Count - removedCount);
            for (int i = 0; i < allItems.Count; i++)
                if (!removed[i])
                    newAllItems.Add(allItems[i]);
            allItems = newAllItems;

            //Move the null node to nr [0]
            foreach (IncludeItem item in allItems)
            {
                if (item.Current == null)
                {
                    int itemIndex = item.Parent.Children.IndexOf(item);
                    Item item0 = item.Parent.Children[0];
                    item.Parent.Children[0] = item;
                    item.Parent.Children[itemIndex] = item0;
                    break;
                }
            }

            //Insert method decls and move structs & fields up as needed
            ast.Apply(new Phase2(finalTrans, allItems));

            //Insert the headers in the files

            if (Options.Compiler.OneOutputFile)
            {
                //for (int i = 0; i < allItems.Count; i++)
                int i = 0;
                while (allItems.Count > 0)
                {
                    if (allItems[i] is IncludeItem)
                    {
                        IncludeItem includeItem = (IncludeItem) allItems[i];
                        //Dont want the standard lib
                        if (includeItem.Current == null)
                        {
                            i++;
                            continue;
                        }
                        //If it has children with children, then pick another first
                        if (includeItem.Children.Any(child => child.Children.Count > 0))
                        {
                            i++;
                            continue;
                        }
                        if (includeItem.Children.Count == 0)
                        {
                            if (includeItem.Parent == null)
                                break;
                            i++;
                            continue;
                        }
                        i = 0;
                        //Put all children into this
                        while (includeItem.Children.Count > 0)
                        {
                            int childNr = includeItem.Children.Count - 1;
                            allItems.Remove(includeItem.Children[childNr]);
                            if (includeItem.Children[childNr] is FieldItem)
                            {
                                FieldItem aItem = (FieldItem)includeItem.Children[childNr];
                                Node node = aItem.FieldDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is StructItem)
                            {
                                StructItem aItem = (StructItem)includeItem.Children[childNr];
                                Node node = aItem.StructDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is MethodDeclItem)
                            {
                                MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[childNr];
                                AMethodDecl aNode = new AMethodDecl();
                                if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                                aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                                aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                                foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                                {
                                    AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                    aNode.GetFormals().Add(clone);
                                }
                                includeItem.Current.GetDecl().Insert(0, aNode);
                            }
                            else if (includeItem.Children[childNr] is IncludeItem)
                            {
                                IncludeItem aChild = (IncludeItem)includeItem.Children[childNr];
                                if (aChild.Current == null)
                                {
                                    AIncludeDecl node = new AIncludeDecl(new TInclude("include"),
                                                        new TStringLiteral("\"TriggerLibs/NativeLib\""));
                                    includeItem.Current.GetDecl().Insert(0, node);
                                }
                                else
                                {
                                    PDecl[] decls = new PDecl[aChild.Current.GetDecl().Count];
                                    aChild.Current.GetDecl().CopyTo(decls, 0);
                                    for (int k = decls.Length - 1; k >= 0; k--)
                                    {
                                        includeItem.Current.GetDecl().Insert(0, decls[k]);
                                    }
                                    aChild.Current.Parent().RemoveChild(aChild.Current);
                                    //i = -1;
                                }
                            }
                            includeItem.Children.RemoveAt(childNr);
                        }
                    }
                }
            }
            else
                foreach (IncludeItem includeItem in allItems.OfType<IncludeItem>())
                {
                    for (int i = includeItem.Children.Count - 1; i >= 0; i--)
                    {
                        Node node;
                        if (includeItem.Children[i] is IncludeItem)
                        {
                            IncludeItem aItem = (IncludeItem) includeItem.Children[i];
                            node = new AIncludeDecl(new TInclude("include"),
                                                    new TStringLiteral("\"" + (aItem.Current == null ? "TriggerLibs/NativeLib" : aItem.Current.GetName().Text.Replace("\\", "/")) + "\""));
                            if (aItem.Current == null && finalTrans.mainEntry != null)
                            {
                                //Search for user defined initlib
                                bool foundInvoke = false;
                                foreach (ASimpleInvokeExp invokeExp in finalTrans.data.SimpleMethodLinks.Keys)
                                {
                                    if(invokeExp.GetName().Text == "libNtve_InitLib" && invokeExp.GetArgs().Count == 0)
                                    {
                                        /*finalTrans.errors.Add(new ErrorCollection.Error(invokeExp.GetName(),
                                                                                        Util.GetAncestor<AASourceFile>(
                                                                                            invokeExp),
                                                                                        "You are invoking libNtve_InitLib() yourself somewhere. It will not be auto inserted.",
                                                                                        true));*/
                                        foundInvoke = true;
                                        break;
                                    }
                                }

                                if (!foundInvoke)
                                {
                                    //Init the lib
                                    ASimpleInvokeExp initExp = new ASimpleInvokeExp();
                                    initExp.SetName(new TIdentifier("libNtve_InitLib"));
                                    finalTrans.data.ExpTypes[initExp] = new AVoidType(new TVoid("void"));
                                    foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
                                    {
                                        if (method.GetName().Text == "libNtve_InitLib" && method.GetFormals().Count == 0)
                                        {
                                            finalTrans.data.SimpleMethodLinks[initExp] = method;
                                        }
                                    }
                                    AABlock block = (AABlock) finalTrans.mainEntry.GetBlock();
                                    block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), initExp));
                                }
                            }
                        }
                        else if (includeItem.Children[i] is FieldItem)
                        {
                            FieldItem aItem = (FieldItem)includeItem.Children[i];
                            node = aItem.FieldDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is StructItem)
                        {
                            StructItem aItem = (StructItem)includeItem.Children[i];
                            node = aItem.StructDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is MethodDeclItem)
                        {
                            MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[i];
                            AMethodDecl aNode = new AMethodDecl();
                            if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                            aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                            aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                            foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                            {
                                AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                aNode.GetFormals().Add(clone);
                            }
                            node = aNode;
                        }
                        else
                            throw new Exception("FixIncludes.Apply: Unexpected item type");

                        includeItem.Current.GetDecl().Insert(0, node);
                    }
                }
        }
        public override void OutAAProgram(AAProgram node)
        {
            if (strings.Count == 0)
                return;

            //Obfuscate all strings
            List<string> obfuscated = new List<string>();
            foreach (AStringConstExp stringConstExp in strings)
            {
                TStringLiteral token = stringConstExp.GetStringLiteral();
                string s = token.Text.Substring(1, token.Text.Length - 2);
                obfuscated.Add(Obfuscate(s));
            }

            //Set invokes instead of string constants, and move varaiabes down
            List<AFieldDecl> ignoredFields = new List<AFieldDecl>();
            List<AFieldDecl> moveFieldsIn = new List<AFieldDecl>();
            Dictionary<AFieldDecl, AMethodDecl> fieldMethods = new Dictionary<AFieldDecl, AMethodDecl>();
            for (int i = 0; i < strings.Count; i++)
            {
                AStringConstExp stringExp = strings[i];
                Token token = stringExp.GetStringLiteral();
                bool inDeobfuscator = Util.GetAncestor<AMethodDecl>(stringExp) == finalTrans.data.DeobfuscateMethod;

                if (inDeobfuscator)
                {
                    AFieldDecl field = finalTrans.data.UnobfuscatedStrings[stringExp];

                    AStringConstExp newStringConst = new AStringConstExp(stringExp.GetStringLiteral());

                    field.SetInit(newStringConst);

                    AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                    finalTrans.data.FieldLinks[fieldRef] = field;

                    stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                }
                else
                {
                    AFieldDecl field;
                    if (!finalTrans.data.ObfuscatedStrings.ContainsKey(stringExp))
                    {
                        int line = -finalTrans.data.ObfuscatedStrings.Count - 1;
                        field = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const", line, 0),
                                                new ANamedType(new TIdentifier("string", line, 1), null),
                                                new TIdentifier("Galaxy_pp_stringO" +
                                                                finalTrans.data.ObfuscatedStrings.Count), null);
                        //If the strings are the same - point them to same field
                        bool newField = true;
                        foreach (AStringConstExp oldStringConstExp in finalTrans.data.ObfuscatedStrings.Keys)
                        {
                            if (stringExp.GetStringLiteral().Text == oldStringConstExp.GetStringLiteral().Text)
                            {
                                field = finalTrans.data.ObfuscatedStrings[oldStringConstExp];
                                newField = false;
                                break;
                            }
                        }
                        if (newField)
                        {
                            AASourceFile file = (AASourceFile)finalTrans.data.DeobfuscateMethod.Parent();
                            file.GetDecl().Insert(file.GetDecl().IndexOf(finalTrans.data.DeobfuscateMethod) + 1, field);

                            finalTrans.data.Fields.Add(new SharedData.DeclItem<AFieldDecl>(file, field));
                        }
                        finalTrans.data.ObfuscatedStrings.Add(stringExp, field);

                    }
                    field = finalTrans.data.ObfuscatedStrings[stringExp];
                    string obfuscatedString = obfuscated[i];

                    ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                    invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                   stringExp.GetStringLiteral().Line,
                                                   stringExp.GetStringLiteral().Pos));

                    AStringConstExp newStringConst =
                        new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                    invoke.GetArgs().Add(newStringConst);
                    finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;

                    if (Util.GetAncestor<PStm>(stringExp) == null && false)
                    {
                        ignoredFields.Add(field);
                        /*if (Util.GetAncestor<ASimpleInvokeExp>(stringExp) == null)
                            stringExp.ReplaceBy(invoke);*/
                        //Add obfuscate call to this location);
                        continue;
                        /*ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                        invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                       stringExp.GetStringLiteral().Line,
                                                       stringExp.GetStringLiteral().Pos));

                        AStringConstExp newStringConst =
                            new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                        invoke.GetArgs().Add(newStringConst);
                        stringExp.ReplaceBy(invoke);

                        finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;
                        continue;*/
                    }

                    if (field.GetInit() == null)
                    {
                        /*field.SetInit(invoke);
                        field.SetConst(null);*/

                        if (
                            stringExp.GetStringLiteral().Text.Remove(0, 1).Substring(0,
                                                                                     stringExp.GetStringLiteral().Text.
                                                                                         Length - 2) == "")
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    return "";
                                }
                             *
                             */
                            ANullExp nullExp = new ANullExp();

                            field.SetInit(nullExp);
                            field.SetConst(null);

                            AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\"\""));
                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 stringConst)
                                                                         },
                                                                     new TRBrace("}")));

                            AASourceFile pFile = (AASourceFile)field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);
                            finalTrans.data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null);
                            finalTrans.data.ExpTypes[nullExp] = new ANamedType(new TIdentifier("null"), null);

                            fieldMethods[field] = method;
                        }
                        else
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    if (field == null)
                                    {
                                        field = Invoke;
                                    }
                                    if (field == null)
                                    {
                                        return Invoke;
                                    }
                                    return field;
                                }
                             */

                            ANullExp nullExp1 = new ANullExp();

                            field.SetInit(nullExp1);
                            field.SetConst(null);

                            ANullExp nullExp2 = new ANullExp();
                            AFieldLvalue fieldRef1 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef2 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef3 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef1Exp = new ALvalueExp(fieldRef1);
                            ALvalueExp fieldRef3Exp = new ALvalueExp(fieldRef3);
                            ABinopExp binop1 = new ABinopExp(fieldRef1Exp, new AEqBinop(new TEq("==")), nullExp2);
                            AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef2, invoke);

                            AIfThenStm ifStm1 = new AIfThenStm(new TLParen("("), binop1,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AExpStm(new TSemicolon(";"),
                                                                                                    assignment)
                                                                                    },
                                                                                new TRBrace("}"))));

                            /*ANullExp nullExp3 = new ANullExp();
                            AFieldLvalue fieldRef4 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef4Exp = new ALvalueExp(fieldRef4);
                            AStringConstExp invokeArgClone =
                                new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                            ASimpleInvokeExp invokeClone = new ASimpleInvokeExp(new TIdentifier(invoke.GetName().Text),
                                                                                new ArrayList() { invokeArgClone });
                            finalTrans.data.SimpleMethodLinks[invokeClone] = finalTrans.data.DeobfuscateMethod;
                            ABinopExp binop2 = new ABinopExp(fieldRef4Exp, new AEqBinop(new TEq("==")), nullExp3);

                            AIfThenStm ifStm2 = new AIfThenStm(new TLParen("("), binop2,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AValueReturnStm(new TReturn("return"), invokeClone)
                                                                                    },
                                                                                new TRBrace("}"))));*/

                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             ifStm1,
                                                                             //ifStm2,
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 fieldRef3Exp)
                                                                         },
                                                                     new TRBrace("}")));
                            AASourceFile pFile = (AASourceFile) field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);

                            finalTrans.data.FieldLinks[fieldRef1] =
                                finalTrans.data.FieldLinks[fieldRef2] =
                                finalTrans.data.FieldLinks[fieldRef3] =
                                /*finalTrans.data.FieldLinks[fieldRef4] = */field;
                            finalTrans.data.LvalueTypes[fieldRef1] =
                                finalTrans.data.LvalueTypes[fieldRef2] =
                                finalTrans.data.LvalueTypes[fieldRef3] =
                                //finalTrans.data.LvalueTypes[fieldRef4] =
                                finalTrans.data.ExpTypes[fieldRef1Exp] =
                                finalTrans.data.ExpTypes[fieldRef3Exp] =
                                //finalTrans.data.ExpTypes[fieldRef4Exp] =
                                finalTrans.data.ExpTypes[assignment] = field.GetType();

                            finalTrans.data.ExpTypes[nullExp1] =
                                finalTrans.data.ExpTypes[nullExp2] =
                                /*finalTrans.data.ExpTypes[nullExp3] =*/ new ANamedType(new TIdentifier("null"), null);
                            finalTrans.data.ExpTypes[binop1] =
                                /*finalTrans.data.ExpTypes[binop2] = */new ANamedType(new TIdentifier("bool"), null);

                            fieldMethods[field] = method;
                        }

                        /* AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                         finalTrans.data.FieldLinks[fieldRef] = field;*/

                        //stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                    }
                    ASimpleInvokeExp invoke2 =
                            new ASimpleInvokeExp(new TIdentifier(fieldMethods[field].GetName().Text), new ArrayList());
                    finalTrans.data.SimpleMethodLinks[invoke2] = fieldMethods[field];
                    stringExp.ReplaceBy(invoke2);

                    //If we are in a field, move it in
                    if (Util.GetAncestor<AFieldDecl>(invoke2) != null)
                        moveFieldsIn.Add(Util.GetAncestor<AFieldDecl>(invoke2));
                }
            }

            foreach (AFieldDecl field in finalTrans.data.ObfuscationFields)
            {
                if (field.GetInit() == null && field.Parent() != null)
                {
                    field.Parent().RemoveChild(field);
                }
            }

            //A constant field, or a field used by a constant field cannot be moved in
            List<AFieldDecl> constantFields = new List<AFieldDecl>();
            foreach (SharedData.DeclItem<AFieldDecl> field in finalTrans.data.Fields)
            {
                if (field.Decl.GetConst() != null)
                    constantFields.Add(field.Decl);
            }
            for (int i = 0; i < constantFields.Count; i++)
            {
                GetFieldLvalues lvalues = new GetFieldLvalues();
                constantFields[i].Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl field = finalTrans.data.FieldLinks[lvalue];
                    if (!constantFields.Contains(field))
                        constantFields.Add(field);
                }
            }
            moveFieldsIn.RemoveAll(constantFields.Contains);
            Dictionary<AFieldDecl, List<AFieldDecl>> dependancies = new Dictionary<AFieldDecl, List<AFieldDecl>>();
            //Order the fields so any dependancies are instansiated first
            foreach (AFieldDecl field in moveFieldsIn)
            {
                dependancies.Add(field, new List<AFieldDecl>());
                GetFieldLvalues lvalues = new GetFieldLvalues();
                field.Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl dependancy = finalTrans.data.FieldLinks[lvalue];
                    if (!dependancies[field].Contains(dependancy))
                        dependancies[field].Add(dependancy);
                }
            }
            List<PStm> newStatements = new List<PStm>();
            while (dependancies.Keys.Count > 0)
            {
                AFieldDecl field = dependancies.FirstOrDefault(f1 => f1.Value.Count == 0).Key ??
                                   dependancies.Keys.First(f => true);

                AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef, field.GetInit());
                field.SetInit(null);

                newStatements.Add(new AExpStm(new TSemicolon(";"), assignment));

                finalTrans.data.FieldLinks[fieldRef] = field;
                finalTrans.data.LvalueTypes[fieldRef] =
                    finalTrans.data.ExpTypes[assignment] = field.GetType();

                foreach (KeyValuePair<AFieldDecl, List<AFieldDecl>> dependancy in dependancies)
                {
                    if (dependancy.Value.Contains(field))
                        dependancy.Value.Remove(field);
                }

                dependancies.Remove(field);
            }
            AABlock initBody = (AABlock) finalTrans.mainEntry.GetBlock();
            for (int i = newStatements.Count - 1; i >= 0; i--)
            {
                initBody.GetStatements().Insert(0, newStatements[i]);
            }
        }
        public override void CaseANonstaticInvokeExp(ANonstaticInvokeExp node)
        {
            PExp reciever = node.GetReceiver();
            PType type = finalTrans.data.ExpTypes[reciever];

            //If the reciever is not a var, put it in a new var.
            if (!(reciever is ALvalueExp))
            {
                AALocalDecl localDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(type, data), new TIdentifier("nonstaticInvokeVar"), reciever);
                ALocalLvalue localRef = new ALocalLvalue(new TIdentifier("nonstaticInvokeVar"));
                ALvalueExp localRefExp = new ALvalueExp(localRef);
                node.SetReceiver(localRefExp);
                PStm pStm = Util.GetAncestor<PStm>(node);
                AABlock pBlock = (AABlock) pStm.Parent();
                pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), new ALocalDeclStm(new TSemicolon(";"), localDecl));
                reciever = localRefExp;

                data.LvalueTypes[localRef] =
                    data.ExpTypes[localRefExp] = type;
                data.LocalLinks[localRef] = localDecl;

                localDecl.Apply(this);
            }

            if (type is ANamedType && finalTrans.data.StructTypeLinks.ContainsKey((ANamedType)type))
            {
                //ANamedType type = (ANamedType) finalTrans.data.ExpTypes[reciever];
                if (finalTrans.data.StructTypeLinks[(ANamedType) type].GetClassToken() != null)
                {
                    //Pass the pointer
                    ALvalueExp lvalueExp = (ALvalueExp) reciever;
                    APointerLvalue pointerLvalue = (APointerLvalue) lvalueExp.GetLvalue();
                    reciever = pointerLvalue.GetBase();
                }

                AMethodDecl method = finalTrans.data.StructMethodLinks[node];
                ASimpleInvokeExp simpleInvoke = new ASimpleInvokeExp();
                simpleInvoke.SetName(node.GetName());
                PExp[] exps = new PExp[node.GetArgs().Count];
                node.GetArgs().CopyTo(exps, 0);
                foreach (PExp exp in exps)
                {
                    simpleInvoke.GetArgs().Add(exp);
                }
                simpleInvoke.GetArgs().Add(reciever);
                node.ReplaceBy(simpleInvoke);
                finalTrans.data.SimpleMethodLinks[simpleInvoke] = method;
                finalTrans.data.StructMethodLinks.Remove(node);
                finalTrans.data.ExpTypes[simpleInvoke] = method.GetReturnType();
                finalTrans.data.ExpTypes.Remove(node);
                simpleInvoke.Apply(this);
            }
            else
            {//Enrichment
                /*AEnrichmentDecl enrichment = finalTrans.data.EnrichmentTypeLinks[type];

                foreach (AEnrichmentDecl enrichmentDecl in finalTrans.data.Enrichments)
                {
                    if (Util.IsVisible(node, enrichmentDecl) &&
                        Util.IsDeclVisible(enrichmentDecl, Util.GetAncestor<AASourceFile>(node)) &&
                        Util.TypesEqual(type, enrichmentDecl.GetType(), finalTrans.data))
                    {
                        enrichment = enrichmentDecl;
                        break;
                    }
                }
                if (enrichment == null)
                {
                    finalTrans.errors.Add(new ErrorCollection.Error(node.GetName(), "TransFormMethodDecls.NonStaticInvoke: Expected enrichment - this is a bug. It should have been caught earlier"));
                    throw new ParserException(node.GetName(), "");
                }*/
                AMethodDecl method = finalTrans.data.StructMethodLinks[node];
                ASimpleInvokeExp simpleInvoke = new ASimpleInvokeExp();
                simpleInvoke.SetName(node.GetName());
                PExp[] exps = new PExp[node.GetArgs().Count];
                node.GetArgs().CopyTo(exps, 0);
                foreach (PExp exp in exps)
                {
                    simpleInvoke.GetArgs().Add(exp);
                }
                simpleInvoke.GetArgs().Add(reciever);
                node.ReplaceBy(simpleInvoke);
                finalTrans.data.SimpleMethodLinks[simpleInvoke] = method;
                finalTrans.data.StructMethodLinks.Remove(node);
                finalTrans.data.ExpTypes[simpleInvoke] = method.GetReturnType();
                finalTrans.data.ExpTypes.Remove(node);
                simpleInvoke.Apply(this);

            }
        }