text:
#include "map_editor.h"
#include "rgs.h"
#include "globals.h"
#include "entity_gfx.h"

RGS_Screen *mapEditorScreen;

RGS_Screen *gfxScreen;
RGS_Screen *geomScreen;
RGS_Screen *attScreen;
RGS_Screen *entityScreen;

RGS_Tilemap *workingTilemap = NULL;
RGS_Tilemap *selectorTilemap = NULL;

RGS_SurfaceImage *tilemapImage;

RGS_UIOptionList *mapLayers;

RGS_UICheckBox *gfxLayerCheckBox;
RGS_UICheckBox *geomLayerCheckBox;
RGS_UICheckBox *att1LayerCheckBox;
RGS_UICheckBox *entityLayerCheckBox;

RGS_UICheckBox *applyToAll;
RGS_UICheckBox *applyToAllAtts;

RGS_UIOptionList *geomTiles;
RGS_UIOptionList *attributeTiles;
RGS_UIOptionList *brushList;
RGS_UIOptionList *gfxPaintModeList;
RGS_UIOptionList *entityList;

int gfxPaintMode = GFX_PAINT_SINGLETILE;

RGS_UIHorizontalScroller *mapScrollerH;
RGS_UIVerticalScroller *mapScrollerV;
RGS_UIVerticalScroller *tileSelectorScroller;

RGS_UITextInput *brushName;
RGS_UIButton *saveBrush;
RGS_UIButton *saveBrushesToFile;

RGS_UIButton *entityPlaceModeButton;
RGS_UIButton *entitySelectModeButton;
RGS_UIButton *entityRemoveModeButton;
RGS_Shape *entityModeSelector;

char entity_icon[] = {0x53, 0x50, 0x52, 0x32, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x01, 0x07, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x03, 0x00, 0xBB, 0xFF, 0x00, 0xFF, 0x55, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x01, 0x02, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x01, 0x02, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02};

RGS_UITextInput *entName;
RGS_UITextInput *entCode;
RGS_UIButton *saveEntity;
RGS_UIButton *setEntitySprite;
RGS_UIButton *saveEntitiesToFile;

RGS_Sprite *previewSprite = NULL;

RGS_UITextInput *attName;
RGS_UITextInput *attCode;
RGS_UIButton *saveAtt;
RGS_UIButton *saveAttsToFile;

RGS_Shape *tileSelector;

RGS_UIButton *createEntityButton;
RGS_Screen *entityOverlayScreen;

void reloadFileBrowser(char *dirname);
extern RGS_Label *errorMessageLabel;
extern RGS_UITextInput *fileInput;
extern char curdir[4096];

char *currentTile = "";

int showGeomTiles = 1;
int showAttTiles = 1;
int showEntities = 1;

int curTileIndex = 0;;
int painting = 0;
int erasing = 0;

Uint16 curGFXTile = 0;
Uint8 curGeomTile = TILE_SOLID;

int paintMode = PAINT_MODE_GFX;

Uint16 newBrushStartTile = 0;
Uint16 newBrushEndTile = 0;
RGS_UIButton *createBrushButton;
RGS_UIButton *removeBrushButton;

Uint16 oldPaintMode = 0;

char *curTilemapTilePath = NULL;

RGS_Screen *newTilemapScreen = NULL;
RGS_UITextInput *newTilemapWidth;
RGS_UITextInput *newTilemapHeight;
RGS_UITextInput *newTilemapTileSize;
RGS_UIButton *newTilemapGo;

ISArray *entitySprites;

int doApplyToAll = 0;
int doApplyToAllAtts = 0;

ISArray *brushes;
ISArray *attributes;
ISArray *entities;

Editor_Brush *curBrush = NULL;
RGS_Tilemap *brushTilemap = NULL;
RGS_Tilemap *brushPreviewTilemap = NULL;

RGS_UIButton *createAttButton = NULL;
RGS_UIButton *removeAttButton = NULL;

int numAttColors = 16;
int attColors[16] = {0xFF96C9, 0x00ffff,0xff00ff,0x0000ff,0xc0c0c0,0x008080,0x800080,0x000080,0xffff00,0x808000,0x008000,0xff0000,0x800000,0xff6000,0x0078ff,0x00ffb4};
int curAttTile = 0;
Editor_Att *curAtt = NULL;
Editor_Entity *curEntity = NULL;

int entityMode = ENTITY_MODE_PLACE;
RGS_Entity *selectedEntity = NULL;

int eDragOffsetX = 0;
int eDragOffsetY = 0;

void initMapEditor() {

	mapEditorScreen = RGS_CreateScreen();
	mapEditorScreen->visible = 0;

	gfxScreen = RGS_CreateScreen();
	gfxScreen->visible = 0;
	geomScreen = RGS_CreateScreen();
	geomScreen->visible = 0;
	attScreen = RGS_CreateScreen();
	attScreen->visible = 0;
	entityScreen = RGS_CreateScreen();
	entityScreen->visible = 0;
	entityOverlayScreen = RGS_CreateScreen();

	entitySprites = ISArray_Create(sizeof(RGS_Sprite));

	RGS_CreateLabel(mapEditorScreen, "MAP LAYERS", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+5,24,0x79CA00);
	RGS_CreateLabel(geomScreen, "COLLISION TILES", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+170,24,0x6F7FF8);
	RGS_CreateLabel(attScreen, "ATTRIBUTE TILES", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+170,24,0xFF8C49);

	RGS_CreateLabel(gfxScreen, "PAINT MODE", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+160,24,0xFF931F);
	RGS_CreateLabel(gfxScreen, "GFX TILES", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+250,24,0xEA68FC);
	RGS_CreateLabel(gfxScreen, "BRUSHES", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+400,24,0x86FFE7);
	RGS_CreateLabel(entityScreen, "ENTITIES", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+170,24,0xFF5E8B);

	mapLayers = RGS_CreateUIOptionList(mapEditorScreen, 15, EDITOR_LEFT_MARGIN+5, 40, 100, 100);
	RGS_AddUIOption(mapLayers, "GFX Tiles", PAINT_MODE_GFX, NULL, 0xffffff);
	RGS_AddUIOption(mapLayers, "Collision Tiles", PAINT_MODE_GEOM, NULL, 0xffffff);
	RGS_AddUIOption(mapLayers, "Attribute Tiles", PAINT_MODE_ATT1, NULL, 0xffffff);
	RGS_AddUIOption(mapLayers, "Entities", PAINT_MODE_ENTITY, NULL, 0xffffff);

	RGS_SelectButtonByID(mapLayers, PAINT_MODE_GFX);
	mapLayers->onSelect = choosePaintMode;

	gfxLayerCheckBox = RGS_CreateUICheckBox(mapEditorScreen, "visible", EDITOR_LEFT_MARGIN+110, 43);
	gfxLayerCheckBox->checked = 1;
	gfxLayerCheckBox->onChange = changeLayerVis;
	geomLayerCheckBox = RGS_CreateUICheckBox(mapEditorScreen, "visible", EDITOR_LEFT_MARGIN+110, 58);
	geomLayerCheckBox->checked = 1;
	geomLayerCheckBox->onChange = changeLayerVis;
	att1LayerCheckBox = RGS_CreateUICheckBox(mapEditorScreen, "visible", EDITOR_LEFT_MARGIN+110, 73);
	att1LayerCheckBox->checked = 1;
	att1LayerCheckBox->onChange = changeLayerVis;
	entityLayerCheckBox = RGS_CreateUICheckBox(mapEditorScreen, "visible", EDITOR_LEFT_MARGIN+110, 88);
	entityLayerCheckBox->checked = 1;
	entityLayerCheckBox->onChange = changeLayerVis;

	geomTiles = RGS_CreateUIOptionList(geomScreen, 15, EDITOR_LEFT_MARGIN+170, 40, 100, 100);
	RGS_AddUIOption(geomTiles, "TILE_SOLID", TILE_SOLID, NULL, 0x00ff00);
	RGS_AddUIOption(geomTiles, "TILE_EMPTY", TILE_EMPTY, NULL, 0x00ff00);
	geomTiles->onSelect = chooseGeomBrush;

	RGS_SelectButtonByID(geomTiles, 1);

	applyToAll = RGS_CreateUICheckBox(geomScreen, "Apply to all with same gfx.", EDITOR_LEFT_MARGIN+170, 150);
	applyToAll->onChange = changeApplyToAll;

	////////////////////////////////////////////////////////////////////////////////////
	// ATTRIBUTE SCREEN
	////////////////////////////////////////////////////////////////////////////////////

	attributeTiles = RGS_CreateUIOptionList(attScreen, 15, EDITOR_LEFT_MARGIN+170, 40, 100, 77);
	attributeTiles->onSelect = chooseAttTile;

	applyToAllAtts = RGS_CreateUICheckBox(attScreen, "Apply to all with same gfx.", EDITOR_LEFT_MARGIN+170, 150);
	applyToAllAtts->onChange = changeApplyToAll;

	createAttButton = RGS_CreateUIButton(attScreen, "New Attr.", EDITOR_LEFT_MARGIN+170, 122, 55, 18);
	createAttButton->uiObject.onRelease = createNewAtt;
	removeAttButton = RGS_CreateUIButton(attScreen, "Remove", EDITOR_LEFT_MARGIN+231, 122, 40, 18);
	removeAttButton->uiObject.onRelease = removeAtt;

	attName = RGS_CreateUITextInput(attScreen, EDITOR_LEFT_MARGIN+280, 40, 100, 18);
	attCode = RGS_CreateUITextInput(attScreen, EDITOR_LEFT_MARGIN+280, 65, 100, 18);

	saveAtt = RGS_CreateUIButton(attScreen, "Update", EDITOR_LEFT_MARGIN+280, 90, 50, 18);
	saveAtt->uiObject.onRelease = updateAttName;
	saveAttsToFile = RGS_CreateUIButton(attScreen, "Save Attributes To File", EDITOR_LEFT_MARGIN+280, 122, 130, 18);
	saveAttsToFile->uiObject.onRelease = saveAttributes;

	////////////////////////////////////////////////////////////////////////////////////
	// ENTITY SCREEN
	////////////////////////////////////////////////////////////////////////////////////

	entityList = RGS_CreateUIOptionList(entityScreen, 15, EDITOR_LEFT_MARGIN+170, 40, 100, 77);
	entityList->onSelect = chooseEntity;

	createEntityButton = RGS_CreateUIButton(entityScreen, "New Entity", EDITOR_LEFT_MARGIN+170, 122, 55, 18);
	createEntityButton->uiObject.onRelease = createNewEntity;

	entName = RGS_CreateUITextInput(entityScreen, EDITOR_LEFT_MARGIN+280, 40, 100, 18);
	entCode = RGS_CreateUITextInput(entityScreen, EDITOR_LEFT_MARGIN+280, 65, 100, 18);
	setEntitySprite = RGS_CreateUIButton(entityScreen, "Set Sprite", EDITOR_LEFT_MARGIN+280, 90, 100, 18);
	setEntitySprite->uiObject.onRelease = setEntitySpriteGO;
	saveEntity = RGS_CreateUIButton(entityScreen, "Update", EDITOR_LEFT_MARGIN+280, 115, 50, 18);
	saveEntity->uiObject.onRelease = updateEntityName;
	saveEntitiesToFile = RGS_CreateUIButton(entityScreen, "Save Entities To File", EDITOR_LEFT_MARGIN+480, 122, 130, 18);
	saveEntitiesToFile->uiObject.onRelease = saveEntities;

	entityModeSelector = RGS_CreateShape(entityScreen, RGS_SHAPE_RECT, 0xffffff, EDITOR_LEFT_MARGIN+208, 145, 54, 22);

	RGS_CreateLabel(entityScreen, "MODE:", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+170,152,0xFF8C49);
	entityPlaceModeButton = RGS_CreateUIButton(entityScreen, "Place", EDITOR_LEFT_MARGIN+210, 147, 50,18);
	entityPlaceModeButton->uiObject.onRelease = chooseEntityMode;
	entitySelectModeButton = RGS_CreateUIButton(entityScreen, "Select", EDITOR_LEFT_MARGIN+265, 147, 50,18);
	entitySelectModeButton->uiObject.onRelease = chooseEntityMode;
//	entityRemoveModeButton = RGS_CreateUIButton(entityScreen, "Remove", EDITOR_LEFT_MARGIN+320, 147, 50,18);
//	entityRemoveModeButton->uiObject.onRelease = chooseEntityMode;

	////////////////////////////////////////////////////////////////////////////////////
	// GFX SCREEN
	////////////////////////////////////////////////////////////////////////////////////

	gfxPaintModeList = RGS_CreateUIOptionList(gfxScreen, 15, EDITOR_LEFT_MARGIN+160, 40, 80, 100);
	RGS_AddUIOption(gfxPaintModeList, "Single tile", GFX_PAINT_SINGLETILE, NULL, 0xffffff);
	RGS_AddUIOption(gfxPaintModeList, "Brush", GFX_PAINT_BRUSH, NULL, 0xffffff);
	RGS_SelectButtonByID(gfxPaintModeList, GFX_PAINT_SINGLETILE);
	gfxPaintModeList->onSelect = chooseGfxPaintMode;

	brushList = RGS_CreateUIOptionList(gfxScreen, 15, EDITOR_LEFT_MARGIN+400, 40, 100, 77);
	brushList->onSelect = chooseBrush;

	createBrushButton = RGS_CreateUIButton(gfxScreen, "New Brush", EDITOR_LEFT_MARGIN+400, 122, 55, 18);
	createBrushButton->uiObject.onRelease = startCreatingBrush;
	removeBrushButton = RGS_CreateUIButton(gfxScreen, "Remove", EDITOR_LEFT_MARGIN+460, 122, 40, 18);
	removeBrushButton->uiObject.onRelease = removeBrush;

	brushName = RGS_CreateUITextInput(gfxScreen, EDITOR_LEFT_MARGIN+505, 40, 100, 18);
	saveBrush = RGS_CreateUIButton(gfxScreen, "Update", EDITOR_LEFT_MARGIN+610, 40, 50, 18);
	saveBrush->uiObject.onRelease = updateBrushName;
	saveBrushesToFile = RGS_CreateUIButton(gfxScreen, "Save Brushes To File", EDITOR_LEFT_MARGIN+695, 40, 120, 18);
	saveBrushesToFile->uiObject.onRelease = saveBrushes;

	mapScrollerH = RGS_CreateUIHorizontalScroller(mapEditorScreen, EDITOR_LEFT_MARGIN+5, 768-25, 1024 - EDITOR_LEFT_MARGIN - 30, 20);
	mapScrollerV = RGS_CreateUIVerticalScroller(mapEditorScreen, 1024-20, EDITOR_TOP_MARGIN, 20, 768 - EDITOR_TOP_MARGIN);
	tileSelectorScroller = RGS_CreateUIVerticalScroller(gfxScreen, EDITOR_LEFT_MARGIN+378, 40, 10, 100);

	newTilemapScreen = RGS_CreateScreen();

	RGS_CreateLabel(newTilemapScreen, "CREATE NEW TILEMAP", RGS_FONT_BIG, EDITOR_LEFT_MARGIN+5,EDITOR_TOP_MARGIN-130,0x79CA00);
	RGS_CreateLabel(newTilemapScreen, "Tile size (8-256):", RGS_FONT_SMALL, EDITOR_LEFT_MARGIN+5,EDITOR_TOP_MARGIN-97,0x4c4c4c);
	RGS_CreateLabel(newTilemapScreen, "Map width:", RGS_FONT_SMALL, EDITOR_LEFT_MARGIN+5,EDITOR_TOP_MARGIN-72,0x4c4c4c);
	RGS_CreateLabel(newTilemapScreen, "Map height:", RGS_FONT_SMALL, EDITOR_LEFT_MARGIN+5,EDITOR_TOP_MARGIN-47,0x4c4c4c);

	newTilemapTileSize = RGS_CreateUITextInput(newTilemapScreen, EDITOR_LEFT_MARGIN+85, EDITOR_TOP_MARGIN-100, 40, 20);
	RGS_SetLabelText(newTilemapTileSize->label, "8");

	newTilemapWidth = RGS_CreateUITextInput(newTilemapScreen, EDITOR_LEFT_MARGIN+85, EDITOR_TOP_MARGIN-75, 40, 20);
	RGS_SetLabelText(newTilemapWidth->label, "64");
	newTilemapHeight = RGS_CreateUITextInput(newTilemapScreen, EDITOR_LEFT_MARGIN+85, EDITOR_TOP_MARGIN-50, 40, 20);
	RGS_SetLabelText(newTilemapHeight->label, "64");

	newTilemapGo = RGS_CreateUIButton(newTilemapScreen, "Create", EDITOR_LEFT_MARGIN+5, EDITOR_TOP_MARGIN-25, 120, 18);
	newTilemapGo->uiObject.onRelease = CreateNewTilemapGO;
	newTilemapScreen->visible = 0;

	brushes = ISArray_Create(sizeof(Editor_Brush));
	attributes = ISArray_Create(sizeof(Editor_Att));
	entities = ISArray_Create(sizeof(Editor_Entity));

	RGS_RegisterDefaultEntity(entityOverlayScreen, "", DefEntity_Init, NULL, NULL, 1, entity_icon);

	refreshAtts();

	//// temporary stuff

}

