code:
/* Runtime Condenser by Nodrak
 * This will sum up identical runtimes into one, giving a total of how many times it occured. The first occurance
 * of the runtime will log the proc, source, usr and src, the rest will just add to the total. Infinite loops will
 * also be caught and displayed (if any) above the list of runtimes.
 *
 * How to use:
 * 1) Copy and paste your list of runtimes from Dream Daemon into input.exe
 * 2) Run RuntimeCondenser.exe
 * 3) Open output.txt for a condensed report of the runtimes
 */

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//Make all of these global. It's bad yes, but it's a small program so it really doesn't affect anything.
	//Because hardcoded numbers are bad :(
	const unsigned short maxStorage = 99; //100 - 1

	//What we use to read input
	string currentLine = "Blank";
	string nextLine = "Blank";

	//Stores lines we want to keep to print out
	string storedRuntime[maxStorage+1];
	string storedProc[maxStorage+1];
	string storedSource[maxStorage+1];
	string storedUsr[maxStorage+1];
	string storedSrc[maxStorage+1];

	//Stat tracking stuff for output
	unsigned int totalRuntimes = 0;
	unsigned int totalUniqueRuntimes = 0;
	unsigned int totalInfiniteLoops = 0;
	unsigned int totalUniqueInfiniteLoops = 0;

	//Misc
	unsigned int numRuntime[maxStorage+1]; //Number of times a specific runtime has occured
	bool checkNextLines = false; //Used in case byond has condensed a large number of similar runtimes
	int storedIterator = 0; //Used to remember where we stored the runtime

bool readFromFile()
{
	//Open file to read
	ifstream inputFile("input.txt");

	if(inputFile.is_open())
	{
		while(!inputFile.eof()) //Until end of file
		{
			//If we've run out of storage
			if(storedRuntime[maxStorage] != "Blank") break;

			//Update our lines
			currentLine	= nextLine;
			getline(inputFile, nextLine);

			//After finding a new runtime, check to see if there are extra values to store
			if(checkNextLines)
			{
				//Skip ahead
				currentLine = nextLine;
				getline(inputFile, nextLine);

				//If we find this, we have new stuff to store
				if(nextLine.find("usr:") != std::string::npos)
				{
					//Store more info
					storedSource[storedIterator] = currentLine;
					storedUsr[storedIterator] = nextLine;

					//Skip ahead again
					currentLine = nextLine;
					getline(inputFile, nextLine);

					//Store the last of the info
					storedSrc[storedIterator] = nextLine;
				}
				checkNextLines = false;
			}

			//Found an infinite loop!
			if(currentLine.find("Infinite loop suspected") != std::string::npos || currentLine.find("Maximum recursion level reached") != std::string::npos)
			{
				totalInfiniteLoops++;

				for(int i=0; i <= maxStorage; i++)
				{
					//We've already encountered this
					if(currentLine == storedRuntime[i])
					{
						numRuntime[i]++;
						break;
					}

					//We've never encoutnered this
					if(storedRuntime[i] == "Blank")
					{
						storedRuntime[i] = currentLine;
						currentLine = nextLine;
						getline(inputFile, nextLine); //Skip the "if this is not an infinite loop" line
						storedProc[i] = nextLine;
						numRuntime[i] = 1;
						checkNextLines = true;
						storedIterator = i;
						totalUniqueInfiniteLoops++;
						break;
					}
				}
			}
			//Found a runtime!
			else if(currentLine.find("runtime error:") != std::string::npos)
			{
				totalRuntimes++;
				for(int i=0; i <= maxStorage; i++)
				{
					//We've already encountered this
					if(currentLine == storedRuntime[i])
					{
						numRuntime[i]++;
						break;
					}

					//We've never encoutnered this
					if(storedRuntime[i] == "Blank")
					{
						storedRuntime[i] = currentLine;
						storedProc[i] = nextLine;
						numRuntime[i] = 1;
						checkNextLines = true;
						storedIterator = i;
						totalUniqueRuntimes++;
						break;
					}
				}
			}
		}
	}
	else
	{
		return false;
	}
	return true;
}

bool writeToFile()
{
	//Open and clear the file
	ofstream outputFile("Output.txt", ios::trunc);

	if(outputFile.is_open())
	{
		outputFile << "Note: The proc name, source file, src and usr are all from the FIRST of the identical runtimes. Everything else is cropped.\n\n";
		if(totalUniqueInfiniteLoops > 0)
		{
			outputFile << "Total unique infinite loops: " << totalUniqueInfiniteLoops << endl;
		}
		if(totalInfiniteLoops > 0)
		{
			outputFile << "Total infinite loops: " << totalInfiniteLoops << endl;
		}
		outputFile << "Total unique runtimes: " << totalUniqueRuntimes << endl;
		outputFile << "Total runtimes: " << totalRuntimes << endl << endl;

		//Display a warning if we've hit the maximum space we've allocated for storage
		if(totalUniqueRuntimes + totalUniqueInfiniteLoops >= maxStorage)
		{
			outputFile << "Warning: The maximum number of unique runtimes has been hit. If there were more, they have been cropped out.\n\n";
		}

		//If we have infinite loops, display them first.
		if(totalInfiniteLoops > 0)
		{
			outputFile << "** Infinite loops **";
			for(int i=0; i <= maxStorage; i++)
			{
				if(storedRuntime[i].find("Infinite loop suspected") != std::string::npos || storedRuntime[i].find("Maximum recursion level reached") != std::string::npos)
				{
					if(numRuntime[i] != 0) outputFile << endl << endl << "The following infinite loop has occured " << numRuntime[i] << " time(s).\n";
					if(storedRuntime[i] != "Blank") outputFile << storedRuntime[i] << endl;
					if(storedProc[i] != "Blank") outputFile << storedProc[i] << endl;
					if(storedSource[i] != "Blank") outputFile << storedSource[i] << endl;
					if(storedUsr[i] != "Blank") outputFile << storedUsr[i] << endl;
					if(storedSrc[i] != "Blank") outputFile << storedSrc[i] << endl;
				}
			}
			outputFile << endl << endl; //For spacing
		}

		//Do runtimes next
		outputFile << "** Runtimes **";
		for(int i=0; i <= maxStorage; i++)
		{
			if(storedRuntime[i].find("Infinite loop suspected") != std::string::npos || storedRuntime[i].find("Maximum recursion level reached") != std::string::npos) continue;

			if(numRuntime[i] != 0) outputFile << endl << endl << "The following runtime has occured " << numRuntime[i] << " time(s).\n";
			if(storedRuntime[i] != "Blank") outputFile << storedRuntime[i] << endl;
			if(storedProc[i] != "Blank") outputFile << storedProc[i] << endl;
			if(storedSource[i] != "Blank") outputFile << storedSource[i] << endl;
			if(storedUsr[i] != "Blank") outputFile << storedUsr[i] << endl;
			if(storedSrc[i] != "Blank") outputFile << storedSrc[i] << endl;
		}
		outputFile.close();
	}
	else
	{
		return false;
	}
	return true;
}

void sortRuntimes()
{
	string tempRuntime[maxStorage+1];
	string tempProc[maxStorage+1];
	string tempSource[maxStorage+1];
	string tempUsr[maxStorage+1];
	string tempSrc[maxStorage+1];
	unsigned int tempNumRuntime[maxStorage+1];
	unsigned int highestCount = 0; //Used for descending order
//	int keepLooping = 0;

	//Move all of our data into temporary arrays. Also clear the stored data (not necessary but.. just incase)
	for(int i=0; i <= maxStorage; i++)
	{
		//Get the largest occurance of a single runtime
		if(highestCount < numRuntime[i])
		{
			highestCount = numRuntime[i];
		}

		tempRuntime[i] = storedRuntime[i];	storedRuntime[i] = "Blank";
		tempProc[i] = storedProc[i];		storedProc[i] = "Blank";
		tempSource[i] = storedSource[i];	storedSource[i] = "Blank";
		tempUsr[i] = storedUsr[i];			storedUsr[i] = "Blank";
		tempSrc[i] = storedSrc[i];			storedSrc[i] = "Blank";
		tempNumRuntime[i] = numRuntime[i];	numRuntime[i] = 0;
	}

	while(highestCount > 0)
	{
		for(int i=0; i <= maxStorage; i++) //For every runtime
		{
			if(tempNumRuntime[i] == highestCount) //If the number of occurances of that runtime is equal to our current highest
			{
				for(int j=0; j <= maxStorage; j++) //Find the next available slot and store the info
				{
					if(storedRuntime[j] == "Blank") //Found an empty spot
					{
						storedRuntime[j] = tempRuntime[i];
						storedProc[j] = tempProc[i];
						storedSource[j] = tempSource[i];
						storedUsr[j] = tempUsr[i];
						storedSrc[j] = tempSrc[i];
						numRuntime[j] = tempNumRuntime[i];
						break;
					}
				}
			}
		}
		highestCount--; //Lower our 'highest' by one and continue
	}
}