void chooseEntityMode(void *target) {
	//	entityModeSelector = RGS_CreateShape(entityScreen, RGS_SHAPE_RECT, 0xffffff, EDITOR_LEFT_MARGIN+208, 145, 54, 22);
	if(target == entityPlaceModeButton) {
		entityModeSelector->object.x = EDITOR_LEFT_MARGIN+208;
		entityMode = ENTITY_MODE_PLACE;
	} else if(target == entitySelectModeButton) {
		entityModeSelector->object.x = EDITOR_LEFT_MARGIN+263;
		entityMode = ENTITY_MODE_SELECT;
	} else if(target == entityRemoveModeButton) {
		entityModeSelector->object.x = EDITOR_LEFT_MARGIN+318;
		entityMode = ENTITY_MODE_REMOVE;
	}
}

void DefEntity_Init(RGS_Entity *entity) {
	entity->noGravityOn = 1;
	entity->noClipOn = 1;
}

void refreshEntitiesInMap() {
	int i,j;
	Editor_Entity *curEdEnt;
	RGS_Entity *ent;

	for(j =0; j < entities->length;j++) {
		curEdEnt = (Editor_Entity*)entities->data[j];

		for(i =0; i < workingTilemap->entities->length;i++) {
			ent = (RGS_Entity*)workingTilemap->entities->data[i];
			if(ent->entityID == curEdEnt->code) {
				if(curEdEnt->spritePath->length > 0) {
					RGS_DestroyObject(ent->object);
					ent->object = (RGS_Object*)RGS_CreateSprite(entityOverlayScreen, curEdEnt->spritePath->text);
				}
			}
		}
	}
}

void updateEntityName(void *target) {
	ISString_SetText(curEntity->name, entName->label->text);
	curEntity->code = atoi(entCode->label->text);

	printf("id: %d\n", curEntity->code);

	int i;
	RGS_Entity *ent;
	for(i =0; i < workingTilemap->entities->length;i++) {
		ent = (RGS_Entity*)workingTilemap->entities->data[i];
		if(ent->entityID == curEntity->code) {
			if(curEntity->spritePath->length > 0) {
				RGS_DestroyObject(ent->object);
				ent->object = (RGS_Object*)RGS_CreateSprite(entityOverlayScreen, curEntity->spritePath->text);
			}
		}
	}

	refreshEntities();
}

void setEntitySpriteGO(void *target) {
	char tmp[4096];
	strcpy(tmp, curdir);
	strcat(tmp, "/");
	strcat(tmp, fileInput->label->text);
	ISString_SetText(curEntity->spritePath, tmp);
}

void refreshEntities() {
	int i;
	Editor_Entity *ent;

	RGS_ClearUIOptionList(entityList);
	//	RGS_AddUIOption(entityList, "CLEAR  ATTRIBUTE", 0, NULL, 0xffffff);

	for(i=0;i<entities->length;i++) {
		ent = (Editor_Entity*) entities->data[i];
		RGS_AddUIOption(entityList, ent->name->text, i, NULL, 0xffffff);
	}

	//if(entities->length > 0)
	//	chooseEntity(0, NULL);
}

void createNewEntity(void *target) {
	Editor_Entity *newEntity = (Editor_Entity*)ISArray_CreateElement(entities);
	newEntity->name = ISString_Create("new entity");
	newEntity->spritePath = ISString_Create("");
	newEntity->code = 1;
	refreshEntities();
}

void chooseEntity(int id, void *data) {
	curEntity = (Editor_Entity*) entities->data[id];
	RGS_SetLabelText(entName->label, curEntity->name->text);
	char code[16];
	sprintf(code, "%d", curEntity->code);
	RGS_SetLabelText(entCode->label, code);
	if(previewSprite != NULL) {
		RGS_DestroyObject((RGS_Object*)previewSprite);
	}

	if(strlen(curEntity->spritePath->text) > 1) {
		previewSprite = RGS_CreateSprite(entityScreen, curEntity->spritePath->text);
		previewSprite->object.x = EDITOR_LEFT_MARGIN+390;
		previewSprite->object.y = 40;
	} else {
		previewSprite = NULL;
	}
}

void updateAttName(void *target) {
	ISString_SetText(curAtt->name, attName->label->text);
	curAtt->code = atoi(attCode->label->text);
	refreshAtts();
}

void saveEntities(void *target) {
	char spritePath[256];
	char tmp[4096];
	strcpy(tmp, curdir);
	strcat(tmp, "/");
	strcat(tmp, fileInput->label->text);

	int i;
	Uint16 sval = 0;

	FILE *outPtr = fopen(tmp, "wb");
	sval = entities->length;
	fwrite(&sval, 2, 1, outPtr);

	Editor_Entity *ent;

	for(i=0; i < entities->length; i++) {
		ent = (Editor_Entity*)entities->data[i];
		sval = ent->name->length;
		fwrite(&sval, 2, 1, outPtr);
		fwrite(ent->name->text, 1, ent->name->length, outPtr);

		if(ent->spritePath->length > 0) {
			strcpy(spritePath, ent->spritePath->text+strlen(curdir)+1);
			sval = strlen(spritePath);
			fwrite(&sval, 2, 1, outPtr);
			fwrite(spritePath, 1, strlen(spritePath), outPtr);
		} else {
			sval = 0;
			fwrite(&sval, 2, 1, outPtr);
		}
		fwrite(&ent->code, 1, 1, outPtr);
	}

	fclose(outPtr);
	reloadFileBrowser(curdir);
}

void saveAttributes(void *target) {
	char tmp[4096];
	strcpy(tmp, curdir);
	strcat(tmp, "/");
	strcat(tmp, fileInput->label->text);

	int i;
	Uint16 sval = 0;

	FILE *outPtr = fopen(tmp, "wb");
	sval = attributes->length;
	fwrite(&sval, 2, 1, outPtr);

	Editor_Att *att;

	for(i=0; i < attributes->length; i++) {
		att = (Editor_Att*)attributes->data[i];
		sval = att->name->length;
		fwrite(&sval, 2, 1, outPtr);
		fwrite(att->name->text, 1, att->name->length, outPtr);
		fwrite(&att->code, 1, 1, outPtr);
	}

	fclose(outPtr);
	reloadFileBrowser(curdir);
}

void chooseAttTile(int id, void *data) {
	if(id == 0) {
		curAtt = NULL;
		curAttTile = 0;
	} else {
		curAtt = (Editor_Att*) attributes->data[id-1];
		RGS_SetLabelText(attName->label, curAtt->name->text);
		char code[16];
		sprintf(code, "%d", curAtt->code);
		RGS_SetLabelText(attCode->label, code);
		curAttTile = curAtt->code;
	}
}

void refreshAtts() {
	int i;
	Editor_Att *att;

	RGS_ClearUIOptionList(attributeTiles);
	RGS_AddUIOption(attributeTiles, "CLEAR  ATTRIBUTE", 0, NULL, 0xffffff);
	for(i=0;i<attributes->length;i++) {
		att = (Editor_Att*) attributes->data[i];
		RGS_AddUIOption(attributeTiles, att->name->text, i+1, NULL, attColors[att->code % 16]);
	}
	RGS_SelectButtonByID(attributeTiles, 0);
}

void createNewAtt(void *target) {
	Editor_Att *newAtt = (Editor_Att*)ISArray_CreateElement(attributes);
	newAtt->name = ISString_Create("new attribute");
	newAtt->code = 1;
	refreshAtts();
}

void removeAtt(void *target) {
	if(attributeTiles->selectedID == -1)
		return;

	if(attributeTiles->selectedID == 0)	{
		RGS_SetLabelText(errorMessageLabel, "ERROR: You cannot remove that! 'Ta fuck!");
		return;
	}

	Editor_Att *att = (Editor_Att*)attributes->data[attributeTiles->selectedID-1];

	ISArray_RemoveElement(attributes, (void*)att);
	refreshAtts();
}

void MapEditor_LoadEntities(char *fileName) {
	Editor_Entity *ent;
	int i;

	char tmp[4096];

	for(i=0;i<entities->length;i++) {
		ent = (Editor_Entity*)entities->data[i];
		ISString_Destroy(ent->name);
		ISString_Destroy(ent->spritePath);
		//		ISArray_RemoveElement(entities, (void*)ent);
		//		free((void*)ent);
	}
	if(entities->length > 0)
		ISArray_Clear(entities);

	FILE *inPtr = fopen(fileName, "rb");

	Uint16 numEnts, sval;
	fread(&numEnts, 2, 1, inPtr);

	char *tmpString = NULL;

	for(i=0;i<numEnts;i++) {
		ent = (Editor_Entity*)ISArray_CreateElement(entities);
		fread(&sval, 2, 1, inPtr);
		if(tmpString != NULL)
			free(tmpString);
		tmpString = (char*)malloc(sval+1);
		fread(tmpString, 1, sval, inPtr);
		memset(tmpString+sval, 0, 1);
		ent->name = ISString_Create(tmpString);
		free(tmpString);
		tmpString = NULL;

		fread(&sval, 2, 1, inPtr);
		if(sval > 0) {
			tmpString = (char*)malloc(sval+1);
			fread(tmpString, 1, sval, inPtr);
			memset(tmpString+sval, 0, 1);
			strcpy(tmp, curdir);
			strcat(tmp, "/");
			strcat(tmp, tmpString);
			ent->spritePath = ISString_Create(tmp);
			free(tmpString);
			tmpString = NULL;
		} else {
			ent->spritePath = ISString_Create("");
		}

		fread(&ent->code, 1, 1, inPtr);
	}

	fclose(inPtr);

	refreshEntities();
	refreshEntitiesInMap();
}

void MapEditor_LoadAttributes(char *fileName) {

	int i;
	Editor_Att *att;

	for(i=0;i<attributes->length;i++) {
		att = (Editor_Att*)attributes->data[i];
		ISString_Destroy(att->name);
		ISArray_RemoveElement(attributes, (void*)att);
		free((void*)att);
	}

	FILE *inPtr = fopen(fileName, "rb");

	Uint16 numAtts, sval;
	fread(&numAtts, 2, 1, inPtr);

	char *tmpString = NULL;

	for(i=0;i<numAtts;i++) {
		att = (Editor_Att*)ISArray_CreateElement(attributes);
		fread(&sval, 2, 1, inPtr);
		if(tmpString != NULL)
			free(tmpString);
		tmpString = (char*)malloc(sval+1);
		fread(tmpString, 1, sval, inPtr);
		memset(tmpString+sval, 0, 1);
		att->name = ISString_Create(tmpString);
		fread(&att->code, 1, 1, inPtr);
	}

	fclose(inPtr);
	refreshAtts();

}

void MapEditor_LoadBrushes(char *fileName) {

	destroyBrushes();

	FILE *inPtr = fopen(fileName, "rb");

	Uint16 numBrushes, sval;
	fread(&numBrushes, 2, 1, inPtr);
	int i;

	char *tmpString = NULL;

	for(i=0;i<numBrushes;i++) {
		Editor_Brush *newBrush = (Editor_Brush*)ISArray_CreateElement(brushes);
		fread(&sval, 2, 1, inPtr);

		if(tmpString != NULL)
			free(tmpString);
		tmpString = (char*)malloc(sval+1);
		fread(tmpString, 1, sval, inPtr);
		memset(tmpString+sval, 0, 1);
		newBrush->name = ISString_Create(tmpString);
		fread(&newBrush->id, 2, 1, inPtr);
		fread(&newBrush->brushRect, sizeof(RGS_Rect), 1, inPtr);
		newBrush->data = (Uint16*)malloc(2*(newBrush->brushRect.w*newBrush->brushRect.h));
		fread(newBrush->data, 2, newBrush->brushRect.w*newBrush->brushRect.h, inPtr);
	}

	fclose(inPtr);
	refreshBrushList();
}

void saveBrushes(void *target) {
	char tmp[4096];
	strcpy(tmp, curdir);
	strcat(tmp, "/");
	strcat(tmp, fileInput->label->text);

	int i;

	Uint16 sval = 0;

	FILE *outPtr = fopen(tmp, "wb");
	sval = brushes->length;
	fwrite(&sval, 2, 1, outPtr);

	Editor_Brush *brush;

	for(i=0; i < brushes->length; i++) {
		brush = (Editor_Brush*)brushes->data[i];
		sval = brush->name->length;
		fwrite(&sval, 2, 1, outPtr);
		fwrite(brush->name->text, 1, brush->name->length, outPtr);
		fwrite(&brush->id, 2, 1, outPtr);
		fwrite(&brush->brushRect, sizeof(RGS_Rect), 1, outPtr);
		fwrite(brush->data, 2, brush->brushRect.w*brush->brushRect.h, outPtr);
	}

	fclose(outPtr);
	reloadFileBrowser(curdir);
}

void updateBrushName(void *target) {
	if(curBrush != NULL)
		ISString_SetText(curBrush->name, brushName->label->text);
	refreshBrushList();
}

void chooseGfxPaintMode(int id, void *data) {
	if(id == GFX_PAINT_BRUSH) {
		if(brushes->length == 0) {
			RGS_SetLabelText(errorMessageLabel, "There are no brushes defined!");
			RGS_SelectButtonByID(gfxPaintModeList, gfxPaintMode);
			return;
		}
		if(curBrush == NULL) {
			RGS_SetLabelText(errorMessageLabel, "There is no brush selected!");
			RGS_SelectButtonByID(gfxPaintModeList, gfxPaintMode);
			return;
		}
		brushTilemap->object.visible = 1;
	} else {
		brushTilemap->object.visible = 0;
	}
	gfxPaintMode = id;
}

void chooseGeomBrush(int id, void *data) {
	curGeomTile = id;
}

void choosePaintMode(int id, void *data) {
	paintMode = id;

	gfxScreen->visible = 0;
	geomScreen->visible = 0;
	attScreen->visible = 0;
	entityScreen->visible = 0;

	switch(paintMode) {
		case PAINT_MODE_GFX:
			gfxScreen->visible = 1;
			break;
		case PAINT_MODE_GEOM:
			geomScreen->visible = 1;
			break;
		case PAINT_MODE_ATT1:
			attScreen->visible = 1;
			break;
		case PAINT_MODE_ENTITY:
			entityScreen->visible = 1;
			break;
	}
}

void MapEditor_SaveTilemap(char *fileName) {
	RGS_SaveTilemap(workingTilemap, fileName);
}

void CreateNewTilemapGO(void *target) {
	if(curTilemapTilePath == NULL) {
		RGS_SetLabelText(errorMessageLabel, "ERROR: You need to choose a tileset first!");
		return;
	}

	if(workingTilemap != NULL) {
		RGS_DestroyObject((RGS_Object*)workingTilemap);
	}

	RGS_ScreenDestroyObjects(entityOverlayScreen);
	workingTilemap = RGS_CreateEmptyTilemap(mapEditorScreen, 1024-EDITOR_LEFT_MARGIN-30, 768-EDITOR_TOP_MARGIN-30, atoi(newTilemapWidth->label->text), atoi(newTilemapHeight->label->text),  atoi(newTilemapTileSize->label->text), curTilemapTilePath);
	setupNewTilemap();
	choosePaintMode(PAINT_MODE_GFX, NULL);
	newTilemapScreen->visible = 0;
}

void startCreatingBrush(void *target) {
	if(paintMode != PAINT_MODE_BRUSHDEFSTART)
		oldPaintMode = paintMode;
	paintMode = PAINT_MODE_BRUSHDEFSTART;
}

void refreshBrushList() {
	RGS_ClearUIOptionList(brushList);
	int i;
	Editor_Brush *brush;
	for(i=0;i<brushes->length;i++){
		brush = (Editor_Brush*)brushes->data[i];
		RGS_AddUIOption(brushList, brush->name->text, i, NULL, 0xffffff);
	}
}

void removeBrush(void *target) {
	if(brushList->selectedID == -1)
		return;

	Editor_Brush *brush = (Editor_Brush*)brushes->data[brushList->selectedID];
	ISArray_RemoveElement(brushes, (void*)brush);
	DestroyBrush(brush);
	refreshBrushList();
}

void destroyBrushes() {
	int i;
	Editor_Brush *brush;
	int stLen = brushes->length;
	for(i=stLen-1;i >= 0; i--) {
		brush = (Editor_Brush*)brushes->data[i];
		DestroyBrush(brush);
		ISArray_RemoveElement(brushes, brush);
	}
}

void DestroyBrush(Editor_Brush *brush) {
	free(brush->data);
	ISString_Destroy(brush->name);
	free(brush);
}

void changeApplyToAll(void *target) {
	RGS_UICheckBox *targetBox = (RGS_UICheckBox*)target;
	if(targetBox == applyToAll) {
		doApplyToAll = targetBox->checked;
	} else if (targetBox == applyToAllAtts) {
		doApplyToAllAtts = targetBox->checked;
	}
}

void changeLayerVis(void *target) {
	RGS_UICheckBox *targetBox = (RGS_UICheckBox*)target;
	if(targetBox == gfxLayerCheckBox) {
		workingTilemap->object.visible = targetBox->checked;
	} else if(targetBox == geomLayerCheckBox) {
		showGeomTiles = targetBox->checked;
	} else if(targetBox == att1LayerCheckBox) {
		showAttTiles = att1LayerCheckBox->checked;
	} else if(targetBox == entityLayerCheckBox) {
		showEntities = entityLayerCheckBox->checked;
	}
}

void applyBrush(Editor_Brush *brush, Uint16 tIndex) {
	int i,j;

	int x = tIndex % workingTilemap->mapWidth;
	int y = (tIndex-x) / workingTilemap->mapWidth;

	int k = 0;

	for(i=y;i<y+brush->brushRect.h;i++) {
		for(j=x;j<x+brush->brushRect.w;j++) {
			workingTilemap->mapTileData[(i*workingTilemap->mapWidth)+j] = brush->data[k];
			k++;
		}
	}
}

void paintTile(int tileIndex) {
	int i;

	switch(paintMode) {
		case PAINT_MODE_GEOM:
			if(doApplyToAll == 1) {
				for(i=0;i<workingTilemap->mapWidth*workingTilemap->mapHeight;i++) {
					if(workingTilemap->mapTileData[i] == workingTilemap->mapTileData[tileIndex])
						workingTilemap->mapAttributeData[i] = curGeomTile;
				}
			} else {
				workingTilemap->mapAttributeData[tileIndex] = curGeomTile;
			}
			break;
			case PAINT_MODE_GFX:
			switch(gfxPaintMode) {
				case GFX_PAINT_SINGLETILE:
					workingTilemap->mapTileData[tileIndex] = curGFXTile;
					break;
				case GFX_PAINT_BRUSH:
					applyBrush(curBrush, tileIndex);
					break;
			}
			RGS_RedrawTilemapBuffer(workingTilemap);
			break;
			case PAINT_MODE_BRUSHDEFSTART:
			paintMode = PAINT_MODE_BRUSHDEFEND;
			newBrushStartTile = tileIndex;
			break;
			case PAINT_MODE_BRUSHDEFEND:
			newBrushEndTile = tileIndex;
			break;
			case PAINT_MODE_ATT1:
			if(doApplyToAllAtts == 1) {
				for(i=0;i<workingTilemap->mapWidth*workingTilemap->mapHeight;i++) {
					if(workingTilemap->mapTileData[i] == workingTilemap->mapTileData[tileIndex])
						workingTilemap->userAttributeData[i] = curAttTile;
				}
			} else {
				workingTilemap->userAttributeData[tileIndex] = curAttTile;
			}
			break;
			case PAINT_MODE_ENTITY: {
				switch(entityMode) {
					case ENTITY_MODE_PLACE: {
						RGS_EntitySprite *newSprite;
						if(curEntity != NULL) {
						if(curEntity->spritePath->length > 0) {
							newSprite = RGS_CreateEntitySprite(entityOverlayScreen, workingTilemap, curEntity->spritePath->text);
						} else {
							newSprite = RGS_CreateEntitySpriteFromMemory(entityOverlayScreen, workingTilemap, entity_icon);
						}

						newSprite->entity->entityID = curEntity->code;
						newSprite->entity->noClipOn = 1;
						newSprite->entity->noGravityOn = 1;
						newSprite->entity->x = (tileIndex % workingTilemap->mapWidth) * workingTilemap->tileSize;
						newSprite->entity->y = ((tileIndex / workingTilemap->mapWidth)+1) * workingTilemap->tileSize;
						}
						}
						break;
					case ENTITY_MODE_SELECT: {
						selectedEntity = RGS_TilemapGetEntityAt(workingTilemap, RGS_GetMouseX()-workingTilemap->object.x+workingTilemap->cameraX, RGS_GetMouseY()-workingTilemap->object.y+workingTilemap->cameraY);
						if(selectedEntity != NULL) {
							eDragOffsetX = RGS_GetMouseX()-workingTilemap->object.x+workingTilemap->cameraX-selectedEntity->x;
							eDragOffsetY = RGS_GetMouseY()-workingTilemap->object.y+workingTilemap->cameraY-selectedEntity->y;
						}
					}
					break;
						default:
						break;
				}
			}
			break;
	}
}