int main() {
	char exit; //Used to stop the program from immediatly exiting

	//Start everything fresh. "Blank" should never occur in the runtime logs on its own.
	for(int i=0; i <= maxStorage; i++)
	{
		storedRuntime[i] = "Blank";
		storedProc[i] = "Blank";
		storedSource[i] = "Blank";
		storedUsr[i] = "Blank";
		storedSrc[i] = "Blank";
		numRuntime[i] = 0;

	}

	if(readFromFile())
	{
		cout << "Input read successfully!\n";
	}
	else
	{
		cout << "Input failed to open, shutting down.\n";
		cout << "\nEnter any letter to quit.\n";
		cin >> exit;
		return 1;
	}

	sortRuntimes();

	if(writeToFile())
	{
		cout << "Output was successful!\n";
		cout << "\nEnter any letter to quit.\n";
		cin >> exit;
		return 0;
	}
	else
	{
		cout << "The output file could not be opened, shutting down.\n";
		cout << "\nEnter any letter to quit.\n";
		cin >> exit;
		return 0;
	}

	return 0;
}

path: tools/Runtime Condenser/Main.cpp

license: mit


code:
Note: The proc name, source file, src and usr are all from the FIRST of the identical runtimes. Everything else is cropped.

Total unique runtimes: 25
Total runtimes: 767

** Runtimes **

The following runtime has occured 269 time(s).
runtime error: Cannot read null.viruses
proc name: cure (/datum/disease/proc/cure)
  source file: disease.dm,156
  usr: null
  src: Space Retrovirus (/datum/disease/dnaspread)

The following runtime has occured 199 time(s).
runtime error: Cannot read null.has_gravity
proc name: throw at (/atom/movable/proc/throw_at)
  source file: throwing.dm,194
  usr: Reese Marcotte (/mob/living/carbon/human)
  src: Reese Marcotte (/mob/living/carbon/human)

The following runtime has occured 165 time(s).
runtime error: Cannot read null.slot_flags
proc name: db click (/mob/living/carbon/human/db_click)
  source file: inventory.dm,1083
  usr: Puke Chunks (/mob/living/carbon/human)
  src: Puke Chunks (/mob/living/carbon/human)

The following runtime has occured 25 time(s).
runtime error: Cannot read null.flags
proc name: relaymove (/obj/effect/dummy/spell_jaunt/relaymove)

The following runtime has occured 24 time(s).
runtime error: Cannot read null.len
proc name: mergeRecordLists (/proc/mergeRecordLists)
  source file: helpers.dm,260
  usr: Wintermute (/mob/living/silicon/ai)
  src: null

The following runtime has occured 20 time(s).
runtime error: Cannot read null.total_volume
proc name: attackby (/obj/machinery/reagentgrinder/attackby)
  source file: Chemistry-Machinery.dm,751
  usr: Reese Marcotte (/mob/living/carbon/human)
  src: All-In-One Grinder (/obj/machinery/reagentgrinder)

The following runtime has occured 16 time(s).
runtime error: Cannot read null.broadcasting
proc name: radio menu (/mob/living/silicon/robot/proc/radio_menu)
  source file: robot.dm,857
  usr: Engineering Cyborg -432 (/mob/living/silicon/robot)
  src: Engineering Cyborg -432 (/mob/living/silicon/robot)

The following runtime has occured 7 time(s).
runtime error: unexpected stat
proc name: Stat (/mob/living/silicon/robot/Stat)
  source file: robot.dm,227
  usr: Michigan Slim (/mob/living/carbon/human)
  src: Engineering Cyborg -133 (/mob/living/silicon/robot)

The following runtime has occured 7 time(s).
runtime error: Cannot read null.current
proc name: check completion (/datum/objective/download/check_completion)
  source file: objective.dm,411
  usr: null
  src: /datum/objective/download (/datum/objective/download)

The following runtime has occured 6 time(s).
runtime error: Cannot create objects of type null.
proc name: Topic (/obj/machinery/computer/rdconsole/Topic)
  source file: rdconsole.dm,381
  usr: Matthew Hoff (/mob/living/carbon/human)
  src: Core R&D Console (/obj/machinery/computer/rdconsole/core)

The following runtime has occured 6 time(s).
runtime error: Cannot read null.fields
proc name: mergeRecordLists (/proc/mergeRecordLists)
  source file: helpers.dm,263
  usr: Wintermute (/mob/living/silicon/ai)
  src: null

The following runtime has occured 3 time(s).
runtime error: undefined variable /client/var/loc
proc name: get turf (/proc/get_turf)
  source file: helper_procs.dm,38
  usr: the ghost (/mob/dead/observer)
  src: null

The following runtime has occured 3 time(s).
runtime error: Cannot read null.nodes
proc name: merge powernets (/datum/powernet/proc/merge_powernets)
  source file: power.dm,401
  usr: Darin Keppel (/mob/living/carbon/human)
  src: /datum/powernet (/datum/powernet)

The following runtime has occured 3 time(s).
runtime error: Cannot read null.reagents
proc name: fire syringe (/obj/item/weapon/gun/syringe/proc/fire_syringe)

The following runtime has occured 2 time(s).
runtime error: undefined proc or verb /obj/machinery/space_heater/attack().

The following runtime has occured 2 time(s).
runtime error: list index out of bounds
proc name: mergeConnectedNetworksOnTurf (/obj/structure/cable/proc/mergeConnectedNetworksOnTurf)
  source file: cable.dm,520
  usr: Josue Sandford (/mob/living/carbon/human)
  src: the power cable (/obj/structure/cable)

The following runtime has occured 2 time(s).
runtime error: Cannot read null.loc
proc name: Life (/mob/living/simple_animal/corgi/Ian/Life)
  source file: corgi.dm,304
  usr: null
  src: Captain Ian (/mob/living/simple_animal/corgi/Ian)

The following runtime has occured 1 time(s).
runtime error: undefined proc or verb /obj/machinery/portable_atmospherics/canister/toxins/attack().

The following runtime has occured 1 time(s).
runtime error: undefined variable /datum/preferences/var/fields
proc name: Topic (/obj/machinery/computer/cloning/Topic)
  source file: cloning.dm,370
  usr: Logan Graves (/mob/living/carbon/human)
  src: Cloning console (/obj/machinery/computer/cloning)

The following runtime has occured 1 time(s).
runtime error: undefined variable /turf/simulated/floor/plating/var/mineral
proc name: attackby (/turf/simulated/wall/attackby)
  source file: turf.dm,600
  usr: Monte Smail (/mob/living/carbon/human)
  src: the plating (176,172,5) (/turf/simulated/floor/plating)

The following runtime has occured 1 time(s).
runtime error: Cannot read null.blood_DNA
proc name: update inv w uniform (/mob/living/carbon/human/update_inv_w_uniform)
  source file: update_icons.dm,372
  usr: null
  src: Chip Harshman (/mob/living/carbon/human)

The following runtime has occured 1 time(s).
runtime error: Cannot execute null.dropped().
proc name: drop l hand (/mob/proc/drop_l_hand)
  source file: inventory.dm,104
  usr: Jeb Stone (/mob/living/carbon/human)
  src: Jeb Stone (/mob/living/carbon/human)

The following runtime has occured 1 time(s).
runtime error: Cannot read null.w_class
proc name: attackby (/obj/item/weapon/storage/attackby)
  source file: storage.dm,187
  usr: Samuel York (/mob/living/carbon/human)
  src: the backpack (/obj/item/weapon/storage/backpack)

The following runtime has occured 1 time(s).
runtime error: Cannot read null.amount
proc name: attackby (/obj/machinery/constructable_frame/machine_frame/attackby)
  source file: constructable_frame.dm,27
  usr: Quinton Bould (/mob/living/carbon/human)
  src: the machine frame (/obj/machinery/constructable_frame/machine_frame)