void MapEditor_KeyPress(int keyCode) {
	switch(keyCode) {
		case RGS_DELETE:
			if(selectedEntity != NULL) {
				RGS_ScreenRemoveObject(entityOverlayScreen, selectedEntity->object);
				selectedEntity = NULL;
			}
		break;
	}
}

void changeTile(void *target) {
	painting = 1;
	paintTile(curTileIndex);
}

void selectTile(void *target) {
	int startY = workingTilemap->cameraY/workingTilemap->tileSize;
	if(startY > 0)
		startY += 1;

	int offsetY = selectorTilemap->cameraY - (startY*workingTilemap->tileSize);
	curGFXTile = (RGS_GetMouseX() - selectorTilemap->object.x) / workingTilemap->tileSize + (((RGS_GetMouseY() - selectorTilemap->object.y+offsetY) / workingTilemap->tileSize)*selectorTilemap->mapWidth);
}

void endChangeTile(void *target) {
	painting = 0;

	if(selectedEntity != NULL) {
		selectedEntity->object->onRelease = NULL;
	}

	if(paintMode == PAINT_MODE_BRUSHDEFEND) {
		paintMode = oldPaintMode;
		createNewBrush();
	}
}

void copyBrushToTilemap(Editor_Brush *brush, RGS_Tilemap *tilemap) {
	int i,j;
	int k =0;
	for(i =0; i < brush->brushRect.h; i++) {
		for(j=0; j < brush->brushRect.w; j++) {
			tilemap->mapTileData[(i*brush->brushRect.w) + j] = brush->data[k];
			k++;
		}
	}
}

void chooseBrush(int id, void *data) {
	curBrush = (Editor_Brush*)brushes->data[id];

	if(brushTilemap != NULL) {
		RGS_DestroyObject((RGS_Object*)brushTilemap);
	}

	if(brushPreviewTilemap != NULL) {
		RGS_DestroyObject((RGS_Object*)brushPreviewTilemap);
	}

	brushTilemap = RGS_CreateEmptyTilemap(gfxScreen, curBrush->brushRect.w*workingTilemap->tileSize, curBrush->brushRect.h*workingTilemap->tileSize, curBrush->brushRect.w,curBrush->brushRect.h, workingTilemap->tileSize, curTilemapTilePath);
	brushPreviewTilemap = RGS_CreateEmptyTilemap(gfxScreen, curBrush->brushRect.w*workingTilemap->tileSize, curBrush->brushRect.h*workingTilemap->tileSize, curBrush->brushRect.w,curBrush->brushRect.h, workingTilemap->tileSize, curTilemapTilePath);
	brushPreviewTilemap->object.x = EDITOR_LEFT_MARGIN+505;
	brushPreviewTilemap->object.y = 62;

	copyBrushToTilemap(curBrush, brushTilemap);
	copyBrushToTilemap(curBrush, brushPreviewTilemap);

	RGS_SetLabelText(brushName->label, curBrush->name->text);
	brushTilemap->object.visible = 0;

}

void createNewBrush() {
	Editor_Brush *newBrush = (Editor_Brush*)ISArray_CreateElement(brushes);

	if(workingTilemap->cameraX > 0)
		newBrush->brushRect.x =	(workingTilemap->cameraX/workingTilemap->tileSize) +1+ ((tileSelector->object.x - workingTilemap->object.x)/workingTilemap->tileSize);
	else
		newBrush->brushRect.x =	(tileSelector->object.x - workingTilemap->object.x)/workingTilemap->tileSize;

	if(workingTilemap->cameraY > 0)
		newBrush->brushRect.y =	(workingTilemap->cameraY/workingTilemap->tileSize) + ((tileSelector->object.y - workingTilemap->object.y)/workingTilemap->tileSize);
	else
		newBrush->brushRect.y =	(tileSelector->object.y - workingTilemap->object.y)/workingTilemap->tileSize;

	newBrush->brushRect.w = tileSelector->object.w / workingTilemap->tileSize;
	newBrush->brushRect.h = tileSelector->object.h / workingTilemap->tileSize;

	newBrush->data = (Uint16*)malloc(sizeof(Uint16) * newBrush->brushRect.w * newBrush->brushRect.h);
	int i,j;
	int k=0;

	for(i=newBrush->brushRect.y; i < newBrush->brushRect.y+newBrush->brushRect.h; i++) {
		for(j=newBrush->brushRect.x; j < newBrush->brushRect.x+newBrush->brushRect.w; j++) {
			memcpy(newBrush->data+k, workingTilemap->mapTileData + (i*workingTilemap->mapWidth) + j, sizeof(Uint16));
			k++;
		}
	}

	newBrush->id = brushes->length-1;
	newBrush->name = ISString_Create("new brush");
	refreshBrushList();
	//RGS_AddUIOption(brushList, "new brush", brushes->length-1, NULL, 0xffffff);
}

void scrollMap(void *target) {
	workingTilemap->cameraX = ((float)((workingTilemap->mapWidth * workingTilemap->tileSize)-1024+EDITOR_LEFT_MARGIN+30)) * mapScrollerH->scrollValue;
	workingTilemap->cameraY = ((float)((workingTilemap->mapHeight * workingTilemap->tileSize)-768+EDITOR_TOP_MARGIN+30)) * mapScrollerV->scrollValue;
}

void scrollTileSelector(void *target) {
	selectorTilemap->cameraY = ((float)((selectorTilemap->mapHeight * selectorTilemap->tileSize)-100)) * tileSelectorScroller->scrollValue;
}

void CreateTileSelector() {

	if(selectorTilemap != NULL) {
		RGS_DestroyObject((RGS_Object*)selectorTilemap);
	}

	// create tile selector
	int tWidth = 128/workingTilemap->tileSize;
	int tHeight = ceil((float)((workingTilemap->tilesSurface->surface->w/workingTilemap->tileSize) * (workingTilemap->tilesSurface->surface->h/workingTilemap->tileSize))/tWidth);

	selectorTilemap = RGS_CreateEmptyTilemap(gfxScreen, 128, 100, tWidth,tHeight, workingTilemap->tileSize, curTilemapTilePath);
	selectorTilemap->object.x = EDITOR_LEFT_MARGIN+250;
	selectorTilemap->object.y = 40;

	selectorTilemap->object.onPress = selectTile;

	int i,j;
	int k=0;
	for(i=0;i < tHeight; i++) {
		for(j=0;j < tWidth; j++) {
			selectorTilemap->mapTileData[i*tWidth+j] = k;
			k++;
		}
	}

	float tmp = ((float)(100))/((float)(selectorTilemap->mapHeight*workingTilemap->tileSize));
	tileSelectorScroller->percentage = tmp*100.0f;
	tileSelectorScroller->onChange = scrollTileSelector;
	tileSelector = RGS_CreateShape(mapEditorScreen, RGS_SHAPE_RECT_OUTLINE, 0xffffff, 0,0, workingTilemap->tileSize, workingTilemap->tileSize);

}

void MapEditor_SetTilesetPath(char *newPath) {
	if(curTilemapTilePath == NULL)
		curTilemapTilePath = (char*)malloc(4096);

	strcpy(curTilemapTilePath, newPath);

	if(workingTilemap != NULL) {
		RGS_LoadNewTilemapTiles(workingTilemap, newPath);
		CreateTileSelector();
	}
}

void MapEditor_CreateNewTilemap() {
	mapEditorScreen->visible = 0;
	newTilemapScreen->visible = 1;
}

void openMap(char *mapFile) {

	if(curTilemapTilePath == NULL) {
		RGS_SetLabelText(errorMessageLabel, "ERROR: You need to choose a tileset first!");
		return;
	}

	RGS_ScreenDestroyObjects(entityOverlayScreen);

	workingTilemap = RGS_CreateTilemap(mapEditorScreen, 1024-EDITOR_LEFT_MARGIN-30, 768-EDITOR_TOP_MARGIN-30, mapFile, curTilemapTilePath);

	setupNewTilemap();
	choosePaintMode(PAINT_MODE_GFX, NULL);
}

void setupNewTilemap() {

	workingTilemap->object.x = EDITOR_LEFT_MARGIN+5;
	workingTilemap->object.y = EDITOR_TOP_MARGIN+5;
	//tilemapImage = RGS_CreateSurfaceImage(mapEditorScreen, workingTilemap->tilesSurface, EDITOR_LEFT_MARGIN+5, 5);
	workingTilemap->object.onPress = changeTile;
	workingTilemap->object.onRelease = endChangeTile;
	workingTilemap->object.onReleaseOutside = endChangeTile;
	mapEditorScreen->visible =1 ;
	float tmp = ((float)(1024-EDITOR_LEFT_MARGIN-30))/((float)(workingTilemap->mapWidth*workingTilemap->tileSize));
	mapScrollerH->percentage = tmp*100.0f;
	mapScrollerH->onChange = scrollMap;

	tmp = ((float)(768-EDITOR_TOP_MARGIN-30))/((float)(workingTilemap->mapHeight*workingTilemap->tileSize));
	mapScrollerV->percentage = tmp*100.0f;
	mapScrollerV->onChange = scrollMap;

	CreateTileSelector();
}