The following runtime has occured 1 time(s).
runtime error: Cannot modify null.status.
proc name: death (/mob/living/silicon/robot/death)

path: tools/Runtime Condenser/Output.txt


code:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnstandardnessTestForDM", "UnstandardnessTestForDM\UnstandardnessTestForDM.csproj", "{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|x86 = Debug|x86
		Release|x86 = Release|x86
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}.Debug|x86.ActiveCfg = Debug|x86
		{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}.Debug|x86.Build.0 = Debug|x86
		{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}.Release|x86.ActiveCfg = Release|x86
		{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}.Release|x86.Build.0 = Release|x86
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


code:
namespace UnstandardnessTestForDM
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.panel1 = new System.Windows.Forms.Panel();
            this.listBox2 = new System.Windows.Forms.ListBox();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(222, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Locate all #defines";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // listBox1
            //
            this.listBox1.FormattingEnabled = true;
            this.listBox1.Location = new System.Drawing.Point(12, 82);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(696, 160);
            this.listBox1.TabIndex = 1;
            this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
            //
            // panel1
            //
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel1.Controls.Add(this.listBox2);
            this.panel1.Controls.Add(this.label4);
            this.panel1.Controls.Add(this.label3);
            this.panel1.Controls.Add(this.label2);
            this.panel1.Controls.Add(this.label1);
            this.panel1.Location = new System.Drawing.Point(12, 297);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(696, 244);
            this.panel1.TabIndex = 2;
            //
            // listBox2
            //
            this.listBox2.FormattingEnabled = true;
            this.listBox2.Location = new System.Drawing.Point(8, 71);
            this.listBox2.Name = "listBox2";
            this.listBox2.Size = new System.Drawing.Size(683, 160);
            this.listBox2.TabIndex = 4;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(5, 55);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(69, 13);
            this.label4.TabIndex = 3;
            this.label4.Text = "Referenced: ";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(5, 42);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(40, 13);
            this.label3.TabIndex = 2;
            this.label3.Text = "Value: ";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(5, 29);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(61, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "Defined in: ";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            this.label1.Location = new System.Drawing.Point(3, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(79, 29);
            this.label1.TabIndex = 0;
            this.label1.Text = "label1";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(9, 38);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(81, 13);
            this.label5.TabIndex = 3;
            this.label5.Text = "Files searched: ";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(720, 553);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.listBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Unstandardness Test For DM";
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        public System.Windows.Forms.ListBox listBox2;
        public System.Windows.Forms.Label label5;
        public System.Windows.Forms.ListBox listBox1;
    }
}


code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;

namespace UnstandardnessTestForDM
{
    public partial class Form1 : Form
    {
        DMSource source;

        public Form1()
        {
            InitializeComponent();
            source = new DMSource();
            source.mainform = this;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            source.find_all_defines();
            generate_define_report();
        }

        public void generate_define_report()
        {

            TextWriter tw = new StreamWriter("DEFINES REPORT.txt");

            tw.WriteLine("Unstandardness Test For DM report for DEFINES");
            tw.WriteLine("Generated on " + DateTime.Now);
            tw.WriteLine("Total number of defines " + source.defines.Count());
            tw.WriteLine("Total number of Files " + source.filessearched);
            tw.WriteLine("Total number of references " + source.totalreferences);
            tw.WriteLine("Total number of errorous defines " + source.errordefines);
            tw.WriteLine("------------------------------------------------");

            foreach (Define d in source.defines)
            {
                tw.WriteLine(d.name);
                tw.WriteLine("\tValue: " + d.value);
                tw.WriteLine("\tComment: " + d.comment);
                tw.WriteLine("\tDefined in: " + d.location + " : " + d.line);
                tw.WriteLine("\tNumber of references: " + d.references.Count());
                foreach (String s in d.references)
                {
                    tw.WriteLine("\t\t" + s);
                }
            }

            tw.WriteLine("------------------------------------------------");
            tw.WriteLine("SUCCESS");

            tw.Close();

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Define d = (Define)listBox1.Items[listBox1.SelectedIndex];
                label1.Text = d.name;
                label2.Text = "Defined in: " + d.location + " : " + d.line;
                label3.Text = "Value: " + d.value;
                label4.Text = "References: " + d.references.Count();
                listBox2.Items.Clear();
                foreach (String s in d.references)
                {
                    listBox2.Items.Add(s);
                }

            }
            catch (Exception ex) { Console.WriteLine("ERROR HERE: " + ex.Message); }
        }

    }

    public class DMSource
    {
        public List<Define> defines;
        public const int FLAG_DEFINE = 1;
        public Form1 mainform;

        public int filessearched = 0;
        public int totalreferences = 0;
        public int errordefines = 0;

        public List<String> filenames;

        public DMSource()
        {
            defines = new List<Define>();
            filenames = new List<String>();
        }

        public void find_all_defines()
        {
            find_all_files();
            foreach(String filename in filenames){
                searchFileForDefines(filename);
            }

        }

        public void find_all_files()
        {
            filenames = new List<String>();
            String dmefilename = "";

            foreach (string f in Directory.GetFiles("."))
            {
                if (f.ToLower().EndsWith(".dme"))
                {
                    dmefilename = f;
                    break;
                }
            }

            if (dmefilename.Equals(""))
            {
                MessageBox.Show("dme file not found");
                return;
            }

            using (var reader = File.OpenText(dmefilename))
            {
                    String s;
                    while (true)
                    {
                        s = reader.ReadLine();

                        if (!(s is String))
                            break;

                        if (s.StartsWith("#include"))
                        {
                            int start = s.IndexOf("\"")+1;
                            s = s.Substring(start, s.Length - 11);

                            if (s.EndsWith(".dm"))
                            {
                                filenames.Add(s);
                            }
                        }

                        s = s.Trim(' ');
                        if (s == "") { continue; }
                    }
                reader.Close();
            }
        }

        public void DirSearch(string sDir, int flag)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d))
                    {
                        if (f.ToLower().EndsWith(".dm"))
                        {
                            if ((flag & FLAG_DEFINE) > 0)
                            {
                                searchFileForDefines(f);
                            }
                        }
                    }
                    DirSearch(d, flag);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine("ERROR IN DIRSEARCH");
                Console.WriteLine(excpt.Message);
                Console.WriteLine(excpt.Data);
                Console.WriteLine(excpt.ToString());
                Console.WriteLine(excpt.StackTrace);
                Console.WriteLine("END OF ERROR IN DIRSEARCH");
            }
        }

        //DEFINES
        public void searchFileForDefines(String fileName)
        {
            filessearched++;
            FileInfo f = new FileInfo(fileName);
            List<String> lines = new List<String>();
            List<String> lines_without_comments = new List<String>();

            mainform.label5.Text = "Files searched: " + filessearched + "; Defines found: " + defines.Count() + "; References found: " + totalreferences + "; Errorous defines: " + errordefines;
            mainform.label5.Refresh();

            //This code segment reads the file and stores it into the lines variable.
            using (var reader = File.OpenText(fileName))
            {
                try
                {
                    String s;
                    while (true)
                    {
                        s = reader.ReadLine();
                        lines.Add(s);
                        s = s.Trim(' ');
                        if (s == "") { continue; }
                    }
                }
                catch { }
                reader.Close();
            }

            mainform.listBox1.Items.Add("ATTEMPTING: " + fileName);
            lines_without_comments = remove_comments(lines);

            /*TextWriter tw = new StreamWriter(fileName);
            foreach (String s in lines_without_comments)
            {
                tw.WriteLine(s);
            }
            tw.Close();
            mainform.listBox1.Items.Add("REWRITE: "+fileName);*/

            try
            {
                for (int i = 0; i < lines_without_comments.Count; i++)
                {
                    String line = lines_without_comments[i];

                    if (!(line is string))
                        continue;

                    //Console.WriteLine("LINE: " + line);

                    foreach (Define define in defines)
                    {

                        if (line.IndexOf(define.name) >= 0)
                        {
                            define.references.Add(fileName + " : " + i);
                            totalreferences++;
                        }
                    }

                    if( line.ToLower().IndexOf("#define") >= 0 )
                    {
                        line = line.Trim();
                        line = line.Replace('\t', ' ');
                        //Console.WriteLine("LINE = "+line);
                        String[] slist = line.Split(' ');
                        if(slist.Length >= 3){
                            //slist[0] has the value of "#define"
                            String name = slist[1];
                            String value = slist[2];

                            for (int j = 3; j < slist.Length; j++)
                            {
                                value += " " + slist[j];
                                //Console.WriteLine("LISTITEM["+j+"] = "+slist[j]);
                            }

                            value = value.Trim();

                            String comment = "";

                            if (value.IndexOf("//") >= 0)
                            {
                                comment = value.Substring(value.IndexOf("//"));
                                value = value.Substring(0, value.IndexOf("//"));
                            }

                            comment = comment.Trim();
                            value = value.Trim();

                            Define d = new Define(fileName,i,name,value,comment);
                            defines.Add(d);
                            mainform.listBox1.Items.Add(d);
                            mainform.listBox1.Refresh();
                        }else{
                            Define d = new Define(fileName, i, "ERROR ERROR", "Something went wrong here", line);
                            errordefines++;
                            defines.Add(d);
                            mainform.listBox1.Items.Add(d);
                            mainform.listBox1.Refresh();
                        }
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                MessageBox.Show("Exception: " + e.Message + " | " + e.ToString());
            }
        }

        bool iscomment = false;
        int ismultilinecomment = 0;
        bool isstring = false;
        bool ismultilinestring = false;
        int escapesequence = 0;
        int stringvar = 0;

        public List<String> remove_comments(List<String> lines)
        {
            List<String> r = new List<String>();

            iscomment = false;
            ismultilinecomment = 0;
            isstring = false;
            ismultilinestring = false;

            bool skiponechar = false; //Used so the / in */ doesn't get written;

            for (int i = 0; i < lines.Count(); i++)
            {

                String line = lines[i];

                if (!(line is String))
                    continue;

                iscomment = false;
                isstring = false;
                char ca = ' ';
                escapesequence = 0;

                String newline = "";

                int k = line.Length;

                for (int j = 0; j < k; j++)
                {

                    char c = line.ToCharArray()[j];

                    if (escapesequence == 0)
                        if (normalstatus())
                        {
                            if (ca == '/' && c == '/')
                            {
                                c = ' ';
                                iscomment = true;

                                newline = newline.Remove(newline.Length - 1);
                                k = line.Length;
                            }
                            if (ca == '/' && c == '*')
                            {
                                c = ' ';
                                ismultilinecomment = 1;
                                newline = newline.Remove(newline.Length - 1);
                                k = line.Length;
                            }
                            if (c == '"')
                            {
                                isstring = true;
                            }
                            if (ca == '{' && c == '"')
                            {
                                ismultilinestring = true;
                            }
                        }
                        else if (isstring)
                        {

                            if (c == '\\')
                            {
                                escapesequence = 2;
                            }
                            else if (stringvar > 0)
                            {
                                if (c == ']')
                                {
                                    stringvar--;
                                }
                                else if (c == '[')
                                {
                                    stringvar++;
                                }
                            }
                            else if (c == '"')
                            {
                                isstring = false;
                            }
                            else if (c == '[')
                            {
                                stringvar++;
                            }
                        }
                        else if (ismultilinestring)
                        {
                            if (ca == '"' && c == '}')
                            {
                                ismultilinestring = false;
                            }
                        }
                        else if (ismultilinecomment > 0)
                        {
                            if (ca == '/' && c == '*')
                            {
                                c = ' ';    //These things are here to prevent /*/ from bieng interpreted as the start and end of a comment.
                                skiponechar = true;
                                ismultilinecomment++;
                            }
                            if (ca == '*' && c == '/')
                            {
                                c = ' ';    //These things are here to prevent /*/ from bieng interpreted as the start and end of a comment.
                                skiponechar = true;
                                ismultilinecomment--;
                            }
                        }

                        if (!iscomment && (ismultilinecomment==0) && !skiponechar)
                        {
                            newline += c;
                        }

                        if (skiponechar)
                        {
                            skiponechar = false;
                        }
                        if (escapesequence > 0)
                        {
                            escapesequence--;
                        }
                        else
                        {
                            ca = c;
                        }
                }

                r.Add(newline.TrimEnd());

            }

            return r;
        }

        private bool normalstatus()
        {
            return !isstring && !ismultilinestring && (ismultilinecomment==0) && !iscomment && (escapesequence == 0);
        }

    }

    public class Define
    {
        public String location;
        public int line;
        public String name;
        public String value;
        public String comment;
        public List<String> references;

        public Define(String location, int line, String name, String value, String comment)
        {
            this.location = location;
            this.line = line;
            this.name = name;
            this.value = value;
            this.comment = comment;
            this.references = new List<String>();
        }

        public override String ToString()
        {
            return "DEFINE: \""+name+"\" is defined as \""+value+"\" AT "+location+" : "+line;
        }

    }

}


code:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!--
    Microsoft ResX Schema

    Version 2.0

    The primary goals of this format is to allow a simple XML format
    that is mostly human readable. The generation and parsing of the
    various data types are done through the TypeConverter classes
    associated with the data types.

    Example:

    ... ado.net/XML headers & schema ...
    <resheader name="resmimetype">text/microsoft-resx</resheader>
    <resheader name="version">2.0</resheader>
    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>[base64 mime encoded serialized .NET Framework object]</value>
    </data>
    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
        <comment>This is a comment</comment>
    </data>

    There are any number of "resheader" rows that contain simple
    name/value pairs.

    Each data row contains a name, and value. The row also contains a
    type or mimetype. Type corresponds to a .NET class that support
    text/value conversion through the TypeConverter architecture.
    Classes that don't support this are serialized and stored with the
    mimetype set.

    The mimetype is used for serialized objects, and tells the
    ResXResourceReader how to depersist the object. This is currently not
    extensible. For a given mimetype the value must be set accordingly:

    Note - application/x-microsoft.net.object.binary.base64 is the format
    that the ResXResourceWriter will generate, however the reader can
    read any of the formats listed below.

    mimetype: application/x-microsoft.net.object.binary.base64
    value   : The object must be serialized with
            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.soap.base64
    value   : The object must be serialized with
            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.bytearray.base64
    value   : The object must be serialized into a byte array
            : using a System.ComponentModel.TypeConverter
            : and then encoded with base64 encoding.
    -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
</root>


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace UnstandardnessTestForDM
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}


code:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnstandardnessTestForDM")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("UnstandardnessTestForDM")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c0e09000-1840-4416-8bb2-d86a8227adf1")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


code:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.239
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace UnstandardnessTestForDM.Properties
{

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources
    {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources()
        {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager
        {
            get
            {
                if ((resourceMan == null))
                {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UnstandardnessTestForDM.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture
        {
            get
            {
                return resourceCulture;
            }
            set
            {
                resourceCulture = value;
            }
        }
    }
}


code:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!--
    Microsoft ResX Schema

    Version 2.0

    The primary goals of this format is to allow a simple XML format
    that is mostly human readable. The generation and parsing of the
    various data types are done through the TypeConverter classes
    associated with the data types.

    Example:

    ... ado.net/XML headers & schema ...
    <resheader name="resmimetype">text/microsoft-resx</resheader>
    <resheader name="version">2.0</resheader>
    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>[base64 mime encoded serialized .NET Framework object]</value>
    </data>
    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
        <comment>This is a comment</comment>
    </data>

    There are any number of "resheader" rows that contain simple
    name/value pairs.

    Each data row contains a name, and value. The row also contains a
    type or mimetype. Type corresponds to a .NET class that support
    text/value conversion through the TypeConverter architecture.
    Classes that don't support this are serialized and stored with the
    mimetype set.

    The mimetype is used for serialized objects, and tells the
    ResXResourceReader how to depersist the object. This is currently not
    extensible. For a given mimetype the value must be set accordingly:

    Note - application/x-microsoft.net.object.binary.base64 is the format
    that the ResXResourceWriter will generate, however the reader can
    read any of the formats listed below.

    mimetype: application/x-microsoft.net.object.binary.base64
    value   : The object must be serialized with
            : System.Serialization.Formatters.Binary.BinaryFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.soap.base64
    value   : The object must be serialized with
            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.bytearray.base64
    value   : The object must be serialized into a byte array
            : using a System.ComponentModel.TypeConverter
            : and then encoded with base64 encoding.
    -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
</root>


code:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.239
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace UnstandardnessTestForDM.Properties
{

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
    {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default
        {
            get
            {
                return defaultInstance;
            }
        }
    }
}


code:
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
  <Profiles>
    <Profile Name="(Default)" />
  </Profiles>
  <Settings />
</SettingsFile>


code:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.30703</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A0EEBFC9-41D4-474D-853D-126AFDFB82DE}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>UnstandardnessTestForDM</RootNamespace>
    <AssemblyName>UnstandardnessTestForDM</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <EmbeddedResource Include="Form1.resx">
      <DependentUpon>Form1.cs</DependentUpon>
    </EmbeddedResource>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
      <SubType>Designer</SubType>
    </EmbeddedResource>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>


code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>


code:
@REM Script to easily upload tgstation.rsc to your FTP-server so that clients download it from an
@REM external webserver instead of from your connection when joining your game server.
@REM
@REM Run this script every time you have compiled your code, otherwise joining players will get errors.
@REM
@REM Replace USERNAME with your FTP username
@REM Replace PASSWORD with your FTP password
@REM Replace FOLDER/FOLDER with the folder on the FTP server where you want to store tgstation.rsc, for example: cd www/rsc
@REM Replace FTP.DOMAIN.COM with the IP-address or domain name of your FTP server
@REM Add the URL to the location of tgstation.rsc on your webserver into data\external_rsc_urls.txt
@REM
@echo off
echo user USERNAME> ftpcmd.dat
echo PASSWORD>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo cd FOLDER/FOLDER>> ftpcmd.dat
echo put ..\..\tgstation.rsc>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat FTP.DOMAIN.COM
del ftpcmd.dat

path: tools/Upload tgstation.rsc to external FTP/upload_rsc.bat


code:
#!/usr/bin/env python

import re, os, sys, fnmatch

# Regex pattern to extract the directory path in a #define FILE_DIR
filedir_pattern = re.compile(r'^#define\s*FILE_DIR\s*"(.*?)"')

# Regex pattern to extract any single quoted piece of text. This can also
# match single quoted strings inside of double quotes, which is part of a
# regular text string and should not be replaced. The replacement function
# however will any match that doesn't appear to be a filename so these
# extra matches should not be a problem.
rename_pattern = re.compile(r"'(.+?)'")

# Only filenames matching this pattern will have their resources renamed
source_pattern = re.compile(r"^.*?\.(dm|dmm)$")

# Open the .dme file and return a list of all FILE_DIR paths in it
def read_filedirs(filename):
    result = []
    dme_file = file(filename, "rt")

    # Read each line from the file and check for regex pattern match
    for row in dme_file:
        match = filedir_pattern.match(row)
        if match:
            result.append(match.group(1))

    dme_file.close()
    return result

# Search through a list of directories, and build a dictionary which
# maps every file to its full pathname (relative to the .dme file)
# If the same filename appears in more than one directory, the earlier
# directory in the list takes preference.
def index_files(file_dirs):
    result = {}

    # Reverse the directory list so the earlier directories take precedence
    # by replacing the previously indexed file of the same name
    for directory in reversed(file_dirs):
        for name in os.listdir(directory):
            # Replace backslash path separators on Windows with forward slash
            # Force "name" to lowercase when used as a key since BYOND resource
            # names are case insensitive, even on Linux.
            if name.find(".") == -1:
                continue
            result[name.lower()] = directory.replace('\\', '/') + '/' + name

    return result

# Recursively search for every .dm/.dmm file in the .dme file directory. For
# each file, search it for any resource names in single quotes, and replace
# them with the full path previously found by index_files()
def rewrite_sources(resources):
    # Create a closure for the regex replacement function to capture the
    # resources dictionary which can't be passed directly to this function
    def replace_func(name):
        key = name.group(1).lower()
        if key in resources:
            replacement = resources[key]
        else:
            replacement = name.group(1)
        return "'" + replacement + "'"

    # Search recursively for all .dm and .dmm files
    for (dirpath, dirs, files) in os.walk("."):
        for name in files:
            if source_pattern.match(name):
                path = dirpath + '/' + name
                source_file = file(path, "rt")
                output_file = file(path + ".tmp", "wt")

                # Read file one line at a time and perform replacement of all
                # single quoted resource names with the fullpath to that resource
                # file. Write the updated text back out to a temporary file.
                for row in source_file:
                    row = rename_pattern.sub(replace_func, row)
                    output_file.write(row)

                output_file.close()
                source_file.close()

                # Delete original source file and replace with the temporary
                # output. On Windows, an atomic rename() operation is not
                # possible like it is under POSIX.
                os.remove(path)
                os.rename(path + ".tmp", path)

dirs = read_filedirs("tgstation.dme");
resources = index_files(dirs)
rewrite_sources(resources)


code:
@echo off
rem Cheridan asked for this. - N3X
call python ss13_genchangelog.py ../html/changelog.html ../html/changelogs
pause


code:
class Location
{
  int x;
  int y;
  int z;

  public Location()
  {
  }

  public Location(int paramInt1, int paramInt2, int paramInt3)
  {
    this.x = paramInt1;
    this.y = paramInt2;
    this.z = paramInt3;
  }

  public void set(int paramInt1, int paramInt2, int paramInt3)
  {
    this.x = paramInt1;
    this.y = paramInt2;
    this.z = paramInt3;
  }

  public boolean equals(Object paramObject)
  {
    if (!(paramObject instanceof Location)) return false;
    Location localLocation = (Location)paramObject;
    if ((this.x != localLocation.x) || (this.y != localLocation.y) || (this.z != localLocation.z)) return false;
    return true;
  }

  public int hashCode()
  {
    return (this.z * 256 + this.y) * 256 + this.x;
  }

  public String toString()
  {
    return "(" + this.x + "," + this.y + "," + this.z + ")";
  }
}


code:
Manifest-Version: 1.0
Created-By: 1.6.0_31 (Sun Microsystems Inc.)
Main-Class: MapPatcher


code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class Map
{
  boolean sizeunknown;
  int minx;
  int miny;
  int minz;
  int maxx;
  int maxy;
  int maxz;
  HashMap<String, String> tile_types;
  HashMap<String, String> codes_by_value;
  HashMap<Location, String> tiles;

  public Map()
  {
    this.sizeunknown = true;
    this.tile_types = new HashMap();
    this.codes_by_value = new HashMap();
    this.tiles = new HashMap();
  }

  public Map(File paramFile)
  {
    this(paramFile, false);
  }

  public Map(File paramFile, boolean paramBoolean)
  {
    this.sizeunknown = true;
    try {
      BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramFile)));

      this.tile_types = new HashMap();
      this.codes_by_value = new HashMap();
      this.tiles = new HashMap();

      MapPatcher.Systemoutprintln(new StringBuilder().append("Loading map ").append(paramFile.getName()).toString());
      MapPatcher.Systemoutprint("Loading tiles");
      String str1 = "";
      int i = 0;
      while ((str1 = localBufferedReader.readLine()) != null)
      {
        if (str1.equals("")) break;
        if (str1.startsWith("\""))
        {
          if (i < 1)
          {
            int j = str1.indexOf("\"", 1);
            i = j - 1;
          }
          String str2 = str1.substring(1, 1 + i);
          String str3 = str1.substring(str1.indexOf("("));
          this.tile_types.put(str2, str3);
          this.codes_by_value.put(str3, str2);
        }
      }

      MapPatcher.Systemoutprintln(new StringBuilder().append(" ").append(this.tile_types.size()).toString());
      if (!paramBoolean)
      {
        MapPatcher.Systemoutprintln("Loading levels");
        while (true)
        {
          if ((str1 = localBufferedReader.readLine()) != null) { if (str1.startsWith("(")) break label270;  } else {
            label270: if (str1 == null)
            {
              break;
            }
            int k = str1.indexOf(",", 1);
            int m = Integer.parseInt(str1.substring(1, k));
            str1 = str1.substring(k);
            k = str1.indexOf(",", 1);
            int n = Integer.parseInt(str1.substring(1, k));
            str1 = str1.substring(k);
            k = str1.indexOf(")", 1);
            int i1 = Integer.parseInt(str1.substring(1, k));

            MapPatcher.Systemoutprintln(new StringBuilder().append("New map part from (").append(m).append(",").append(n).append(",").append(i1).append(")").toString());

            int i3 = n;
            if (this.sizeunknown)
            {
              this.minx = m; this.maxx = this.minx;
              this.miny = n; this.maxy = this.miny;
              this.minz = i1; this.maxz = this.minz;
              this.sizeunknown = false;
            }
            if (this.minz > i1) this.minz = i1;
            if (this.maxz < i1) this.maxz = i1;
            while (!(str1 = localBufferedReader.readLine()).startsWith("\"}"))
            {
              int i2 = m;
              if (this.miny > i3) this.miny = i3;
              if (this.maxy < i3) this.maxy = i3;
              while (str1.length() > 0)
              {
                String str4 = str1.substring(0, i);
                Location localLocation = new Location(i2, i3, i1);
                if (this.minx > i2) this.minx = i2;
                if (this.maxx < i2) this.maxx = i2;
                this.tiles.put(localLocation, this.tile_types.get(str4));
                str1 = str1.substring(i);
                i2++;
              }
              i3++;
            }
          }
        }
      }
      localBufferedReader.close();
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  public void mirrorY()
  {
    for (int i = this.minz; i <= this.maxz; i++)
      for (int j = this.minx; j <= this.maxx; j++)
        for (int k = this.miny; k < (this.miny + this.maxy) / 2; k++)
        {
          int m = this.maxy - (k - this.miny);
          String str = contentAt2(j, k, i);
          setAt(j, k, i, contentAt2(j, m, i));
          setAt(j, m, i, str);
        }
  }

  public String contentAt(int paramInt1, int paramInt2, int paramInt3)
  {
    Location localLocation = new Location(paramInt1, paramInt2, paramInt3);
    String str = (String)this.tiles.get(localLocation);
    if (str == null) System.err.println(new StringBuilder().append("Null at ").append(paramInt1).append(",").append(paramInt2).append(",").append(paramInt3).append(" Possible loading error").toString());
    return str == null ? "null" : str;
  }

  public String contentAt2(int paramInt1, int paramInt2, int paramInt3)
  {
    Location localLocation = new Location(paramInt1, paramInt2, paramInt3);
    return (String)this.tiles.get(localLocation);
  }

  public void setAt(int paramInt1, int paramInt2, int paramInt3, String paramString)
  {
    if (this.sizeunknown)
    {
      this.minx = (this.maxx = paramInt1);
      this.miny = (this.maxy = paramInt2);
      this.minz = (this.maxz = paramInt3);
      this.sizeunknown = false;
    }
    else
    {
      this.minx = Math.min(this.minx, paramInt1);
      this.miny = Math.min(this.miny, paramInt2);
      this.minz = Math.min(this.minz, paramInt3);
      this.maxx = Math.max(this.maxx, paramInt1);
      this.maxy = Math.max(this.maxy, paramInt2);
      this.maxz = Math.max(this.maxz, paramInt3);
    }
    Location localLocation = new Location(paramInt1, paramInt2, paramInt3);
    localLocation.set(paramInt1, paramInt2, paramInt3);
    this.tiles.put(localLocation, paramString);
  }

  public void save(File paramFile) throws Exception
  {
    saveReferencing(paramFile, null);
  }

  public void saveReferencing(File paramFile, Map paramMap) throws Exception
  {
    FileWriter localFileWriter = new FileWriter(paramFile);

    this.tile_types.clear();
    this.codes_by_value.clear();
    Vector localVector1 = new Vector();
    for (Object localObject1 = this.tiles.keySet().iterator(); ((Iterator)localObject1).hasNext(); ) { Location localLocation = (Location)((Iterator)localObject1).next();

      String str1 = (String)this.tiles.get(localLocation);
      if (!localVector1.contains(str1))
        localVector1.add(str1);
    }
    MapPatcher.Systemoutprintln(new StringBuilder().append("We have ").append(localVector1.size()).append(" different tiles").toString());
    localObject1 = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    int i = 1;
    int j = localObject1.length;
    while (j < localVector1.size())
    {
      j *= localObject1.length;
      i++;
    }
    Vector localVector2;
    if (paramMap == null) {
      localVector2 = localVector1;
    }
    else {
      localVector2 = new Vector();
      for (Iterator localIterator = localVector1.iterator(); localIterator.hasNext(); ) { localObject2 = (String)localIterator.next();

        if (paramMap.codes_by_value.containsKey(localObject2))
        {
          localObject3 = paramMap.getIdFor((String)localObject2);
          this.tile_types.put(localObject3, localObject2);
          this.codes_by_value.put(localObject2, localObject3);
        }
        else {
          localVector2.add(localObject2);
        } }
      localVector1.clear();
    }

    int k = 0;
    for (Object localObject2 = localVector2.iterator(); ((Iterator)localObject2).hasNext(); ) { localObject3 = (String)((Iterator)localObject2).next();
      do
      {
        str2 = int2code((String[])localObject1, k, i);
        k++;
      }while (this.tile_types.containsKey(str2));
      this.tile_types.put(str2, localObject3);
      this.codes_by_value.put(localObject3, str2);
    }
    String str2;
    localVector2.clear();

    k = 0;
    for (int m = 0; m < this.tile_types.size(); m++)
    {
      do
      {
        localObject3 = int2code((String[])localObject1, k, i);
        k++;
      }while (!this.tile_types.containsKey(localObject3));
      str2 = (String)this.tile_types.get(localObject3);
      localFileWriter.write(new StringBuilder().append("\"").append((String)localObject3).append("\" = ").append(str2).append("\r\n").toString());
    }
    localVector2.clear();

    localFileWriter.write("\n");

    m = 1 + this.maxz - this.minz;
    Object localObject3 = new SavingThread[m];
    int n = (this.maxy - this.miny) * ((this.maxx - this.minx) * i + 2) + 32;

    for (k = 0; k < m; k++)
    {
      localObject3[k] = new SavingThread(this.minz + k, this, n);
      localObject3[k].start();
    }

    int i1 = 0;
    String str3 = "";
    while (i1 == 0) {
      try {
        Thread.sleep(100L); } catch (Exception localException) {
      }
      i1 = 1;

      str3 = "";
      for (k = 0; k < m; k++)
      {
        if (!localObject3[k].done)
          i1 = 0;
        if (str3.length() != 0) str3 = new StringBuilder().append(str3).append(" ").toString();
        str3 = new StringBuilder().append(str3).append(localObject3[k].done ? "Done" : new StringBuilder().append(localObject3[k].progress).append("%").toString()).toString();
      }
      MapPatcher.Systemoutprint(new StringBuilder().append(str3).append("\r").toString());
    }

    for (k = 0; k < m; k++) {
      localFileWriter.write(localObject3[k].result.toString());
    }
    localFileWriter.flush();
    localFileWriter.close();
  }

  public String getIdFor(String paramString)
  {
    if (this.codes_by_value.containsKey(paramString))
    {
      return (String)this.codes_by_value.get(paramString);
    }
    return "???";
  }

  public String int2code(String[] paramArrayOfString, int paramInt1, int paramInt2)
  {
    String str = "";
    while (paramInt1 >= paramArrayOfString.length)
    {
      int i = paramInt1 % paramArrayOfString.length;
      str = new StringBuilder().append(paramArrayOfString[i]).append(str).toString();
      paramInt1 -= i;
      paramInt1 /= paramArrayOfString.length;
    }
    str = new StringBuilder().append(paramArrayOfString[paramInt1]).append(str).toString();
    while (str.length() < paramInt2) str = new StringBuilder().append(paramArrayOfString[0]).append(str).toString();
    return str;
  }
}


code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;

public class MapPatcher
{
  static boolean silent = false;

  public static void main(String[] paramArrayOfString)
  {
    String str1 = "usage: [me] -diff [old_map] [new_map] [diff_file]";
    String str2 = "usage: [me] -patch [old_map] [diff_file] [new_map]";
    String str3 = "usage: [me] -pack [unpacked] [packed.dmm]";
    String str4 = "usage: [me] -unpack [packed.dmm] [unpacked]";
    String str5 = "usage: [me] -clean [oldmap.dmm] [newmap.dmm] [cleaned.dmm]";
    String str6 = "usage: [me] -merge [original] [local] [remote] [output]";

    for (int i = 0; i < paramArrayOfString.length; i++)
      if (paramArrayOfString[i].equalsIgnoreCase("-silent"))
      {
        silent = true;
        for (; i < paramArrayOfString.length - 1; i++)
          paramArrayOfString[i] = paramArrayOfString[(i + 1)];
        paramArrayOfString = (String[])Arrays.copyOf(paramArrayOfString, paramArrayOfString.length - 1);
        break;
      }
    Object localObject;
    int i2;
    int i3;
    int i5;
    if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-merge")))
    {
      if (paramArrayOfString.length < 5)
      {
        System.out.println(str6);
        try { System.in.read(); } catch (Exception localException1) {
        }return;
      }

      Map localMap1 = new Map(new File(paramArrayOfString[1]));
      localObject = new Map(new File(paramArrayOfString[2]));
      Map localMap8 = new Map(new File(paramArrayOfString[3]));
      Map localMap9 = new Map();

      if ((localMap1.minx != ((Map)localObject).minx) || (localMap1.minx != localMap8.minx) || (localMap1.maxx != ((Map)localObject).maxx) || (localMap1.maxx != localMap8.maxx) || (localMap1.miny != ((Map)localObject).miny) || (localMap1.miny != localMap8.miny) || (localMap1.maxy != ((Map)localObject).maxy) || (localMap1.maxy != localMap8.maxy) || (localMap1.minz != ((Map)localObject).minz) || (localMap1.minz != localMap8.minz) || (localMap1.maxz != ((Map)localObject).maxz) || (localMap1.maxz != localMap8.maxz))
      {
        Systemoutprintln("Map sizes differ");
        System.exit(1);
      }
      try
      {
        for (int n = localMap1.minz; n <= localMap1.maxz; n++)
          for (i2 = localMap1.miny; i2 <= localMap1.maxy; i2++)
            for (i3 = localMap1.minx; i3 <= localMap1.maxx; i3++)
            {
              boolean bool1 = localMap1.contentAt(i3, i2, n).equals(((Map)localObject).contentAt(i3, i2, n));
              boolean bool2 = localMap1.contentAt(i3, i2, n).equals(localMap8.contentAt(i3, i2, n));
              i5 = ((Map)localObject).contentAt(i3, i2, n).equals(localMap8.contentAt(i3, i2, n));
              if ((!bool1) && (!bool2))
              {
                if (i5 == 0)
                {
                  Systemoutprintln(i3 + "," + i2 + "," + n + " local and remote don't match original and differ");
                  System.exit(1);
                }
                else {
                  localMap9.setAt(i3, i2, n, ((Map)localObject).contentAt(i3, i2, n));
                }
              } else if (!bool1)
                localMap9.setAt(i3, i2, n, ((Map)localObject).contentAt(i3, i2, n));
              else if (!bool2)
                localMap9.setAt(i3, i2, n, localMap8.contentAt(i3, i2, n));
              else
                localMap9.setAt(i3, i2, n, localMap1.contentAt(i3, i2, n));
            }
        Systemoutprintln("Saving");
        localMap9.saveReferencing(new File(paramArrayOfString[4]), localMap1);
        Systemoutprintln("Done");
      }
      catch (Exception localException12)
      {
        localException12.printStackTrace();
      }
    }
    else
    {
      int m;
      int i1;
      if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-diff")))
      {
        if (paramArrayOfString.length < 4)
        {
          System.out.println(str1);
          try { System.in.read(); } catch (Exception localException2) {
          }return;
        }

        Map localMap2 = new Map(new File(paramArrayOfString[1]));
        localObject = new Map(new File(paramArrayOfString[2]));

        int j = Math.max(localMap2.minx, ((Map)localObject).minx);
        m = Math.min(localMap2.maxx, ((Map)localObject).maxx);
        i1 = Math.max(localMap2.miny, ((Map)localObject).miny);
        i2 = Math.min(localMap2.maxy, ((Map)localObject).maxy);
        i3 = Math.max(localMap2.minz, ((Map)localObject).minz);
        int i4 = Math.min(localMap2.maxz, ((Map)localObject).maxz);
        Systemoutprintln("Comparing: x(" + j + "-" + m + ") y(" + i1 + "-" + i2 + ") z(" + i3 + "-" + i4 + ")");
        try
        {
          FileWriter localFileWriter2 = new FileWriter(paramArrayOfString[3]);
          i5 = 0;
          for (int i6 = i3; i6 <= i4; i6++)
          {
            Systemoutprintln("Z-level " + i6);
            for (int i7 = i1; i7 <= i2; i7++)
              for (int i8 = j; i8 <= m; i8++)
                if (!localMap2.contentAt(i8, i7, i6).equals(((Map)localObject).contentAt(i8, i7, i6)))
                {
                  localFileWriter2.write("(" + i8 + "," + (1 + ((Map)localObject).maxy - i7) + "," + i6 + ")=" + ((Map)localObject).contentAt(i8, i7, i6) + "\n");
                  i5++;
                }
          }
          localFileWriter2.flush();
          localFileWriter2.close();
          if (i5 == 0)
            Systemoutprintln("Files do match");
          else
            Systemoutprintln("Writed out " + i5 + " differences");
        }
        catch (Exception localException13)
        {
          localException13.printStackTrace();
        }

        Systemoutprintln("Done");
      }
      else
      {
        String str7;
        String str8;
        if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-patch")))
        {
          if (paramArrayOfString.length < 4)
          {
            System.out.println(str2);
            try { System.in.read(); } catch (Exception localException3) {
            }return;
          }

          Map localMap3 = new Map(new File(paramArrayOfString[1]));
          try
          {
            localObject = new BufferedReader(new InputStreamReader(new FileInputStream(paramArrayOfString[2])));

            while ((str7 = ((BufferedReader)localObject).readLine()) != null)
            {
              str7 = str7.trim();
              if (str7.length() != 0)
              {
                m = str7.indexOf(",", 1);
                i1 = Integer.parseInt(str7.substring(1, m));
                str7 = str7.substring(m);
                m = str7.indexOf(",", 1);
                i2 = Integer.parseInt(str7.substring(1, m));
                str7 = str7.substring(m);
                m = str7.indexOf(")", 1);
                i3 = Integer.parseInt(str7.substring(1, m));
                str8 = str7.substring(str7.indexOf("=") + 1);
                localMap3.setAt(i1, 1 + localMap3.maxy - i2, i3, str8);
              }
            }
            localMap3.save(new File(paramArrayOfString[3]));
          }
          catch (Exception localException8)
          {
            localException8.printStackTrace();
          }

          Systemoutprintln("Done");
        }
        else if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-pack")))
        {
          if (paramArrayOfString.length < 3)
          {
            System.out.println(str3);
            try { System.in.read(); } catch (Exception localException4) {
            }return;
          }

          Map localMap4 = new Map();
          try {
            BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramArrayOfString[1])));
            Systemoutprintln("Loading");

            while ((str7 = localBufferedReader.readLine()) != null)
            {
              str7 = str7.trim();
              if (str7.length() != 0)
              {
                m = str7.indexOf(",", 1);
                i1 = Integer.parseInt(str7.substring(1, m));
                str7 = str7.substring(m);
                m = str7.indexOf(",", 1);
                i2 = Integer.parseInt(str7.substring(1, m));
                str7 = str7.substring(m);
                m = str7.indexOf(")", 1);
                i3 = Integer.parseInt(str7.substring(1, m));
                str8 = str7.substring(str7.indexOf("=") + 1);
                localMap4.setAt(i1, i2, i3, str8);
              }
            }
            Systemoutprintln("Flipping");
            localMap4.mirrorY();
            Systemoutprintln("Saving, bounds: x{" + localMap4.minx + " - " + localMap4.maxx + "}, y{" + localMap4.miny + " - " + localMap4.maxy + "}, z{" + localMap4.minz + " - " + localMap4.maxz + "}");
            localMap4.save(new File(paramArrayOfString[2]));
            Systemoutprintln("Done");
          }
          catch (Exception localException9)
          {
            localException9.printStackTrace();
          }
        }
        else if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-unpack")))
        {
          if (paramArrayOfString.length < 3)
          {
            System.out.println(str4);
            try { System.in.read(); } catch (Exception localException5) {
            }return;
          }

          Systemoutprintln("Loading");
          Map localMap5 = new Map(new File(paramArrayOfString[1]));
          try {
            FileWriter localFileWriter1 = new FileWriter(paramArrayOfString[2]);
            Systemoutprintln("Saving");
            for (int k = localMap5.minz; k <= localMap5.maxz; k++)
            {
              Systemoutprintln("Z-level " + k);
              for (m = localMap5.miny; m <= localMap5.maxy; m++)
                for (i1 = localMap5.minx; i1 <= localMap5.maxx; i1++)
                  localFileWriter1.write("(" + i1 + "," + (1 + localMap5.maxy - m) + "," + k + ")=" + localMap5.contentAt(i1, m, k) + "\n");
              localFileWriter1.write("\n");
            }
            localFileWriter1.flush();
            localFileWriter1.close();

            Systemoutprintln("Done");
          }
          catch (Exception localException10)
          {
            localException10.printStackTrace();
          }
        }
        else if ((paramArrayOfString.length > 0) && (paramArrayOfString[0].equalsIgnoreCase("-clean")))
        {
          if (paramArrayOfString.length < 4)
          {
            System.out.println(str5);
            try { System.in.read(); } catch (Exception localException6) {
            }return;
          }

          Map localMap6 = new Map(new File(paramArrayOfString[1]), true);
          Map localMap7 = new Map(new File(paramArrayOfString[2]));
          try
          {
            localMap7.saveReferencing(new File(paramArrayOfString[3]), localMap6);
            Systemoutprintln("Done");
          }
          catch (Exception localException11)
          {
            localException11.printStackTrace();
          }
        }
        else
        {
          System.out.println(str1);
          System.out.println(str2);
          System.out.println(str3);
          System.out.println(str4);
          System.out.println(str5);
          System.out.println(str6);
          try {
            System.in.read(); } catch (Exception localException7) {  }
        }
      }
    }
  }

  public static void Systemoutprintln(String paramString) { if (!silent)
      System.out.println(paramString); }

  public static void Systemoutprint(String paramString)
  {
    if (!silent)
      System.out.print(paramString);
  }
}