void updateMapEditor() {
	if(mapEditorScreen->visible == 0)
		return;

	if(workingTilemap == NULL)
		return;

	entityOverlayScreen->visible = showEntities;

	int i,j;
	RGS_Rect rect;
	rect.w = rect.h = workingTilemap->tileSize;

	int startX = workingTilemap->cameraX/workingTilemap->tileSize;
	if(startX > 0)
		startX += 1;
	int offsetX = workingTilemap->cameraX - (startX*workingTilemap->tileSize);

	int	startY = workingTilemap->cameraY/workingTilemap->tileSize;
	int offsetY = workingTilemap->cameraY - (startY*workingTilemap->tileSize);

	for(i=startX; i < (startX + workingTilemap->renderWidth/workingTilemap->tileSize); i++) {
		for(j=startY; j < (startY + workingTilemap->renderHeight/workingTilemap->tileSize); j++) {
			rect.x = workingTilemap->object.x + (i-startX) * workingTilemap->tileSize - offsetX;
			rect.y = workingTilemap->object.y + (j-startY) * workingTilemap->tileSize - offsetY;
			if(RGS_GetMouseX() > rect.x && RGS_GetMouseX() < rect.x + rect.w && RGS_GetMouseY() > rect.y && RGS_GetMouseY() < rect.y + rect.h) {
				if(i <= workingTilemap->mapWidth && j < workingTilemap->mapHeight) {
					if(paintMode == PAINT_MODE_GFX && gfxPaintMode == GFX_PAINT_BRUSH && brushTilemap != NULL) {
						brushTilemap->object.x = rect.x;
						brushTilemap->object.y = rect.y;
						brushTilemap->object.visible = 1;
					}
					if(paintMode == PAINT_MODE_BRUSHDEFSTART) {
						tileSelector->object.x = rect.x;
						tileSelector->object.y = rect.y;
						tileSelector->object.w = workingTilemap->tileSize;
						tileSelector->object.h = workingTilemap->tileSize;
						tileSelector->object.visible = 1;
					} else if(paintMode == PAINT_MODE_BRUSHDEFEND) {
						tileSelector->object.w = RGS_GetMouseX() - tileSelector->object.x;
						tileSelector->object.w = tileSelector->object.w - (tileSelector->object.w % workingTilemap->tileSize) + workingTilemap->tileSize;
						tileSelector->object.h = RGS_GetMouseY() - tileSelector->object.y;
						tileSelector->object.h = tileSelector->object.h - (tileSelector->object.h % workingTilemap->tileSize) + workingTilemap->tileSize;
						tileSelector->object.visible = 1;
					} else {
						tileSelector->object.visible = 0;
					}
					curTileIndex = i+j*workingTilemap->mapWidth;
					if(painting == 1 && paintMode != PAINT_MODE_ENTITY)
						paintTile(curTileIndex);
				} else {
					if(brushTilemap != NULL)
						brushTilemap->object.visible = 0;
				}
			}

			if(selectedEntity != NULL && paintMode == PAINT_MODE_ENTITY && entityMode == ENTITY_MODE_SELECT) {

						if(painting == 1) {
							selectedEntity->x = RGS_GetMouseX()-workingTilemap->object.x+workingTilemap->cameraX-eDragOffsetX - (( RGS_GetMouseX()-workingTilemap->object.x+workingTilemap->cameraX-eDragOffsetX) % workingTilemap->tileSize);
							selectedEntity->y = RGS_GetMouseY()-workingTilemap->object.y+workingTilemap->cameraY-eDragOffsetY - ((RGS_GetMouseY()-workingTilemap->object.y+workingTilemap->cameraY-eDragOffsetY) % workingTilemap->tileSize);
							selectedEntity->object->onRelease = endChangeTile;
						}

						tileSelector->object.x = selectedEntity->object->x;
						tileSelector->object.y = selectedEntity->object->y;
						tileSelector->object.w = selectedEntity->object->w;
						tileSelector->object.h = selectedEntity->object->h;
						tileSelector->object.visible = 1;

			}

			if(i <= workingTilemap->mapWidth && j <= workingTilemap->mapHeight && showGeomTiles == 1) {
				if(workingTilemap->mapAttributeData[i+j*workingTilemap->mapWidth] == TILE_SOLID)
					RGS_FillRect(&rect, 0x00ff00);
			}

			if(i <= workingTilemap->mapWidth && j <= workingTilemap->mapHeight && showAttTiles == 1) {
				if(workingTilemap->userAttributeData[i+j*workingTilemap->mapWidth] != 0)
					RGS_FillRect(&rect, attColors[workingTilemap->userAttributeData[i+j*workingTilemap->mapWidth]]);
			}

		}
	}
}

void MapEditor_Hide() {
	mapEditorScreen->visible = 0;
	gfxScreen->visible = 0;
	geomScreen->visible = 0;
	attScreen->visible = 0;
	entityOverlayScreen->visible = 0;
	entityScreen->visible = 0;
}

void MapEditor_Show() {
	mapEditorScreen->visible = 1;
	choosePaintMode(PAINT_MODE_GFX, NULL);
}

void MapEditor_ImportTilemap(RGS_Surface *srcSurface, int tileSize) {
	if(curTilemapTilePath == NULL) {
		RGS_SetLabelText(errorMessageLabel, "ERROR: You need to choose a tileset first!");
		return;
	}

	if(workingTilemap != NULL) {
		RGS_DestroyObject((RGS_Object*)workingTilemap);
	}

	RGS_ScreenDestroyObjects(entityOverlayScreen);
	workingTilemap = RGS_CreateEmptyTilemap(mapEditorScreen, 1024-EDITOR_LEFT_MARGIN-30, 768-EDITOR_TOP_MARGIN-30, srcSurface->surface->w/tileSize, srcSurface->surface->h/tileSize,  tileSize, curTilemapTilePath);
	setupNewTilemap();

	int i,j,l,m,n;
	int bufferSize = tileSize*tileSize;
	Uint8 *tempBuffer = (Uint8*)malloc(bufferSize);
	Uint8 *tempTileBuffer = (Uint8*)malloc(bufferSize);
	int missingByte = 0;

	Uint8 *pixPtr = (Uint8*)srcSurface->surface->pixels;

	Uint8 *tilePixPtr = (Uint8*)workingTilemap->tilesSurface->surface->pixels;
	Uint16 newTileMatch;

	RGS_Color c1,c2;

	for(i=0;i<workingTilemap->mapHeight;i++) {
		for(j=0;j<workingTilemap->mapWidth;j++) {
			for(l=0;l<tileSize;l++) {
				memcpy(tempBuffer+(tileSize*l), pixPtr+((((i*workingTilemap->mapWidth*tileSize)*tileSize)+(j*tileSize))+(srcSurface->surface->w*l)), tileSize);
			}
			newTileMatch = 0;
			for(m=0;m<workingTilemap->tilesSurface->surface->h/tileSize;m++) {
				for(n=0;n<workingTilemap->tilesSurface->surface->w/tileSize;n++) {
					for(l=0;l<tileSize;l++) {
						memcpy(tempTileBuffer+(tileSize*l), tilePixPtr+((((m*(workingTilemap->tilesSurface->surface->w/tileSize)*tileSize)*tileSize)+(n*tileSize))+(workingTilemap->tilesSurface->surface->w*l)), tileSize);
					}
					missingByte = 0;
					for(l=0; l < bufferSize;l++) {
						c1 = RGS_GetSurfaceColorByIndex(srcSurface, tempBuffer[l]);
						c2 =  RGS_GetSurfaceColorByIndex(workingTilemap->tilesSurface, tempTileBuffer[l]);
						if(c1.r != c2.r || c1.g != c2.g || c1.b != c2.b) {
							missingByte = 1;
						}
					}
					if(missingByte == 0)
						newTileMatch = m*(workingTilemap->tilesSurface->surface->w/tileSize)+n;
				}
			}

			workingTilemap->mapTileData[(i*workingTilemap->mapWidth)+j] = newTileMatch;
		}
	}
	MapEditor_Show();
}

void MapEditor_CreateTiles(RGS_Surface *srcSurface, char *destFile, int tileSize) {
	int i,j,k,l;
	int tileWidth = srcSurface->surface->w / tileSize;
	int tileHeight = srcSurface->surface->h / tileSize;
	int bufferSize = tileSize*tileSize;
	int hasTile = 0;
	int missingByte = 0;

	Uint8 *pixPtr = (Uint8*)srcSurface->surface->pixels;

	Uint8 *tempBuffer = (Uint8*)malloc(bufferSize);
	int numTiles=0;
	Uint8 **tileBuffer = NULL;

	for(i=0; i < tileHeight; i++) {
		for(j=0; j < tileWidth; j++) {
			// copy tile to buffer
			for(l=0;l<tileSize;l++) {
				memcpy(tempBuffer+(tileSize*l), pixPtr+((((i*tileWidth*tileSize)*tileSize)+(j*tileSize))+(srcSurface->surface->w*l)), tileSize);
			}

			hasTile = 0;
			for(k=0;k<numTiles;k++) {
				missingByte = 0;
				for(l=0; l < bufferSize;l++) {
					if(tileBuffer[k][l] != tempBuffer[l]) {
						missingByte = 1;
					}
				}
				if(missingByte == 0) {
					hasTile = 1;
					break;
				}
			}

			if(hasTile == 0) {
				tileBuffer = (Uint8**)realloc(tileBuffer, (sizeof(Uint8*)*(numTiles+1)));
				tileBuffer[numTiles] = NULL;
				tileBuffer[numTiles] = (Uint8*)malloc(bufferSize);
				memcpy(tileBuffer[numTiles], tempBuffer, bufferSize);
				numTiles++;
			}
		}
	}

	int optimalSize = ceil(pow(numTiles, 0.5));
	RGS_Surface *newSurface = RGS_CreateSurfaceFromSurface(srcSurface, optimalSize*tileSize, optimalSize*tileSize);
	pixPtr = (Uint8*)newSurface->surface->pixels;

	int yOffset = 0;
	for(i=0;i<numTiles;i++) {
		if(i%optimalSize == 0 && i != 0)
			yOffset+=tileSize;
		for(j=0;j<tileSize;j++) {
			memcpy(pixPtr+((yOffset*optimalSize*tileSize)+(j*optimalSize*tileSize)+((i*tileSize) % (optimalSize*tileSize))), tileBuffer[i]+(j*tileSize), tileSize);
		}
	}

	RGS_WriteSurface(newSurface, destFile, 0);

	if(numTiles > 0) {
		free(tileBuffer);
	}
	free(tempBuffer);
}


text:
#include <mex.h>
#include <stdlib.h>
#include <math.h>
#include "matrix.h"
#include "ow_homography.h"

#define thetax(k) (theta_list[(k)*3])
#define thetay(k) (theta_list[(k)*3+1])
#define thetaz(k) (theta_list[(k)*3+2])

double round(double val)
{
    return floor(val + 0.5);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    mxArray const* imsharp_ptr     = prhs[0]; /* sharp image */
    mxArray const* dims_blurry_ptr = prhs[1]; /* dimensions of blurry image */
    mxArray const* Ksharp_ptr      = prhs[2]; /* Intrinsic calibration of sharp image */
    mxArray const* Kblurry_ptr     = prhs[3]; /* intrinsic calibration of blurry image */
    mxArray const* theta_list_ptr  = prhs[4]; /* Orientations covered by blur kernel */
    mxArray const* kernel_ptr      = prhs[5]; /* Kernel */
    bool const clamp_edges_to_zero = (bool const)mxGetScalar(prhs[6]); /* Set blurry pixels to zero if they involve sharp pixels outside the image? */
    bool const non_uniform         = (bool const)mxGetScalar(prhs[7]); /* Non-uniform blur model? */

    int const n_kernel = mxGetN(theta_list_ptr); /* Number of kernel elements */

    double const *imsharp     = mxGetPr(imsharp_ptr);
    double const *dims_blurry = mxGetPr(dims_blurry_ptr);
    double const *Ksharp      = mxGetPr(Ksharp_ptr);
    double const *Kblurry     = mxGetPr(Kblurry_ptr);
    double const *theta_list  = mxGetPr(theta_list_ptr);
    double const *kernel      = mxGetPr(kernel_ptr);

    int const numdims     = mxGetNumberOfDimensions(imsharp_ptr);
    int const *dims_sharp = mxGetDimensions(imsharp_ptr);
    int const h_sharp     = dims_sharp[0];
    int const w_sharp     = dims_sharp[1];
    int const channels    = (numdims==3) ? dims_sharp[2] : 1;
    int const h_blurry    = (int const)dims_blurry[0];
    int const w_blurry    = (int const)dims_blurry[1];
    int const n_sharp     = h_sharp*w_sharp;
    int const n_blurry    = h_blurry*w_blurry;

    int full_dims_blurry[3];

    mxArray* imblurry_ptr;
    double *imblurry;

    int xi, yi;
    double yj, xj;
    int yjfloor, xjfloor;
    double H[9];
    double R[9];
    double coeffs[4];
    double invKblurry[9];

    int i, j, c, k;

    /* Compute offsets for each channel, so we're not constantly computing c*height*width */
    int* chan_offset_sharp = (int *)mxMalloc(sizeof(int) * channels);
    int* chan_offset_blurry = (int *)mxMalloc(sizeof(int) * channels);
    for(c=0; c<channels; ++c) {
        chan_offset_sharp[c]  = c*h_sharp*w_sharp;
        chan_offset_blurry[c] = c*h_blurry*w_blurry;
    }

    full_dims_blurry[0] = h_blurry;
    full_dims_blurry[1] = w_blurry;
    full_dims_blurry[2] = channels;
    imblurry_ptr = mxCreateNumericArray(3, full_dims_blurry, mxDOUBLE_CLASS, mxREAL);
    imblurry = mxGetPr(imblurry_ptr);

    /* Check thetas -- for uniform blur theta must contain only integers */
    if(!non_uniform) {
        for(k=0; k<n_kernel; ++k)
            if(fabs(round(thetay(k))-thetay(k)) > 1e-10 ||     \
               fabs(round(thetax(k))-thetax(k)) > 1e-10)
               mexErrMsgTxt("theta not integral for uniform blur");
    }

    inv3(Kblurry,invKblurry);
    /* Loop over all rotations */
    for(k=0; k<n_kernel; ++k) {
        if (kernel[k]==0) continue;
        /* Loop over all blurry image pixels:
            (xi,yi): 1-based 2D position in blurry image */
        for(xi=1; xi<=w_blurry; ++xi) {
            for(yi=1; yi<=h_blurry; ++yi) {
                /* i: 0-based linear index into blurry image */
                i = (mwIndex)((xi-1)*h_blurry + yi - 1);
                /* Project blurry image pixel (xi,yi) into sharp image.
                    1-based 2D position in sharp image is (xj,yj) */
                if (non_uniform) {
                    compute_homography_matrix(Ksharp, &theta_list[k*3], invKblurry, H);
                    project_blurry_to_sharp(yi, xi, H, &xj, &yj);
                } else {
                    xj = xi + round(thetax(k));
                    yj = yi + round(thetay(k));
                }
                /* Check if (xj,yj) lies outside domain of sharp image */
                if (yj<1 || yj>=h_sharp || xj<1 || xj>=w_sharp) {
                    /* Flag the pixel as having been influenced by edge effects */
                    if (clamp_edges_to_zero)
                        for(c=0; c<channels; ++c)
                            imblurry[i+chan_offset_blurry[c]] = -1e10;
                    continue;
                }
                /* Get floor(xj,yj) and interpolation coefficients */
                if(non_uniform) {
                    interp_coeffs(xj,yj,&xjfloor,&yjfloor,coeffs);
                } else {
                    xjfloor = (int)xj;
                    yjfloor = (int)yj;
                }
                /* j: 0-based linear index into sharp image */
                j = (mwIndex)((xjfloor-1)*h_sharp + yjfloor - 1);
                /* Do interpolation */
                if(non_uniform) {
                    for(c=0; c<channels; ++c)
                        imblurry[i+chan_offset_blurry[c]] += kernel[k]*(coeffs[0]*imsharp[j+chan_offset_sharp[c]] + \
                                                                        coeffs[1]*imsharp[j+1+chan_offset_sharp[c]] + \
                                                                        coeffs[2]*imsharp[j+h_sharp+chan_offset_sharp[c]] + \
                                                                        coeffs[3]*imsharp[j+h_sharp+1+chan_offset_sharp[c]]);
                } else {
                    for(c=0; c<channels; ++c)
                        imblurry[i+chan_offset_blurry[c]] += kernel[k]*imsharp[j+chan_offset_sharp[c]];
                }
            }
        }
    }
    /* Set all flagged pixels to zero */
    for(i=0; i<n_blurry; ++i)
        for(c=0; c<channels; ++c)
            if(imblurry[i+chan_offset_blurry[c]] <= -1e5)
                imblurry[i+chan_offset_blurry[c]] = 0;
    /* Assign output */
    plhs[0] = imblurry_ptr;

    mxFree(chan_offset_sharp);
    mxFree(chan_offset_blurry);
}