code:
class SavingThread extends Thread
{
  int z;
  Map mymap;
  boolean done;
  int progress;
  StringBuilder result;

  public SavingThread(int paramInt1, Map paramMap, int paramInt2)
  {
    this.z = paramInt1;
    this.mymap = paramMap;
    this.progress = 0;
    this.done = false;
    this.result = new StringBuilder(paramInt2);
  }

  public void run()
  {
    this.result.append("(" + this.mymap.minx + "," + this.mymap.miny + "," + this.z + ") = {\"\r\n");

    int i = (this.mymap.maxx - this.mymap.minx) * (this.mymap.maxy - this.mymap.miny) / 100;
    int j = 0;
    for (int k = this.mymap.miny; k <= this.mymap.maxy; k++)
    {
      for (int m = this.mymap.minx; m <= this.mymap.maxx; m++)
      {
        this.result.append(this.mymap.getIdFor(this.mymap.contentAt(m, k, this.z)));
        j++; if (j >= i) { j = 0; this.progress += 1; }
      }
      this.result.append("\r\n");
    }
    this.result.append("\"}\r\n");
    this.result.append("\r\n");
    this.done = true;
  }
}


code:
@echo off
cd ../../_maps/map_files/
set /P MAPFILE=Please enter mapfile (relative to map_files folder):

java -jar ../../tools/mapmerge/MapPatcher.jar -clean "%MAPFILE%.backup" "%MAPFILE%" "%MAPFILE%"

pause


code:
1. Install java(http://www.java.com/en/download/index.jsp)
2. Make sure java is in your PATH. To test this, open git bash, and type "java". If it says unknown command, you need to add JAVA/bin to your PATH variable (A guide for this can be found at https://www.java.com/en/download/help/path.xml ).

Committing
1. Before starting to edit the map, double-click "prepare_map.bat" in the tools/mapmerge/ directory.
2. After finishing your edit, and before your commit, double-click "clean_map.bat" in the tools/mapmerge/ directory.

This will make sure in the new version of your map, no paths are needlessly changed, thus instead of 8000 lines changed you'll get 50 lines changed. This not only reduces size of your commit, it also makes it possible to get an overview of your map changes on the "files changed" page in your pull request.

Merging
The easiest way to do merging is to install the merge driver. For this, you can just double-click "install_driver.bat" in the tools/mapmerge/ directory.

Alternatively, open -tg-station/.git/config in a text editor, and paste the following lines to the end of it:

[merge "merge-dmm"]
	name = mapmerge driver
	driver = ./tools/mapmerge/mapmerge.sh %O %A %B

After this, merging maps should happen automagically unless there are conflicts(a tile that both you and someone else changed). If there are conflicts, you will unfortunately still be stuck with opening both versions in a map editor, and manually resolving the issues.


code:
@echo off
echo. >> ../../.git/config
echo [merge "merge-dmm"] >> ../../.git/config
echo	name = mapmerge driver >> ../../.git/config
echo	driver = ./tools/mapmerge/mapmerge.sh %O %A %B >> ../../.git/config
echo. >> ../../.git/config


code:
java -jar tools/mapmerge/MapPatcher.jar -merge $1 $2 $3 $2
if [ "$?" -gt 0 ]
then
    echo "Unable to automatically resolve map conflicts, please merge manually."
    exit 1
fi
java -jar tools/mapmerge/MapPatcher.jar -clean $1 $2 $2

exit 0


code:
@echo off
cd ../../_maps/map_files/

for /R %%f in (*.dmm) do copy %%f "%%f.backup"

cls
echo All dmm files in map_files directories have been backed up
echo Now you can make your changes...
echo ---
echo Remember to run clean_map.bat just before you commit your changes!
echo ---
pause


code:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "midi2piano", "midi2piano\midi2piano.csproj", "{68C84B61-F710-491C-BEE8-5E362C167897}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Debug|Mixed Platforms = Debug|Mixed Platforms
		Debug|x86 = Debug|x86
		Release|Any CPU = Release|Any CPU
		Release|Mixed Platforms = Release|Mixed Platforms
		Release|x86 = Release|x86
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{68C84B61-F710-491C-BEE8-5E362C167897}.Debug|Any CPU.ActiveCfg = Debug|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Debug|Mixed Platforms.Build.0 = Debug|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Debug|x86.ActiveCfg = Debug|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Debug|x86.Build.0 = Debug|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Release|Any CPU.ActiveCfg = Release|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Release|Mixed Platforms.ActiveCfg = Release|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Release|Mixed Platforms.Build.0 = Release|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Release|x86.ActiveCfg = Release|x86
		{68C84B61-F710-491C-BEE8-5E362C167897}.Release|x86.Build.0 = Release|x86
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


code:
namespace midi2piano
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.OutputTxt = new System.Windows.Forms.TextBox();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.importMIDIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.importDlg = new System.Windows.Forms.OpenFileDialog();
            this.halpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // OutputTxt
            //
            this.OutputTxt.Dock = System.Windows.Forms.DockStyle.Fill;
            this.OutputTxt.Location = new System.Drawing.Point(0, 24);
            this.OutputTxt.Multiline = true;
            this.OutputTxt.Name = "OutputTxt";
            this.OutputTxt.ReadOnly = true;
            this.OutputTxt.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.OutputTxt.Size = new System.Drawing.Size(284, 240);
            this.OutputTxt.TabIndex = 0;
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem,
            this.copyToolStripMenuItem,
            this.halpToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(284, 24);
            this.menuStrip1.TabIndex = 1;
            this.menuStrip1.Text = "menuStrip1";
            //
            // fileToolStripMenuItem
            //
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.importMIDIToolStripMenuItem,
            this.exitToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
            this.fileToolStripMenuItem.Text = "&File";
            //
            // importMIDIToolStripMenuItem
            //
            this.importMIDIToolStripMenuItem.Name = "importMIDIToolStripMenuItem";
            this.importMIDIToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.I)));
            this.importMIDIToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
            this.importMIDIToolStripMenuItem.Text = "&Import MIDI...";
            this.importMIDIToolStripMenuItem.Click += new System.EventHandler(this.importMIDIToolStripMenuItem_Click);
            //
            // exitToolStripMenuItem
            //
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
            this.exitToolStripMenuItem.Text = "E&xit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            //
            // copyToolStripMenuItem
            //
            this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
            this.copyToolStripMenuItem.Size = new System.Drawing.Size(47, 20);
            this.copyToolStripMenuItem.Text = "&Copy";
            this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
            //
            // importDlg
            //
            this.importDlg.Filter = "MIDI File|*.midi;*.mid";
            //
            // halpToolStripMenuItem
            //
            this.halpToolStripMenuItem.Name = "halpToolStripMenuItem";
            this.halpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
            this.halpToolStripMenuItem.Text = "&Halp";
            this.halpToolStripMenuItem.Click += new System.EventHandler(this.halpToolStripMenuItem_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 264);
            this.Controls.Add(this.OutputTxt);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "Form1";
            this.Text = "MIDI2Piano";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox OutputTxt;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem importMIDIToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
        private System.Windows.Forms.OpenFileDialog importDlg;
        private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem halpToolStripMenuItem;
    }
}