redpajama_set_name: RedPajamaGithub


text:
d=$(dirname "$0")
MAIN_CLASS=$1
LIBRARIES=$2
[ "${MAIN_CLASS}" ] || { echo "Run 'ant eclipse' to generate Eclipse project files"; exit 1; }

cat >"$d/.project" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>floodlight</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>org.eclipse.jdt.core.javabuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>org.eclipse.jdt.core.javanature</nature>
	</natures>
</projectDescription>
EOF

cat >"$d/Floodlight-Default-Conf.launch" << EOF
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
    <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
        <listEntry value="/floodlight/src/main/java/net/floodlightcontroller/core/Main.java"/>
    </listAttribute>
    <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
        <listEntry value="1"/>
    </listAttribute>
    <stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="net.floodlightcontroller.core.Main"/>
    <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="floodlight"/>
    <stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-ea"/>
</launchConfiguration>
EOF

cat > "$d/Floodlight-Quantum-Conf.launch" << EOF
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
    <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
        <listEntry value="/floodlight/src/main/java/net/floodlightcontroller/core/Main.java"/>
    </listAttribute>
    <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
        <listEntry value="1"/>
    </listAttribute>
    <stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="net.floodlightcontroller.core.Main"/>
    <stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-cf src/main/resources/quantum.properties"/>
    <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="floodlight"/>
    <stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-ea"/>
</launchConfiguration>
EOF

cat >"$d/SyncClient.launch" << EOF
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/floodlight/src/main/java/org/sdnplatform/sync/client/SyncClient.java"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="1"/>
</listAttribute>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.sdnplatform.sync.client.SyncClient"/>
<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="--hostname localhost --port 6642 --authScheme CHALLENGE_RESPONSE --keyStorePath /opt/bigswitch/floodlight/configuration/auth_credentials.jceks --keyStorePassword dcbc178a0a3a8674f048ac86372ac456"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="bigfloodlight"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-ea"/>
</launchConfiguration>
EOF

cat >"$d/.classpath" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="src" path="src/main/java" output="target/bin"/>
	<classpathentry kind="src" path="src/main/resources"/>
        <classpathentry kind="src" path="src/test/java" output="target/bin-test"/>
	<classpathentry kind="src" path="src/test/resources"/>
        <classpathentry kind="src" path="lib/gen-java" output="target/bin"/>
EOF
(
IFS=":"
for l in ${LIBRARIES}; do
cat >>$d/.classpath <<EOF
	<classpathentry exported="true" kind="lib" path="$l"/>
EOF
done
)
cat >>"$d/.classpath" <<EOF
	<classpathentry exported="true" kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
	<classpathentry kind="output" path="target/bin"/>
</classpath>
EOF

mkdir -p $d/.settings
cat >$d/.settings/edu.umd.cs.findbugs.core.prefs  <<EOF
excludefilter0=findbugs-exclude.xml|true
filter_settings=Medium|BAD_PRACTICE,CORRECTNESS,MALICIOUS_CODE,MT_CORRECTNESS,PERFORMANCE,SECURITY,STYLE|false|20
filter_settings_neg=NOISE,I18N,EXPERIMENTAL|
EOF


text:
<!---
  category: ControlsLayoutAndText NetworkingAndWebServices
  language: cs
  keywords: xbox mobile desktop iot azure iot-hub azure-event-hub azure-stream-analytics
-->

# The IoT Experience

Best For You is a sample fitness UWP app that uses Windows IoT Core and Azure Iot Hub to collect data from a fictional IoT enabled yoga clothes and presenting it to the user in a meaningful and helpful way on all of their devices to track progress of exercise and health.

![BestForYou](http://i.imgur.com/PdDt7lR.png)

**Features:** | Windows IoT Core | Azure IoT Hub | Azure Event Hub | Azure Stream Analytics
---|---|---|---|---

The solution contains two client side projects and several Azure services:

1. UWP client app designed for Xbox One, Desktop, and Mobile
2. UWP IoT app intended to run on an IoT device such as the Raspberry Pi 3 (it can also run on any other UWP device for demo purposes)
3. Azure IoT Hub, Azure Event Hub, Azure Stream Analytics and more

![Architecture](http://i.imgur.com/a1I5wBg.png)

## Setup

### Cloud
To deploy the Best For Me solution to your Azure subscription you will need to follow the below instructions. We are using Azure Resource Manager to deploy the needed services and connect them to one another. We are also using the Azure cross platform CLI tool which will allow you to deploy the services from your favorite development machine, running Windows, Linux or OSX. The below services will be deployed in your Azure subscription:
* 1 instance of Azure IoT Hub (using the SKU of your choice, considering you can only deploy 1 instance of the free SKU per subscription)
* 1 Storage account (Standard performance)
* 1 Service Bus instance (Basic tier) with 1 Event Hub (1 throughput Unit)
* 1 Stream Analytics Job (1 streaming unit)

The simplest way is to click on the button below and follow instructions. If you prefer command line tools, or to learn more, checkout the [ConnectTheDots project](https://github.com/Azure/connectthedots).

[![Deploy to Azure](http://azuredeploy.net/deploybutton.png)](https://azuredeploy.net/?repository=https://github.com/Microsoft/AppDevXbox/tree/BestForYou_iot_app/ARMTemplate)

### Client
1. Add IoT Hub Connected Service to the HeartRateDevice project and connect it to the IoT Hub service you created in the previous section
    * Make sure Visual Studio is closed and install the [Connected Service for Azure IoT Hub](https://visualstudiogallery.msdn.microsoft.com/e254a3a5-d72e-488e-9bd3-8fee8e0cd1d6)
    * Launch Visual Studio, right click on the *HeartRateDevice* project and click on **Add Connected Service**
    * Choose Azure IoT Hub and click configure
    * Choose **Hardcore shared access key in application's code**
    * Make sure you are logged in to Visual Studio with the same account associated with the Azure subscription and select the IoT Hub project you created in the previous section
    * Chose a device to connect - most likely you will need to create one
    * Click OK

2.  In the HeartRateDevice application, change the SendDeviceToCloudMessageAsync method in the *AzureIoTHub.cs* file to the following:

   ```csharp
   public static async Task SendDeviceToCloudMessageAsync(double heartBeat)
   {
      var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Amqp);
      var message = new Message(Encoding.ASCII.GetBytes(heartBeat.ToString()));
      await deviceClient.SendEventAsync(message);
   }
   ```

   That's it for the HeartRateDevice, feel free to run it on your desktop and play around with the slider to send the data to Azure IoT Hub. If you want to run it on a real IoT Device, you can run it on a Raspberry Pi 3. We used the [FEZ HAT](https://www.ghielectronics.com/catalog/product/500) to simulate heart rate by pressing one of the buttons. For more info on connecting your app to Azure IoT Hub, check out [this blog post](https://blogs.windows.com/buildingapps/2016/03/03/connect-your-windows-app-to-azure-iot-hub-with-visual-studio/)

3. Next, you will need to add the correct strings in the *Keys.cs* source file in the Yoga project so it can receive the data from the HeartRateDevice through the IoT Hub and Event Hub.
    * **EventHubCompatibleEndpoint** and **EventHubCompatibleName** are found in the Azure Portal under the Event Hub -> Messaging section
    * **IoTHubAccessPolicyName** and **IoTHubAccessPolicyPrimaryKey** are found in the Azure Portal under the IoT Hub -> Settings -> Shared Policies

    The project uses the [Azure SB Lite](https://github.com/ppatierno/azuresblite) library to receive the IoT Hub data. Visit [this blog post](https://paolopatierno.wordpress.com/2015/11/02/azure-iot-hub-get-telemetry-data-using-amqp-stack-and-azure-sb-lite/) to learn more about it.

4. Run

***

## Next Steps ##
<!--- #### - Download the sample from the Windows Store. --->

#### - Read the [blog post](https://blogs.windows.com/buildingapps/2016/10/13/internet-of-things-on-the-xbox-app-dev-on-xbox-series)

#### - Download the source by clicking on **Clone or download** above

#### - View the [one minute dev video](https://channel9.msdn.com/Blogs/One-Dev-Minute/Creating-IoT-apps-for-the-Xbox)


text:
package com.cky.learnandroiddetails.MVP;

/**
 * Created by cuikangyuan on 16/7/29.
 */
public class LoginPresenterImpl implements LoginPresenter, OnLoginFinishedListener {

    private LoginView mLoginView;

    private LoginModel mLoginModel;

    public LoginPresenterImpl(LoginView loginView) {
        mLoginView = loginView;
        mLoginModel = new LoginModelImpl();
    }

    @Override
    public void validateCredentials(String username, String password) {
        if (mLoginView != null) {
            mLoginView.showProgress();
        }

        mLoginModel.login(username, password, this);
    }

    @Override
    public void onDestroy() {
        mLoginView = null;
    }

    @Override
    public void onSuccess() {
        if (mLoginView != null) {
            mLoginView.hideProgress();
            mLoginView.navigateToHome();
        }
    }

    @Override
    public void onUsernameError() {
        if (mLoginView != null) {
            mLoginView.setUsernameError();
            mLoginView.hideProgress();
        }
    }

    @Override
    public void onPasswordError() {
        if (mLoginView != null) {
            mLoginView.setPasswordError();
            mLoginView.hideProgress();
        }
    }
}


text:
import string
import spacy
from spacy.symbols import VERB

splits = [' is it ', ' is ', ' am ', 'open ', ' for ']

nlp = spacy.load('en')

def make_subject(x):
    if len(x.split()) == 1:
        return 'no subject'
    else:
        for s in splits:
            if s in x:
                return x.split(s)[-1].lower()
    return x.lower()

def make_root(x):
    for s in splits:
        if s in x:
            return x.split(s)[0].lower() + ' ' + s
    return x.lower()

def parse_data(user_request):
    user_request.replace("'s", ' is')
    user_request = ''.join([i for i in user_request if i not in string.punctuation])
    return make_subject(user_request), make_root(user_request)

def parse(request):
    doc = nlp(request)
    verbs = set()
    for token in doc:
        if token.pos == VERB:
            verbs.add(token.lemma_.lower())

    entities = {}
    for ent in doc.ents:
        entities.update({ent.label_: ent.text})

    core_sub, core_root = parse_data(request)

    data = {
        'verbs': verbs,
        'entities': entities,
        'doc': doc,
        'parse': lambda x: nlp(x),
        'request': request,
        'core_subject': core_sub,
        'core_root': core_root

    }

    return data

def split(request, splitter=' '):
    if splitter == ' ':
        return request.split(splitter)
    else:
        request.split(splitter)
        x = split(request=request)
        return x

def find_name_location(data, name):
    num = data.find(name)
    return num + len(name) + 1


text:
import {isExperimentOn} from '../../../src/experiments';
import {user} from '../../../src/log';

const TAG = 'amp-animation';

export class AmpAnimation extends AMP.BaseElement {

  /** @override */
  buildCallback() {
    user().assert(isExperimentOn(this.win, TAG),
        `Experiment "${TAG}" is disabled.`);
  }
}

AMP.registerElement(TAG, AmpAnimation);


text:
#include <gtest/gtest.h>
#include <cds/container/fcstack.h>

#include <vector>
#include <list>

namespace {
    class FCStack : public ::testing::Test
    {
    protected:
        template <class Stack>
        void test()
        {
            typedef typename Stack::value_type  value_type;
            Stack stack;
            value_type v;

            ASSERT_TRUE( stack.empty());
            ASSERT_EQ( stack.size(), 0u );

            ASSERT_TRUE( stack.push( 1 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 1u );
            ASSERT_TRUE( stack.push( 2 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 2u );
            ASSERT_TRUE( stack.push( 3 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 3u );

            ASSERT_TRUE( stack.pop( v ));
            EXPECT_EQ( v, value_type( 3 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 2u );
            ASSERT_TRUE( stack.pop( v ));
            EXPECT_EQ( v, value_type( 2 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 1u );
            ASSERT_TRUE( stack.pop( v ));
            EXPECT_EQ( v, value_type( 1 ));
            ASSERT_TRUE( stack.empty());
            ASSERT_EQ( stack.size(), 0u );
            v = 1000;
            ASSERT_TRUE( !stack.pop( v ));
            EXPECT_EQ( v, value_type( 1000 ));
            ASSERT_TRUE( stack.empty());
            ASSERT_EQ( stack.size(), 0u );

            ASSERT_TRUE( stack.push( 10 ));
            ASSERT_TRUE( stack.push( 20 ));
            ASSERT_TRUE( stack.push( 30 ));
            ASSERT_TRUE( !stack.empty());
            ASSERT_EQ( stack.size(), 3u );

            while ( stack.pop( v ));

            ASSERT_TRUE( stack.empty());
            ASSERT_EQ( stack.size(), 0u );
        }
    };

    TEST_F( FCStack, default_stack )
    {
        typedef cds::container::FCStack< unsigned int > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_based )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>> stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_empty_wait_strategy )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
                cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::empty>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_single_mutex_single_condvar )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_single_mutex_multi_condvar )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_multi_mutex_multi_condvar )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_single_mutex_single_condvar_2ms )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<2>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_single_mutex_multi_condvar_2ms )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<2>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_multi_mutex_multi_condvar_3ms )
    {
        struct stack_traits: public
            cds::container::fcstack::make_traits <
            cds::opt::wait_strategy<cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<3>>
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, deque_elimination )
    {
        struct stack_traits : public
            cds::container::fcstack::make_traits <
            cds::opt::enable_elimination < true >
            > ::type
        {};
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::deque<unsigned int>>, stack_traits > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_based )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>> stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_empty_wait_strategy )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::empty >
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_multi_mutex_multi_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_single_mutex_multi_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_single_mutex_single_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, vector_elimination )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::vector<unsigned int>>,
            cds::container::fcstack::make_traits<
            cds::opt::enable_elimination< true >
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_based )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>> stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_empty_wait_strategy )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::empty >
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_single_mutex_single_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_single_mutex_multi_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_multi_mutex_multi_condvar )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
            >::type
        > stack_type;
        test<stack_type>();
    }

    TEST_F( FCStack, list_elimination )
    {
        typedef cds::container::FCStack< unsigned int, std::stack<unsigned int, std::list<unsigned int>>,
            cds::container::fcstack::make_traits<
                cds::opt::enable_elimination< true >
                , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<2>>
            >::type
        > stack_type;
        test<stack_type>();
    }
} // namespace


text:
title: Tea Party
---
I printed invitations for [Risley](http://en.wikipedia.org/wiki/Risley_Residential_College)'s
40th anniversary tea party.

!["PR" stamp](<%= @item.identifier %>pr.jpg)

![A letterpress-printed card](<%= @item.identifier %>text.jpg)

![A card being printed in a platen press](<%= @item.identifier %>printing.jpg)


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _DOCUMENT_H_
#define _DOCUMENT_H_

class PrintParamsObj : public CJS_EmbedObj
{
public:
	PrintParamsObj(CJS_Object* pJSObject);
	virtual ~PrintParamsObj(){}

public:
	FX_BOOL bUI;
	int nStart;
	int nEnd;
	FX_BOOL bSilent;
	FX_BOOL bShrinkToFit;
	FX_BOOL bPrintAsImage;
	FX_BOOL bReverse;
	FX_BOOL bAnnotations;
};

class CJS_PrintParamsObj : public CJS_Object
{
public:
	CJS_PrintParamsObj(JSFXObject pObject) : CJS_Object(pObject) {}
	virtual ~CJS_PrintParamsObj(){}

	DECLARE_JS_CLASS(CJS_PrintParamsObj);
};

class Icon;
class Field;

struct IconElement
{
	IconElement() : IconName(L""), NextIcon(NULL), IconStream(NULL) {}
	virtual ~IconElement()
	{
	}
	CFX_WideString	IconName;
	IconElement*	NextIcon;
	Icon*			IconStream;
};

class IconTree
{
public:
	IconTree():m_pHead(NULL), m_pEnd(NULL), m_iLength(0)
	{

	}

	virtual ~IconTree()
	{
	}

public:
	void			InsertIconElement(IconElement* pNewIcon);
	void			DeleteIconElement(CFX_WideString swIconName);
	void			DeleteIconTree();
	int				GetLength();
	IconElement*	operator[](int iIndex);

private:
	IconElement*	m_pHead;
	IconElement*	m_pEnd;
	int				m_iLength;
};

struct CJS_DelayData;
struct CJS_DelayAnnot;
struct CJS_AnnotObj;

class Document : public CJS_EmbedObj
{
public:
	Document(CJS_Object* pJSObject);
	virtual ~Document();

public:
	FX_BOOL	ADBE(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	author(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	baseURL(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	bookmarkRoot(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	calculate(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	Collab(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	creationDate(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	creator(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	delay(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	dirty(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	documentFileName(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL external(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	filesize(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	icons(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	info(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	keywords(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	layout(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	media(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	modDate(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	mouseX(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	mouseY(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	numFields(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	numPages(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	pageNum(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	pageWindowRect(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	path(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	producer(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	subject(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	title(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	zoom(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);
	FX_BOOL	zoomType(IFXJS_Context* cc, CJS_PropValue& vp, JS_ErrorString& sError);

	FX_BOOL addAnnot(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	addField(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	addLink(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	addIcon(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	calculateNow(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	closeDoc(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	createDataObject(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL deletePages(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	exportAsText(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	exportAsFDF(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	exportAsXFDF(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL extractPages(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getAnnot(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getAnnots(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getAnnot3D(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getAnnots3D(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getField(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getIcon(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getLinks(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getNthFieldName(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getOCGs(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getPageBox(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getPageNthWord(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getPageNthWordQuads(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	getPageNumWords(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL getPrintParams(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL getURL(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	importAnFDF(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	importAnXFDF(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	importTextData(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL insertPages(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	mailForm(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	print(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	removeField(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL replacePages(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	resetForm(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	saveAs(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	submitForm(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	mailDoc(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);
	FX_BOOL	removeIcon(IFXJS_Context* cc, const CJS_Parameters& params, CJS_Value& vRet, JS_ErrorString& sError);

public:
	void AttachDoc(CPDFSDK_Document* pDoc);
	CPDFSDK_Document* GetReaderDoc();

	static FX_BOOL				ExtractFileName(CPDFSDK_Document* pDoc, CFX_ByteString& strFileName);
	static FX_BOOL				ExtractFolderName(CPDFSDK_Document* pDoc, CFX_ByteString& strFolderName);

public:
	void						AddDelayData(CJS_DelayData* pData);
	void						DoFieldDelay(const CFX_WideString& sFieldName, int nControlIndex);

	void						AddDelayAnnotData(CJS_AnnotObj *pData);
	void						DoAnnotDelay();
	void						SetIsolate(v8::Isolate* isolate) {m_isolate = isolate;}

private:
	CFX_WideString				ReversalStr(CFX_WideString cbFrom);
	CFX_WideString				CutString(CFX_WideString cbFrom);
	bool						IsEnclosedInRect(CFX_FloatRect rect, CFX_FloatRect LinkRect);
	int							CountWords(CPDF_TextObject* pTextObj);
	CFX_WideString				GetObjWordStr(CPDF_TextObject* pTextObj, int nWordIndex);

	FX_BOOL						ParserParams(JSObject *pObj,CJS_AnnotObj& annotobj);

private:
	v8::Isolate*					m_isolate;
	IconTree*					m_pIconTree;
	CPDFSDK_Document*			m_pDocument;
	CFX_WideString				m_cwBaseURL;

	FX_BOOL								m_bDelay;
	CFX_ArrayTemplate<CJS_DelayData*>	m_DelayData;
	CFX_ArrayTemplate<CJS_AnnotObj*>	m_DelayAnnotData;
};

class CJS_Document : public CJS_Object
{
public:
	CJS_Document(JSFXObject pObject) : CJS_Object(pObject) {};
	virtual ~CJS_Document(){};

	virtual FX_BOOL	InitInstance(IFXJS_Context* cc);

	DECLARE_JS_CLASS(CJS_Document);

	JS_STATIC_PROP(ADBE, Document);
	JS_STATIC_PROP(author, Document);
	JS_STATIC_PROP(baseURL, Document);
	JS_STATIC_PROP(bookmarkRoot, Document);
	JS_STATIC_PROP(calculate, Document);
	JS_STATIC_PROP(Collab, Document);
	JS_STATIC_PROP(creationDate, Document);
	JS_STATIC_PROP(creator, Document);
	JS_STATIC_PROP(delay, Document);
	JS_STATIC_PROP(dirty, Document);
	JS_STATIC_PROP(documentFileName, Document);
	JS_STATIC_PROP(external, Document);
	JS_STATIC_PROP(filesize, Document);
	JS_STATIC_PROP(icons, Document);
	JS_STATIC_PROP(info, Document);
	JS_STATIC_PROP(keywords, Document);
	JS_STATIC_PROP(layout, Document);
	JS_STATIC_PROP(media, Document);
	JS_STATIC_PROP(modDate, Document);
	JS_STATIC_PROP(mouseX, Document);
	JS_STATIC_PROP(mouseY, Document);
	JS_STATIC_PROP(numFields, Document);
	JS_STATIC_PROP(numPages, Document);
	JS_STATIC_PROP(pageNum, Document);
	JS_STATIC_PROP(pageWindowRect, Document);
	JS_STATIC_PROP(path, Document);
	JS_STATIC_PROP(producer, Document);
	JS_STATIC_PROP(subject, Document);
	JS_STATIC_PROP(title, Document);
	JS_STATIC_PROP(zoom, Document);
	JS_STATIC_PROP(zoomType, Document);

	JS_STATIC_METHOD(addAnnot,Document);
	JS_STATIC_METHOD(addField, Document);
	JS_STATIC_METHOD(addLink, Document);
	JS_STATIC_METHOD(addIcon, Document);
	JS_STATIC_METHOD(calculateNow, Document);
	JS_STATIC_METHOD(closeDoc, Document);
	JS_STATIC_METHOD(createDataObject, Document);
	JS_STATIC_METHOD(deletePages, Document);
	JS_STATIC_METHOD(exportAsText, Document);
	JS_STATIC_METHOD(exportAsFDF, Document);
	JS_STATIC_METHOD(exportAsXFDF, Document);
	JS_STATIC_METHOD(extractPages, Document);
	JS_STATIC_METHOD(getAnnot, Document);
	JS_STATIC_METHOD(getAnnots, Document);
	JS_STATIC_METHOD(getAnnot3D, Document);
	JS_STATIC_METHOD(getAnnots3D, Document);
	JS_STATIC_METHOD(getField, Document);
	JS_STATIC_METHOD(getIcon, Document);
	JS_STATIC_METHOD(getLinks, Document);
	JS_STATIC_METHOD(getNthFieldName, Document);
	JS_STATIC_METHOD(getOCGs, Document);
	JS_STATIC_METHOD(getPageBox, Document);
	JS_STATIC_METHOD(getPageNthWord, Document);
	JS_STATIC_METHOD(getPageNthWordQuads, Document);
	JS_STATIC_METHOD(getPageNumWords, Document);
	JS_STATIC_METHOD(getPrintParams, Document);
	JS_STATIC_METHOD(getURL, Document);
	JS_STATIC_METHOD(importAnFDF, Document);
	JS_STATIC_METHOD(importAnXFDF, Document);
	JS_STATIC_METHOD(importTextData, Document);
	JS_STATIC_METHOD(insertPages, Document);
	JS_STATIC_METHOD(mailForm, Document);
	JS_STATIC_METHOD(print, Document);
	JS_STATIC_METHOD(removeField, Document);
	JS_STATIC_METHOD(replacePages, Document);
	JS_STATIC_METHOD(removeIcon, Document);
	JS_STATIC_METHOD(resetForm, Document);
	JS_STATIC_METHOD(saveAs, Document);
	JS_STATIC_METHOD(submitForm, Document);
	JS_STATIC_METHOD(mailDoc, Document);
};

#endif//_DOCUMENT_H_


text:
<?php

namespace Resque\Commands\Socket;

use Resque;
use Resque\Commands\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * TCP connect command class
 *
 * @author Michael Haynes <mike@mjphaynes.com>
 */
class Connect extends Command
{

    protected function configure()
    {
        $this->setName('socket:connect')
            ->setDefinition($this->mergeDefinitions(array(
                new InputOption('connecthost', null, InputOption::VALUE_OPTIONAL, 'The host to connect to.', '127.0.0.1'),
                new InputOption('connectport', null, InputOption::VALUE_OPTIONAL, 'The port to connect to.', Resque\Socket\Server::DEFAULT_PORT),
                new InputOption('connecttimeout', 't', InputOption::VALUE_OPTIONAL, 'The connection timeout time (seconds).', 10),
            )))
            ->setDescription('Connects to a php-resque receiver socket')
            ->setHelp('Connects to a php-resque receiver socket')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $host    = $this->getConfig('connecthost');
        $port    = $this->getConfig('connectport');
        $timeout = $this->getConfig('connecttimeout');

        $conn    = $host.':'.$port;
        $prompt  = 'php-resque '.$conn.'> ';

        $output->writeln('<comment>Connecting to '.$conn.'...</comment>');

        if (!($fh = @fsockopen('tcp://'.$host, $port, $errno, $errstr, $timeout))) {
            $output->writeln('<error>['.$errno.'] '.$errstr.' host '.$conn.'</error>');
            return;
        }

        // Set socket timeout to 200ms
        stream_set_timeout($fh, 0, 200 * 1000);

        $stdin = fopen('php://stdin', 'r');

        $prompting = false;

        Resque\Socket\Server::fwrite($fh, 'shell');

        while (true) {
            if (feof($fh)) {
                $output->writeln('<comment>Connection to '.$conn.' closed.</comment>');
                break;
            }

            $read   = array($fh, $stdin);
            $write  = null;
            $except = null;

            $selected = @stream_select($read, $write, $except, 0);
            if ($selected > 0) {
                foreach ($read as $r) {
                    if ($r == $stdin) {
                        $input = trim(fgets($stdin));

                        if (empty($input)) {
                            $output->write($prompt);
                            $prompting = true;
                        } else {
                            Resque\Socket\Server::fwrite($fh, $input);
                            $prompting = false;
                        }
                    } elseif ($r == $fh) {
                        $input = '';
                        while (($buffer = fgets($fh, 1024)) !== false) {
                            $input .= $buffer;
                        }

                        if ($prompting) {
                            $output->writeln('');
                        }

                        $output->writeln('<pop>'.trim($input).'</pop>');

                        if (!feof($fh)) {
                            $output->write($prompt);
                            $prompting = true;
                        }
                    }
                }
            }

            // Sleep for 10ms to stop CPU spiking
            usleep(10 * 1000);
        }

        fclose($fh);
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Lib (run) where

import Turtle
import qualified Data.Text as Text
import Copy--(rsync, SyncInfo)

-- https://github.com/Gabriel439/Haskell-Turtle-Library/issues/158
parser :: Parser (Text, Text, [Text])
parser = (,,) <$> (argText "source" "source directory to copy")
              <*> (argText "destination" "destination directory to copy")
              <*> (many (optText "exclude" 'e' "Exclude Following Paths(Coma separated List)"))

run :: IO ()
run = do
  (src, dst, exs) <- options
    "Continuesly copies source directory to given destinatio directory"
    parser
  let syncInfo = SyncInfo{source=src,
                          destination=dst,
                          excludes=exs}
  view $ rsync syncInfo
  watch (view.rsync) syncInfo


text:
package util;

/**
 * Created by Administrator on 2016/7/24.
 */
public interface HttpCallbackListener {
    void onFinish(String response);

    void onError(Exception e);
}


text:
var Sensor = require("../models/sensor");
var debug=require("debug")("controllers/sensor.js");
exports.sensorList = function (req, res, next) {
  Sensor.find({}, function (err, listSensors) {
    if (err) {
      debug(err);
      return next(err);
    }
		// Successful, so render
    res.send(listSensors);
  });
};
exports.sensorListForDeployment = function (req, res, next) {
	// need to map devices back up to deployments, eventually
  Sensor.find({deployment: req.params.deployment}, function (err, listSensors) {
    if (err) {
      debug(err);
      return next(err);
    }
		// Successful, so render
    res.send(listSensors);
  });
};
exports.sensorListForDevice = function (req, res, next) {
	// need to map devices back up to deployments, eventually
  Sensor.find({device: req.params.device}, function (err, listSensors) {
    if (err) {
      debug(err);
      return next(err);
    }
		// Successful, so render
    res.send(listSensors);
  });
};
exports.sensorDetail = function (req, res, next) {
  Sensor.findById(req.params._id, function (err, sensor) {
    if (err) {
      debug(err);
      return next(err);
    }
		// Successful, so render
    res.send(sensor);
  });
};
exports.sensorCreate = function (req, res, next) {
  var sensor = new Sensor({
    id: req.body.id,
    name: req.body.name,
    channel: req.body.channel,
    description: req.body.description,
    handler: req.body.handler,
    poll: 60000,
    config: req.body.config,
    location: req.body.location,
    active: req.body.active,
    sensortype: req.body.sensortype
  });
  sensor.save(function (err) {
    if (err) {
      debug(err);
      return next(err);
    }
    res.redirect(sensor.url);
  });
};
exports.sensorDelete = function (req, res, next) {
  Sensor.findOneAndUpdate({
    _id: req.body.id
  }, {
    active: false
  }, {
    upsert: false
  }, function (err, doc) {
    if (err) {
      debug(err);
      next(err);
    }
    return res.send("Sensor Deleted");
  });
};
exports.sensorUpdate = function (req, res, next) {
  Sensor.findOneAndUpdate({
    _id: req.body.id
  }, {
    id: req.body.id,
    name: req.body.name,
    channel: req.body.channel,
    description: req.body.description,
    handler: req.body.handler,
    poll: 60000,
    config: req.body.config,
    location: req.body.location,
    active: req.body.active,
    sensortype: req.body.sensortype
  }, {
    upsert: false
  },
		function (err, doc) {
  if (err) {
    debug(err);
    return res.send(500, {
      error: err
    });
  }
  res.send(doc);
});
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization.Json;
using System.Net.Http;

namespace DraftSimulator.ServerLogic
{
    public class DraftRunLocation
    {
        public string Country { get; set; }
        public string City { get; set; }
        public decimal Latitude { get; set; }
        public decimal Longitude { get; set; }

        public DraftRunLocation()
        {
            return;
        }

        public DraftRunLocation(decimal latitude, decimal longitude)
        {
            this.Latitude = latitude;
            this.Longitude = longitude;

            this.Country = GetCountryFromLatLong(latitude, longitude);
            this.City = GetCityFromLatLong(latitude, longitude);
        }

        public string GetCountryFromLatLong(decimal latitude, decimal longitude)
        {
            string bingMapsRESTCall = "http://dev.virtualearth.net/REST/v1/Locations/" + latitude.ToString() + "," + longitude.ToString() + "?&key=" + "AqZ5LjdL8JNmUrZ2oMH8WBG0XVTYA70p3aCe950KMPN-mkroPDuyfKXeQiOW1Qnu";

            var client = new HttpClient();
            var response = client.GetAsync(bingMapsRESTCall).Result;
            var retResp = new HttpResponseMessage();
            var stringResult = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(stringResult);

            return (string)json["resourceSets"][0]["resources"][0]["address"]["countryRegion"];

        }

        public string GetCityFromLatLong(decimal latitude, decimal longitude)
        {
            string bingMapsRESTCall = "http://dev.virtualearth.net/REST/v1/Locations/" + latitude.ToString() + "," + longitude.ToString() + "?&key=" + "AqZ5LjdL8JNmUrZ2oMH8WBG0XVTYA70p3aCe950KMPN-mkroPDuyfKXeQiOW1Qnu";

            var client = new HttpClient();
            var response = client.GetAsync(bingMapsRESTCall).Result;
            var retResp = new HttpResponseMessage();
            var stringResult = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(stringResult);

            return (string)json["resourceSets"][0]["resources"][0]["address"]["locality"];
        }
        private async Task PopulateLocationInfo(string IPAddress)
        {
             await this.GetJSONResponse(IPAddress);
        }
        public DraftRunLocation(string IPAddress)
        {
            this.GetJSONResponse(IPAddress);

            return;
        }

        public async Task<JObject> GetJSONResponse(string IPAddress)
        {

            //FreeGeoIP Service
            string url = "http://freegeoip.net/json/" + IPAddress;

            //Get the location data via the IP address.

            var client = new HttpClient();
            var response = client.GetAsync(url).Result;
            var retResp = new HttpResponseMessage();
            var stringResult = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(stringResult);

            //FreeGeoIP service
            Country = (string)json["country_name"];
            City = (string)json["city"];
            Latitude = (decimal)json["latitude"];
            Longitude = (decimal)json["longitude"];

            return json;

        }

    }
}


text:
import React from 'react';
import renderer from 'react-test-renderer';
import { CardBlock } from '../../cf-component-card/src/index';

test('should render', () => {
  const component = renderer.create(<CardBlock>CardBlock</CardBlock>);
  expect(component.toJSON()).toMatchSnapshot();
});


text:
  Lagrasse est
       un village
       situé dans le département de l'Aude en Languedoc-Roussillon. Elle totalisait 603 habitants en 2008.

La ville propose de multiples  équipements sportifs, elle propose entre autres un terrain de tennis, un terrain de sport et deux boucles de randonnée.

Si vous envisagez de venir habiter à Lagrasse, vous pourrez facilement trouver une maison à vendre.

À Lagrasse, la valorisation moyenne à la vente d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 416 € du m². À la location la valorisation moyenne se situe à 0 € du m² mensuel.

Le nombre de logements, à Lagrasse, se décomposait en 2011 en 65 appartements et 354 maisons soit
 un marché plutôt équilibré.

À coté de Lagrasse sont localisées les villes de
Caunettes-en-Val à 6 km, 55 habitants,
Montlaur située à 6 km, 529 habitants,
Saint-Martin-des-Puits située à 6 km, 18 habitants,
Saint-Laurent-de-la-Cabrerisse localisée à 6 km, 711 habitants,
Tournissan située à 3 km, 252 habitants,
Rieux-en-Val située à 7 km, 71 habitants,
 entre autres. De plus, Lagrasse est située à seulement 25 km de Carcassonne.


text:
package com.amazonaws.services.elasticmapreduce.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum CancelStepsRequestStatus {

    SUBMITTED("SUBMITTED"),
    FAILED("FAILED");

    private String value;

    private CancelStepsRequestStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return CancelStepsRequestStatus corresponding to the value
     */
    public static CancelStepsRequestStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (CancelStepsRequestStatus enumEntry : CancelStepsRequestStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  faicons: {
    time: "fa fa-clock-o",
    date: "fa fa-calendar",
    up: "fa fa-arrow-up",
    down: "fa fa-arrow-down"
  }
});