Cleanup extra-functions
diff --git a/Android.mk b/Android.mk
index caa6b09..600f356 100644
--- a/Android.mk
+++ b/Android.mk
@@ -32,7 +32,6 @@
     extra-functions.c \
     data.cpp \
     makelist.c \
-    firmware.c \
     partition.cpp \
     partitionmanager.cpp \
     mtdutils/mtdutils.c \
diff --git a/data.cpp b/data.cpp
index 896bb1b..505a3a1 100644
--- a/data.cpp
+++ b/data.cpp
@@ -444,6 +444,11 @@
     }
 }
 
+void DataManager::update_tz_environment_variables(void) {
+	setenv("TZ", DataManager_GetStrValue(TW_TIME_ZONE_VAR), 1);
+    tzset();
+}
+
 void DataManager::SetDefaultValues()
 {
     string str, path;
@@ -600,9 +605,15 @@
     str += dev_id;
 	SetValue(TW_BACKUPS_FOLDER_VAR, str, 0);
 
+#ifdef SP1_DISPLAY_NAME
     if (strlen(EXPAND(SP1_DISPLAY_NAME)))    mConstValues.insert(make_pair(TW_SP1_PARTITION_NAME_VAR, EXPAND(SP1_DISPLAY_NAME)));
+#endif
+#ifdef SP2_DISPLAY_NAME
     if (strlen(EXPAND(SP2_DISPLAY_NAME)))    mConstValues.insert(make_pair(TW_SP2_PARTITION_NAME_VAR, EXPAND(SP2_DISPLAY_NAME)));
+#endif
+#ifdef SP3_DISPLAY_NAME
     if (strlen(EXPAND(SP3_DISPLAY_NAME)))    mConstValues.insert(make_pair(TW_SP3_PARTITION_NAME_VAR, EXPAND(SP3_DISPLAY_NAME)));
+#endif
 
     mConstValues.insert(make_pair(TW_REBOOT_SYSTEM, tw_isRebootCommandSupported(rb_system) ? "1" : "0"));
 #ifdef TW_NO_REBOOT_RECOVERY
@@ -860,20 +871,13 @@
 		}
 	}
 
-	// Update storage free space after settings file is loaded
-	if (use_ext == 1)
-		LOGE("TODO: Fix storage size code!\n"); //SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcext.sze - sdcext.used) / 1048576LLU));
-	else if (has_data_media == 1)
-		LOGE("TODO: Fix storage size code!\n"); //SetValue(TW_STORAGE_FREE_SIZE, (int)((dat.sze - dat.used) / 1048576LLU));
-	else
-		LOGE("TODO: Fix storage size code!\n"); //SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcint.sze - sdcint.used) / 1048576LLU));
-
 	if (has_ext) {
 		string ext_path;
 
 		GetValue(TW_EXTERNAL_PATH, ext_path);
 		PartitionManager.Mount_By_Path(ext_path, 0);
 	}
+	update_tz_environment_variables();
 }
 
 string DataManager::GetCurrentStoragePath(void)
diff --git a/data.hpp b/data.hpp
index c3fb52a..ecf4d70 100644
--- a/data.hpp
+++ b/data.hpp
@@ -47,6 +47,7 @@
     static int SetValue(const string varName, float value, int persist = 0);
 
     static void DumpValues();
+	static void update_tz_environment_variables();
 	static void SetDefaultValues();
 	static void ReadSettingsFile(void);
 	
diff --git a/extra-functions.c b/extra-functions.c
index 952c091..b00f2de 100644
--- a/extra-functions.c
+++ b/extra-functions.c
@@ -14,11 +14,8 @@
  * limitations under the License.
  */
 
-#include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <limits.h>
-#include <paths.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -27,372 +24,49 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <ctype.h>
-#include "cutils/misc.h"
-#include "cutils/properties.h"
-#include <dirent.h>
-#include <getopt.h>
 #include <linux/input.h>
-#include <signal.h>
-#include <sys/limits.h>
-#include <termios.h>
-#include <time.h>
-#include <sys/vfs.h>
 
-#include "tw_reboot.h"
 #include "bootloader.h"
 #include "common.h"
 #include "extra-functions.h"
-#include "minuitwrp/minui.h"
-#include "minzip/DirUtil.h"
-#include "minzip/Zip.h"
-#include "recovery_ui.h"
-#include "roots.h"
 #include "data.h"
 #include "variables.h"
-#include "mincrypt/rsa.h"
-#include "verifier.h"
-#include "mincrypt/sha.h"
-
-#ifndef PUBLIC_KEYS_FILE
-#define PUBLIC_KEYS_FILE "/res/keys"
-#endif
-#ifndef ASSUMED_UPDATE_BINARY_NAME
-#define ASSUMED_UPDATE_BINARY_NAME  "META-INF/com/google/android/update-binary"
-#endif
-enum { INSTALL_SUCCESS, INSTALL_ERROR, INSTALL_CORRUPT };
-
-//kang system() from bionic/libc/unistd and rename it __system() so we can be even more hackish :)
-#undef _PATH_BSHELL
-#define _PATH_BSHELL "/sbin/sh"
-
-extern char **environ;
-
-int __system(const char *command) {
-  pid_t pid;
-	sig_t intsave, quitsave;
-	sigset_t mask, omask;
-	int pstat;
-	char *argp[] = {"sh", "-c", NULL, NULL};
-
-	if (!command)		/* just checking... */
-		return(1);
-
-	argp[2] = (char *)command;
-
-	sigemptyset(&mask);
-	sigaddset(&mask, SIGCHLD);
-	sigprocmask(SIG_BLOCK, &mask, &omask);
-	switch (pid = vfork()) {
-	case -1:			/* error */
-		sigprocmask(SIG_SETMASK, &omask, NULL);
-		return(-1);
-	case 0:				/* child */
-		sigprocmask(SIG_SETMASK, &omask, NULL);
-		execve(_PATH_BSHELL, argp, environ);
-    _exit(127);
-  }
-
-	intsave = (sig_t)  bsd_signal(SIGINT, SIG_IGN);
-	quitsave = (sig_t) bsd_signal(SIGQUIT, SIG_IGN);
-	pid = waitpid(pid, (int *)&pstat, 0);
-	sigprocmask(SIG_SETMASK, &omask, NULL);
-	(void)bsd_signal(SIGINT, intsave);
-	(void)bsd_signal(SIGQUIT, quitsave);
-	return (pid == -1 ? -1 : pstat);
-}
-
-static struct pid {
-	struct pid *next;
-	FILE *fp;
-	pid_t pid;
-} *pidlist;
-
-FILE *__popen(const char *program, const char *type) {
-	struct pid * volatile cur;
-	FILE *iop;
-	int pdes[2];
-	pid_t pid;
-
-	if ((*type != 'r' && *type != 'w') || type[1] != '\0') {
-		errno = EINVAL;
-		return (NULL);
-	}
-
-	if ((cur = malloc(sizeof(struct pid))) == NULL)
-		return (NULL);
-
-	if (pipe(pdes) < 0) {
-		free(cur);
-		return (NULL);
-	}
-
-	switch (pid = vfork()) {
-	case -1:			/* Error. */
-		(void)close(pdes[0]);
-		(void)close(pdes[1]);
-		free(cur);
-		return (NULL);
-		/* NOTREACHED */
-	case 0:				/* Child. */
-	    {
-		struct pid *pcur;
-		/*
-		 * because vfork() instead of fork(), must leak FILE *,
-		 * but luckily we are terminally headed for an execl()
-		 */
-		for (pcur = pidlist; pcur; pcur = pcur->next)
-			close(fileno(pcur->fp));
-
-		if (*type == 'r') {
-			int tpdes1 = pdes[1];
-
-			(void) close(pdes[0]);
-			/*
-			 * We must NOT modify pdes, due to the
-			 * semantics of vfork.
-			 */
-			if (tpdes1 != STDOUT_FILENO) {
-				(void)dup2(tpdes1, STDOUT_FILENO);
-				(void)close(tpdes1);
-				tpdes1 = STDOUT_FILENO;
-			}
-		} else {
-			(void)close(pdes[1]);
-			if (pdes[0] != STDIN_FILENO) {
-				(void)dup2(pdes[0], STDIN_FILENO);
-				(void)close(pdes[0]);
-			}
-		}
-		execl(_PATH_BSHELL, "sh", "-c", program, (char *)NULL);
-		_exit(127);
-		/* NOTREACHED */
-	    }
-	}
-
-	/* Parent; assume fdopen can't fail. */
-	if (*type == 'r') {
-		iop = fdopen(pdes[0], type);
-		(void)close(pdes[1]);
-	} else {
-		iop = fdopen(pdes[1], type);
-		(void)close(pdes[0]);
-	}
-
-	/* Link into list of file descriptors. */
-	cur->fp = iop;
-	cur->pid =  pid;
-	cur->next = pidlist;
-	pidlist = cur;
-
-	return (iop);
-}
-
-/*
- * pclose --
- *	Pclose returns -1 if stream is not associated with a `popened' command,
- *	if already `pclosed', or waitpid returns an error.
- */
-int __pclose(FILE *iop) {
-	struct pid *cur, *last;
-	int pstat;
-	pid_t pid;
-
-	/* Find the appropriate file pointer. */
-	for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
-		if (cur->fp == iop)
-			break;
-
-	if (cur == NULL)
-		return (-1);
-
-	(void)fclose(iop);
-
-	do {
-		pid = waitpid(cur->pid, &pstat, 0);
-	} while (pid == -1 && errno == EINTR);
-
-	/* Remove the entry from the linked list. */
-	if (last == NULL)
-		pidlist = cur->next;
-	else
-		last->next = cur->next;
-	free(cur);
-
-	return (pid == -1 ? -1 : pstat);
-}
-
-//partial kangbang from system/vold
-#ifndef CUSTOM_LUN_FILE
-#define CUSTOM_LUN_FILE "/sys/devices/platform/usb_mass_storage/lun%d/file"
-#endif
-
-int usb_storage_enable(void)
-{
-    int fd;
-	char lun_file[255];
-
-	if (DataManager_GetIntValue(TW_HAS_DUAL_STORAGE) == 1 && DataManager_GetIntValue(TW_HAS_DATA_MEDIA) == 0) {
-		Volume *vol = volume_for_path(DataManager_GetSettingsStoragePath());
-		if (!vol)
-		{
-			LOGE("Unable to locate volume information.");
-			return -1;
-		}
-
-		sprintf(lun_file, CUSTOM_LUN_FILE, 0);
-
-		if ((fd = open(lun_file, O_WRONLY)) < 0)
-		{
-			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			return -1;
-		}
-
-		if ((write(fd, vol->device, strlen(vol->device)) < 0) &&
-			(!vol->device2 || (write(fd, vol->device, strlen(vol->device2)) < 0))) {
-			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			close(fd);
-			return -1;
-		}
-		close(fd);
-
-		Volume *vol2 = volume_for_path(DataManager_GetStrValue(TW_EXTERNAL_PATH));
-		if (!vol)
-		{
-			LOGE("Unable to locate volume information.\n");
-			return -1;
-		}
-
-		sprintf(lun_file, CUSTOM_LUN_FILE, 1);
-
-		if ((fd = open(lun_file, O_WRONLY)) < 0)
-		{
-			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			return -1;
-		}
-
-		if ((write(fd, vol2->device, strlen(vol2->device)) < 0) &&
-			(!vol2->device2 || (write(fd, vol2->device, strlen(vol2->device2)) < 0))) {
-			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			close(fd);
-			return -1;
-		}
-		close(fd);
-	} else {
-		if (DataManager_GetIntValue(TW_HAS_DATA_MEDIA) == 0)
-			strcpy(lun_file, DataManager_GetCurrentStoragePath());
-		else
-			strcpy(lun_file, DataManager_GetStrValue(TW_EXTERNAL_PATH));
-
-		Volume *vol = volume_for_path(lun_file);
-		if (!vol)
-		{
-			LOGE("Unable to locate volume information.\n");
-			return -1;
-		}
-
-		sprintf(lun_file, CUSTOM_LUN_FILE, 0);
-
-		if ((fd = open(lun_file, O_WRONLY)) < 0)
-		{
-			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			return -1;
-		}
-
-		if ((write(fd, vol->device, strlen(vol->device)) < 0) &&
-			(!vol->device2 || (write(fd, vol->device, strlen(vol->device2)) < 0))) {
-			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
-			close(fd);
-			return -1;
-		}
-		close(fd);
-	}
-	return 0;
-}
-
-int usb_storage_disable(void)
-{
-    int fd, index;
-	char lun_file[255];
-
-	for (index=0; index<2; index++) {
-		sprintf(lun_file, CUSTOM_LUN_FILE, index);
-
-		if ((fd = open(lun_file, O_WRONLY)) < 0)
-		{
-			if (index == 0)
-				LOGE("Unable to open ums lunfile '%s': (%s)", lun_file, strerror(errno));
-			return -1;
-		}
-
-		char ch = 0;
-		if (write(fd, &ch, 1) < 0)
-		{
-			if (index == 0)
-				LOGE("Unable to write to ums lunfile '%s': (%s)", lun_file, strerror(errno));
-			close(fd);
-			return -1;
-		}
-
-		close(fd);
-	}
-    return 0;
-}
-
-void update_tz_environment_variables() {
-    setenv("TZ", DataManager_GetStrValue(TW_TIME_ZONE_VAR), 1);
-    tzset();
-}
 
 void run_script(const char *str1, const char *str2, const char *str3, const char *str4, const char *str5, const char *str6, const char *str7, int request_confirm)
 {
 	ui_print("%s", str1);
-        //ui_clear_key_queue();
-	ui_print("\nPress Power to confirm,");
-       	ui_print("\nany other key to abort.\n");
-	int confirm;
-	/*if (request_confirm) // this option is used to skip the confirmation when the gui is in use
-		confirm = ui_wait_key();
-	else*/
-		confirm = KEY_POWER;
-	
-		if (confirm == BTN_MOUSE || confirm == KEY_POWER || confirm == SELECT_ITEM) {
-                	ui_print("%s", str2);
-		        pid_t pid = fork();
-                	if (pid == 0) {
-                		char *args[] = { "/sbin/sh", "-c", (char*)str3, "1>&2", NULL };
-                	        execv("/sbin/sh", args);
-                	        fprintf(stderr, str4, strerror(errno));
-                	        _exit(-1);
-                	}
-			int status;
-			while (waitpid(pid, &status, WNOHANG) == 0) {
-				ui_print(".");
-               		        sleep(1);
-			}
-                	ui_print("\n");
-			if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
-                		ui_print("%s", str5);
-                	} else {
-                		ui_print("%s", str6);
-                	}
-		} else {
-	       		ui_print("%s", str7);
-       	        }
-		//if (!ui_text_visible()) return;
+	ui_print("%s", str2);
+	pid_t pid = fork();
+	if (pid == 0) {
+		char *args[] = { "/sbin/sh", "-c", (char*)str3, "1>&2", NULL };
+		execv("/sbin/sh", args);
+		fprintf(stderr, str4, strerror(errno));
+		_exit(-1);
+	}
+	int status;
+	while (waitpid(pid, &status, WNOHANG) == 0) {
+		ui_print(".");
+		sleep(1);
+	}
+	ui_print("\n");
+	if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
+		ui_print("%s", str5);
+	} else {
+		ui_print("%s", str6);
+	}
 }
 
 void check_and_run_script(const char* script_file, const char* display_name)
 {
 	// Check for and run startup script if script exists
-	struct statfs st;
-	if (statfs(script_file, &st) == 0) {
+	struct stat st;
+	if (stat(script_file, &st) == 0) {
 		ui_print("Running %s script...\n", display_name);
 		char command[255];
 		strcpy(command, "chmod 755 ");
 		strcat(command, script_file);
-		__system(command);
-		__system(script_file);
+		system(command);
+		system(script_file);
 		ui_print("\nFinished running %s script.\n", display_name);
 	}
 }
@@ -404,7 +78,7 @@
 	char backup_loc[255], tw_image_dir[255];
 	int copy_size = strlen(DataManager_GetStrValue(TW_BACKUP_NAME));
 	int index, cur_char;
-	struct statfs st;
+	struct stat st;
 
 	// Check size
 	if (copy_size > MAX_BACKUP_NAME_LEN) {
@@ -435,7 +109,7 @@
 	// Check to make sure that a backup with this name doesn't already exist
 	strcpy(backup_loc, DataManager_GetStrValue(TW_BACKUPS_FOLDER_VAR));
 	sprintf(tw_image_dir,"%s/%s/.", backup_loc, backup_name);
-    if (statfs(tw_image_dir, &st) == 0) {
+    if (stat(tw_image_dir, &st) == 0) {
 		if (show_error)
 			LOGE("A backup with this name already exists.\n");
 		return -4;
@@ -514,12 +188,11 @@
     set_bootloader_message(&boot);
 
     // Remove the command file, so recovery won't repeat indefinitely.
-    if (ensure_path_mounted(COMMAND_FILE) != 0 ||
+    if (system("mount /cache") != 0 ||
         (unlink(COMMAND_FILE) && errno != ENOENT)) {
         LOGW("Can't unlink %s\n", COMMAND_FILE);
     }
 
-    ensure_path_unmounted(CACHE_ROOT);
+    system("umount /cache");
     sync();  // For good measure.
 }
-
diff --git a/extra-functions.h b/extra-functions.h
index 664ca33..f355cdc 100644
--- a/extra-functions.h
+++ b/extra-functions.h
@@ -4,14 +4,8 @@
 #include "mincrypt/rsa.h"
 #include "minzip/Zip.h"
 
-int __system(const char *command);
-FILE * __popen(const char *program, const char *type);
-int __pclose(FILE *iop);
-
 static long tmplog_offset = 0;
 
-void update_tz_environment_variables();
-
 void run_script(const char *str1, const char *str2, const char *str3, const char *str4, const char *str5, const char *str6, const char *str7, int request_confirm);
 
 void check_and_run_script(const char* script_file, const char* display_name);
diff --git a/firmware.c b/firmware.c
deleted file mode 100644
index 2e24699..0000000
--- a/firmware.c
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "bootloader.h"
-#include "common.h"
-#include "firmware.h"
-#include "roots.h"
-
-#include <errno.h>
-#include <string.h>
-#include <sys/reboot.h>
-
-static const char *update_type = NULL;
-static const char *update_data = NULL;
-static int update_length = 0;
-
-int remember_firmware_update(const char *type, const char *data, int length) {
-    if (update_type != NULL || update_data != NULL) {
-        LOGE("Multiple firmware images\n");
-        return -1;
-    }
-
-    update_type = type;
-    update_data = data;
-    update_length = length;
-    return 0;
-}
-
-// Return true if there is a firmware update pending.
-int firmware_update_pending() {
-  return update_data != NULL && update_length > 0;
-}
-
-/* Bootloader / Recovery Flow
- *
- * On every boot, the bootloader will read the bootloader_message
- * from flash and check the command field.  The bootloader should
- * deal with the command field not having a 0 terminator correctly
- * (so as to not crash if the block is invalid or corrupt).
- *
- * The bootloader will have to publish the partition that contains
- * the bootloader_message to the linux kernel so it can update it.
- *
- * if command == "boot-recovery" -> boot recovery.img
- * else if command == "update-radio" -> update radio image (below)
- * else if command == "update-hboot" -> update hboot image (below)
- * else -> boot boot.img (normal boot)
- *
- * Radio/Hboot Update Flow
- * 1. the bootloader will attempt to load and validate the header
- * 2. if the header is invalid, status="invalid-update", goto #8
- * 3. display the busy image on-screen
- * 4. if the update image is invalid, status="invalid-radio-image", goto #8
- * 5. attempt to update the firmware (depending on the command)
- * 6. if successful, status="okay", goto #8
- * 7. if failed, and the old image can still boot, status="failed-update"
- * 8. write the bootloader_message, leaving the recovery field
- *    unchanged, updating status, and setting command to
- *    "boot-recovery"
- * 9. reboot
- *
- * The bootloader will not modify or erase the cache partition.
- * It is recovery's responsibility to clean up the mess afterwards.
- */
-
-int maybe_install_firmware_update(const char *send_intent) {
-    if (update_data == NULL || update_length == 0) return 0;
-
-    /* We destroy the cache partition to pass the update image to the
-     * bootloader, so all we can really do afterwards is wipe cache and reboot.
-     * Set up this instruction now, in case we're interrupted while writing.
-     */
-
-    struct bootloader_message boot;
-    memset(&boot, 0, sizeof(boot));
-    strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
-    strlcpy(boot.recovery, "recovery\n--wipe_cache\n", sizeof(boot.command));
-    if (send_intent != NULL) {
-        strlcat(boot.recovery, "--send_intent=", sizeof(boot.recovery));
-        strlcat(boot.recovery, send_intent, sizeof(boot.recovery));
-        strlcat(boot.recovery, "\n", sizeof(boot.recovery));
-    }
-    if (set_bootloader_message(&boot)) return -1;
-
-    int width = 0, height = 0, bpp = 0;
-    char *busy_image = NULL;/*ui_copy_image(
-        BACKGROUND_ICON_FIRMWARE_INSTALLING, &width, &height, &bpp);*/
-    char *fail_image = NULL;/*ui_copy_image(
-        BACKGROUND_ICON_FIRMWARE_ERROR, &width, &height, &bpp);*/
-
-    ui_print("Writing %s image...\n", update_type);
-    if (write_update_for_bootloader(
-            update_data, update_length,
-            width, height, bpp, busy_image, fail_image)) {
-        LOGE("Can't write %s image\n(%s)\n", update_type, strerror(errno));
-        format_volume("/cache");  // Attempt to clean cache up, at least.
-        return -1;
-    }
-
-    free(busy_image);
-    free(fail_image);
-
-    /* The update image is fully written, so now we can instruct the bootloader
-     * to install it.  (After doing so, it will come back here, and we will
-     * wipe the cache and reboot into the system.)
-     */
-    snprintf(boot.command, sizeof(boot.command), "update-%s", update_type);
-    if (set_bootloader_message(&boot)) {
-        format_volume("/cache");
-        return -1;
-    }
-
-    reboot(RB_AUTOBOOT);
-
-    // Can't reboot?  WTF?
-    LOGE("Can't reboot\n");
-    return -1;
-}
diff --git a/firmware.h b/firmware.h
deleted file mode 100644
index aeb8f97..0000000
--- a/firmware.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _RECOVERY_FIRMWARE_H
-#define _RECOVERY_FIRMWARE_H
-
-/* Save a radio or bootloader update image for later installation.
- * The type should be one of "hboot" or "radio".
- * Takes ownership of type and data.  Returns nonzero on error.
- */
-int remember_firmware_update(const char *type, const char *data, int length);
-
-/* Returns true if a firmware update has been saved. */
-int firmware_update_pending();
-
-/* If an update was saved, reboot into the bootloader now to install it.
- * Returns 0 if no radio image was defined, nonzero on error,
- * doesn't return at all on success...
- */
-int maybe_install_firmware_update(const char *send_intent);
-
-#endif
diff --git a/gui/action.cpp b/gui/action.cpp
index 3d6c9eb..5118b4c 100644
--- a/gui/action.cpp
+++ b/gui/action.cpp
@@ -37,23 +37,9 @@
 #include "../minadbd/adb.h"
 
 int TWinstall_zip(const char* path, int* wipe_cache);
-void wipe_dalvik_cache(void);
 int check_backup_name(int show_error);
-void wipe_battery_stats(void);
-void wipe_rotate_data(void);
-int usb_storage_enable(void);
-int usb_storage_disable(void);
-int __system(const char *command);
-FILE * __popen(const char *program, const char *type);
-int __pclose(FILE *iop);
 void run_script(const char *str1, const char *str2, const char *str3, const char *str4, const char *str5, const char *str6, const char *str7, int request_confirm);
-void update_tz_environment_variables();
-void install_htc_dumlock(void);
-void htc_dumlock_restore_original_boot(void);
-void htc_dumlock_reflash_recovery_to_boot(void);
-int check_for_script_file(void);
 int gui_console_only();
-int run_script_file(void);
 int gui_start();
 };
 
@@ -230,7 +216,7 @@
 			DataManager::SetValue("tw_operation", "Configuring TWRP");
 			DataManager::SetValue("tw_partition", "");
 			ui_print("Configuring TWRP...\n");
-			if (__system("/sbin/installTwrp reinstall") < 0)
+			if (system("/sbin/installTwrp reinstall") < 0)
 			{
 				ui_print("Unable to configure TWRP with this kernel.\n");
 			}
@@ -419,7 +405,7 @@
         {
             DataManager::SetValue(TW_ACTION_BUSY, 1);
 			if (!simulate)
-				usb_storage_enable();
+				PartitionManager.usb_storage_enable();
 			else
 				ui_print("Simulating actions...\n");
         }
@@ -442,7 +428,7 @@
         if (arg == "usb")
         {
             if (!simulate)
-				usb_storage_disable();
+				PartitionManager.usb_storage_disable();
 			else
 				ui_print("Simulating actions...\n");
 			DataManager::SetValue(TW_ACTION_BUSY, 0);
@@ -483,7 +469,7 @@
 
 			PartitionManager.Mount_Current_Storage(true);
 			sprintf(command, "cp /tmp/recovery.log %s", DataManager::GetCurrentStoragePath().c_str());
-			__system(command);
+			system(command);
 			sync();
 			ui_print("Copied recovery log to %s.\n", DataManager::GetCurrentStoragePath().c_str());
 		} else
@@ -542,7 +528,7 @@
 			NewTimeZone += DSTZone;
 		
 		DataManager::SetValue(TW_TIME_ZONE_VAR, NewTimeZone);
-		update_tz_environment_variables();
+		DataManager::update_tz_environment_variables();
 		return 0;
 	}
 
@@ -661,7 +647,7 @@
 				if (simulate) {
 					simulate_progress_bar();
 				} else {
-					__system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
+					system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
 					ui_print("TWRP injection complete.\n");
 				}
 			}
@@ -794,7 +780,7 @@
 			} else {
 				char cmd[512];
 				sprintf(cmd, "dd %s", arg.c_str());
-				__system(cmd);
+				system(cmd);
 			}
             operation_end(0, simulate);
             return 0;
@@ -817,7 +803,7 @@
 					Volume *vol = volume_for_path("/sdcard");
 					strcpy(sddevice, vol->device);
 					// Just need block not whole partition
-					sddevice[strlen("/dev/block/mmcblkX")] = NULL;
+					sddevice[strlen("/dev/block/mmcblkX")] = '\0';
 
 					char es[64];
 					std::string ext_format, sd_path;
@@ -863,7 +849,7 @@
 						//sprintf(command, "mke2fs -t ext4 -m 0 %s", sde.blk);
 						ui_print("Formatting sd-ext as ext4...\n");
 						LOGI("Formatting sd-ext after partitioning, command: '%s'\n", command);
-						__system(command);
+						system(command);
 						ui_print("DONE\n");
 					}
 
@@ -915,7 +901,7 @@
 			if (simulate) {
 				simulate_progress_bar();
 			} else {
-				op_status = __system(arg.c_str());
+				op_status = system(arg.c_str());
 				if (op_status != 0)
 					op_status = 1;
 			}
@@ -975,7 +961,7 @@
 			if (simulate) {
 				simulate_progress_bar();
 			} else {
-				__system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
+				system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
 				ui_print("TWRP injection complete.\n");
 			}
 
@@ -1072,7 +1058,7 @@
 			} else {
 				int wipe_cache = 0;
 				ui_print("Starting ADB sideload feature...\n");
-				__system("touch /tmp/update.zip");
+				system("touch /tmp/update.zip");
 				ret = apply_from_adb(ui, &wipe_cache, "/tmp/last_install");
 				LOGI("Result was: %i\n", ret);
 				if (ret != 0)
@@ -1118,7 +1104,7 @@
 	char line[512];
 
 	DataManager::GetValue("tw_terminal_command_thread", command);
-	fp = __popen(command.c_str(), "r");
+	fp = popen(command.c_str(), "r");
 	if (fp == NULL) {
 		LOGE("Error opening command to run.\n");
 	} else {
diff --git a/gui_stub.c b/gui_stub.c
deleted file mode 100644
index 2a3f979..0000000
--- a/gui_stub.c
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <linux/input.h>
-#include <pthread.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/time.h>
-#include <time.h>
-#include <unistd.h>
-
-int gui_init()
-{
-    return -1;
-}
-
-int gui_loadResources()
-{
-    return -1;
-}
-
-int gui_start()
-{
-    return -1;
-}
-
-void gui_print(const char *fmt, ...)
-{
-    return;
-}
-
-void gui_print_overwrite(const char *fmt, ...)
-{
-    return;
-}
-
-void gui_notifyVarChange(const char *name, const char* value)
-{
-    return;
-}
-
-void gui_console_only(void)
-{
-	return;
-}
\ No newline at end of file
diff --git a/makelist.c b/makelist.c
index ed7cce9..1a2f0a6 100644
--- a/makelist.c
+++ b/makelist.c
@@ -26,7 +26,6 @@
 #include <sys/stat.h>
 #include <dirent.h>
 
-#include "extra-functions.h"
 #include "common.h"
 #include "data.h"
 #include "variables.h"
@@ -40,11 +39,11 @@
     sprintf(cmd, "du -sk %s | awk '{ print $1 }'", path);
 
     FILE *fp;
-    fp = __popen(cmd, "r");
+    fp = popen(cmd, "r");
     
     char str[512];
     fgets(str, sizeof(str), fp);
-    __pclose(fp);
+    pclose(fp);
 
     unsigned long long size = atol(str);
     size *= 1024ULL;
@@ -146,8 +145,8 @@
 {
 	makelist_file_count = 0;
 	makelist_current_size = 0;
-	__system("cd /tmp && rm -rf list");
-	__system("cd /tmp && mkdir list");
+	system("cd /tmp && rm -rf list");
+	system("cd /tmp && mkdir list");
 	if (generate_file_lists(path) < 0) {
 		LOGE("Error generating file list\n");
 		return -1;
diff --git a/partition.cpp b/partition.cpp
index 27f855e..ad3198b 100644
--- a/partition.cpp
+++ b/partition.cpp
@@ -206,7 +206,6 @@
 			Display_Name = "Cache";
 			Wipe_Available_in_GUI = true;
 			Wipe_During_Factory_Reset = true;
-			Update_Size(Display_Error);
 			MTD_Name = "cache";
 		} else if (Mount_Point == "/datadata") {
 			Wipe_During_Factory_Reset = true;
@@ -218,8 +217,29 @@
 			Wipe_During_Factory_Reset = true;
 			Display_Name = "SD-Ext";
 			Wipe_Available_in_GUI = true;
-		} else
-			Update_Size(Display_Error);
+		}
+#ifdef TW_EXTERNAL_STORAGE_PATH
+		if (Mount_Point == EXPAND(TW_EXTERNAL_STORAGE_PATH)) {
+			Is_Storage = true;
+			Storage_Path = EXPAND(TW_EXTERNAL_STORAGE_PATH);
+		}
+#else
+		if (Mount_Point == "/sdcard") {
+			Is_Storage = true;
+			Storage_Path = "/sdcard";
+		}
+#endif
+#ifdef TW_INTERNAL_STORAGE_PATH
+		if (Mount_Point == EXPAND(TW_INTERNAL_STORAGE_PATH)) {
+			Is_Storage = true;
+			Storage_Path = EXPAND(TW_INTERNAL_STORAGE_PATH);
+		}
+#else
+		if (Mount_Point == "/emmc") {
+			Is_Storage = true;
+			Storage_Path = "/emmc";
+		}
+#endif
 	} else if (Is_Image(Fstab_File_System)) {
 		Find_Actual_Block_Device();
 		Setup_Image(Display_Error);
@@ -774,10 +794,17 @@
 		return; // Running blkid on some mtd devices causes a massive crash
 
 	Find_Actual_Block_Device();
-	blkCommand = "blkid " + Actual_Block_Device + " > /tmp/blkidoutput.txt";
+	if (!Is_Present)
+		return;
 
+	if (TWFunc::Path_Exists("/tmp/blkidoutput.txt"))
+		system("rm /tmp/blkidoutput.txt");
+
+	blkCommand = "blkid " + Actual_Block_Device + " > /tmp/blkidoutput.txt";
 	system(blkCommand.c_str());
 	fp = fopen("/tmp/blkidoutput.txt", "rt");
+	if (fp == NULL)
+		return;
 	while (fgets(blkOutput, sizeof(blkOutput), fp) != NULL)
 	{
 		blk = blkOutput;
diff --git a/partitionmanager.cpp b/partitionmanager.cpp
index 855b311..b2bbf8e 100644
--- a/partitionmanager.cpp
+++ b/partitionmanager.cpp
@@ -29,6 +29,8 @@
 #include <vector>
 #include <dirent.h>
 #include <time.h>
+#include <errno.h>
+#include <fcntl.h>
 
 #include "variables.h"
 #include "common.h"
@@ -36,11 +38,6 @@
 #include "data.hpp"
 #include "twrp-functions.hpp"
 
-extern "C" {
-	#include "extra-functions.h"
-	int __system(const char *command);
-}
-
 #ifdef TW_INCLUDE_CRYPTO
 	#ifdef TW_INCLUDE_JB_CRYPTO
 		#include "crypto/jb/cryptfs.h"
@@ -111,6 +108,81 @@
 	return true;
 }
 
+void TWPartitionManager::Output_Partition_Logging(void) {
+	std::vector<TWPartition*>::iterator iter;
+
+	printf("\n\nPartition Logs:\n");
+	for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
+		Output_Partition((*iter));
+}
+
+void TWPartitionManager::Output_Partition(TWPartition* Part) {
+	unsigned long long mb = 1048576;
+
+	if (Part->Can_Be_Mounted) {
+		printf("%s | %s | Size: %iMB Used: %iMB Free: %iMB Backup Size: %iMB\n   Flags: ", Part->Mount_Point.c_str(), Part->Actual_Block_Device.c_str(), (int)(Part->Size / mb), (int)(Part->Used / mb), (int)(Part->Free / mb), (int)(Part->Backup_Size / mb));
+		if (Part->Can_Be_Wiped)
+			printf("Can_Be_Wiped ");
+		if (Part->Wipe_During_Factory_Reset)
+			printf("Wipe_During_Factory_Reset ");
+		if (Part->Wipe_Available_in_GUI)
+			printf("Wipe_Available_in_GUI ");
+		if (Part->Is_SubPartition)
+			printf("Is_SubPartition ");
+		if (Part->Has_SubPartition)
+			printf("Has_SubPartition ");
+		if (Part->Removable)
+			printf("Removable ");
+		if (Part->Is_Present)
+			printf("IsPresent ");
+		if (Part->Can_Be_Encrypted)
+			printf("Can_Be_Encrypted ");
+		if (Part->Is_Encrypted)
+			printf("Is_Encrypted ");
+		if (Part->Is_Decrypted)
+			printf("Is_Decrypted ");
+		if (Part->Has_Data_Media)
+			printf("Has_Data_Media ");
+		if (Part->Is_Storage)
+			printf("Is_Storage ");
+		printf("\n");
+		if (!Part->SubPartition_Of.empty())
+			printf("   SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
+		if (!Part->Symlink_Path.empty())
+			printf("   Symlink_Path: %s\n", Part->Symlink_Path.c_str());
+		if (!Part->Symlink_Mount_Point.empty())
+			printf("   Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
+		if (!Part->Primary_Block_Device.empty())
+			printf("   Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
+		if (!Part->Alternate_Block_Device.empty())
+			printf("   Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
+		if (!Part->Decrypted_Block_Device.empty())
+			printf("   Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
+		if (Part->Length != 0)
+			printf("   Length: %i\n", Part->Length);
+		if (!Part->Display_Name.empty())
+			printf("   Display_Name: %s\n", Part->Display_Name.c_str());
+		if (!Part->Backup_Name.empty())
+			printf("   Backup_Name: %s\n", Part->Backup_Name.c_str());
+		if (!Part->Backup_FileName.empty())
+			printf("   Backup_FileName: %s\n", Part->Backup_FileName.c_str());
+		if (!Part->MTD_Name.empty())
+			printf("   MTD_Name: %s\n", Part->MTD_Name.c_str());
+		if (!Part->Storage_Path.empty())
+			printf("   Storage_Path: %s\n", Part->Storage_Path.c_str());
+		if (!Part->Current_File_System.empty())
+			printf("   Current_File_System: %s\n", Part->Current_File_System.c_str());
+		if (!Part->Fstab_File_System.empty())
+			printf("   Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
+		if (Part->Format_Block_Size != 0)
+			printf("   Format_Block_Size: %i\n", Part->Format_Block_Size);
+	} else {
+		printf("%s | %s | Size: %iMB\n", Part->Mount_Point.c_str(), Part->Actual_Block_Device.c_str(), (int)(Part->Size / mb));
+	}
+	string back_meth = Part->Backup_Method_By_Name();
+	printf("   Backup_Method: %s\n\n", back_meth.c_str());
+}
+
 int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
 	std::vector<TWPartition*>::iterator iter;
 	int ret = false;
@@ -382,6 +454,18 @@
 	time(&start);
 
 	if (Part->Backup(Backup_Folder)) {
+		if (Part->Has_SubPartition) {
+			std::vector<TWPartition*>::iterator subpart;
+
+			for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
+				if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == Part->Mount_Point) {
+					if (!(*subpart)->Backup(Backup_Folder))
+						return false;
+					if (!Make_MD5(generate_md5, Backup_Folder, (*subpart)->Backup_FileName))
+						return false;
+				}
+			}
+		}
 		time(&stop);
 		if (Part->Backup_Method == 1) {
 			*file_bytes_remaining -= Part->Backup_Size;
@@ -399,7 +483,7 @@
 int TWPartitionManager::Run_Backup(void) {
 	int check, do_md5, partition_count = 0;
 	string Backup_Folder, Backup_Name, Full_Backup_Path;
-	unsigned long long total_bytes = 0, file_bytes = 0, img_bytes = 0, free_space = 0, img_bytes_remaining, file_bytes_remaining;
+	unsigned long long total_bytes = 0, file_bytes = 0, img_bytes = 0, free_space = 0, img_bytes_remaining, file_bytes_remaining, subpart_size;
 	unsigned long img_time = 0, file_time = 0;
 	TWPartition* backup_sys = NULL;
 	TWPartition* backup_data = NULL;
@@ -412,6 +496,7 @@
 	TWPartition* backup_sp2 = NULL;
 	TWPartition* backup_sp3 = NULL;
 	TWPartition* storage = NULL;
+	std::vector<TWPartition*>::iterator subpart;
 	struct tm *t;
 	time_t start, stop, seconds, total_start, total_stop;
 	seconds = time(0);
@@ -466,10 +551,17 @@
 		backup_data = Find_Partition_By_Path("/data");
 		if (backup_data != NULL) {
 			partition_count++;
+			subpart_size = 0;
+			if (backup_data->Has_SubPartition) {
+				for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
+					if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == backup_data->Mount_Point)
+						subpart_size += (*subpart)->Backup_Size;
+				}
+			}
 			if (backup_data->Backup_Method == 1)
-				file_bytes += backup_data->Backup_Size;
+				file_bytes += backup_data->Backup_Size + subpart_size;
 			else
-				img_bytes += backup_data->Backup_Size;
+				img_bytes += backup_data->Backup_Size + subpart_size;
 		} else {
 			LOGE("Unable to locate data partition.\n");
 			return false;
@@ -665,6 +757,16 @@
 	time(&Start);
 	if (!Part->Restore(Restore_Name))
 		return false;
+	if (Part->Has_SubPartition) {
+		std::vector<TWPartition*>::iterator subpart;
+
+		for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
+			if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == Part->Mount_Point) {
+				if (!(*subpart)->Restore(Restore_Name))
+					return false;
+			}
+		}
+	}
 	time(&Stop);
 	ui_print("[%s done (%d seconds)]\n\n", Part->Display_Name.c_str(), (int)difftime(Stop, Start));
 	return true;
@@ -791,6 +893,16 @@
 			return false;
 		if (restore_data != NULL && !restore_data->Check_MD5(Restore_Name))
 			return false;
+		if (restore_data != NULL && restore_data->Has_SubPartition) {
+			std::vector<TWPartition*>::iterator subpart;
+
+			for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
+				if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == restore_data->Mount_Point) {
+					if (!(*subpart)->Check_MD5(Restore_Name))
+						return false;
+				}
+			}
+		}
 		if (restore_cache != NULL && !restore_cache->Check_MD5(Restore_Name))
 			return false;
 		if (restore_boot != NULL && !restore_boot->Check_MD5(Restore_Name))
@@ -1043,18 +1155,18 @@
 		return false;
 
 	ui_print("\nWiping Dalvik Cache Directories...\n");
-	__system("rm -rf /data/dalvik-cache");
+	system("rm -rf /data/dalvik-cache");
 	ui_print("Cleaned: /data/dalvik-cache...\n");
-	__system("rm -rf /cache/dalvik-cache");
+	system("rm -rf /cache/dalvik-cache");
 	ui_print("Cleaned: /cache/dalvik-cache...\n");
-	__system("rm -rf /cache/dc");
+	system("rm -rf /cache/dc");
 	ui_print("Cleaned: /cache/dc\n");
 
 	TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
 	if (sdext != NULL) {
 		if (sdext->Is_Present && sdext->Mount(false)) {
 			if (stat("/sd-ext/dalvik-cache", &st) == 0) {
-                __system("rm -rf /sd-ext/dalvik-cache");
+                system("rm -rf /sd-ext/dalvik-cache");
         	    ui_print("Cleaned: /sd-ext/dalvik-cache...\n");
     	    }
         }
@@ -1067,8 +1179,9 @@
 	if (!Mount_By_Path("/data", true))
 		return false;
 
-	__system("rm -r /data/misc/akmd*");
-	__system("rm -r /data/misc/rild*");
+	system("rm -r /data/misc/akmd*");
+	system("rm -r /data/misc/rild*");
+	system("rm -r /data/misc/rild*");
 	ui_print("Rotation data wiped.\n");
 	return true;
 }
@@ -1115,8 +1228,8 @@
 			return false;
 
 		ui_print("Wiping internal storage -- /data/media...\n");
-		__system("rm -rf /data/media");
-		__system("cd /data && mkdir media && chmod 775 media");
+		system("rm -rf /data/media");
+		system("cd /data && mkdir media && chmod 775 media");
 		if (dat->Has_Data_Media) {
 			dat->Recreate_Media_Folder();
 		}
@@ -1157,16 +1270,55 @@
 					DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
 				} else
 					DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
+			} else if ((*iter)->Mount_Point == "/and-sec") {
+				int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
+				DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
+				if ((*iter)->Backup_Size == 0) {
+					DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
+					DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
+				} else
+					DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
 			}
 		}
 	}
 	DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
 	string current_storage_path = DataManager::GetCurrentStoragePath();
 	TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
-	if (FreeStorage)
-		DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
-	else
+	if (FreeStorage != NULL) {
+		// Attempt to mount storage
+		if (!FreeStorage->Mount(false)) {
+			// We couldn't mount storage... check to see if we have dual storage
+			int has_dual_storage;
+			DataManager::GetValue(TW_HAS_DUAL_STORAGE, has_dual_storage);
+			if (has_dual_storage == 1) {
+				// We have dual storage, see if we're using the internal storage that should always be present
+				if (current_storage_path == DataManager::GetSettingsStoragePath()) {
+					// Not able to use internal, so error!
+					LOGE("Unable to mount internal storage.\n");
+					DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
+				} else {
+					// We were using external, flip to internal
+					DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 0);
+					current_storage_path = DataManager::GetCurrentStoragePath();
+					FreeStorage = Find_Partition_By_Path(current_storage_path);
+					if (FreeStorage != NULL) {
+						DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
+					} else {
+						LOGE("Unable to locate internal storage partition.\n");
+						DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
+					}
+				}
+			} else {
+				// No dual storage and unable to mount storage, error!
+				LOGE("Unable to mount storage.\n");
+				DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
+			}
+		} else {
+			DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
+		}
+	} else {
 		LOGI("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
+	}
 	if (!Write_Fstab())
 		LOGE("Error creating fstab\n");
 	return;
@@ -1227,7 +1379,122 @@
 		return false;
 
 	ui_print("Fixing Permissions\nThis may take a few minutes.\n");
-	__system("./sbin/fix_permissions.sh");
+	system("./sbin/fix_permissions.sh");
 	ui_print("Done.\n\n");
 	return true;
 }
+
+//partial kangbang from system/vold
+#ifndef CUSTOM_LUN_FILE
+#define CUSTOM_LUN_FILE "/sys/devices/platform/usb_mass_storage/lun%d/file"
+#endif
+
+int TWPartitionManager::usb_storage_enable(void) {
+	int fd, has_dual, has_data_media;
+	char lun_file[255];
+	TWPartition* Part;
+	string ext_path;
+
+	DataManager::GetValue(TW_HAS_DUAL_STORAGE, has_dual);
+	DataManager::GetValue(TW_HAS_DATA_MEDIA, has_data_media);
+	if (has_dual == 1 && has_data_media == 0) {
+		Part = Find_Partition_By_Path(DataManager::GetSettingsStoragePath());
+		if (Part == NULL) {
+			LOGE("Unable to locate volume information.");
+			return false;
+		}
+		if (!Part->UnMount(true))
+			return false;
+
+		sprintf(lun_file, CUSTOM_LUN_FILE, 0);
+		if ((fd = open(lun_file, O_WRONLY)) < 0) {
+			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			return false;
+		}
+
+		if (write(fd, Part->Actual_Block_Device.c_str(), Part->Actual_Block_Device.size()) < 0) {
+			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			close(fd);
+			return false;
+		}
+		close(fd);
+
+		DataManager::GetValue(TW_EXTERNAL_PATH, ext_path);
+		Part = Find_Partition_By_Path(ext_path);
+		if (Part == NULL) {
+			LOGE("Unable to locate volume information.\n");
+			return false;
+		}
+		if (!Part->UnMount(true))
+			return false;
+
+		sprintf(lun_file, CUSTOM_LUN_FILE, 1);
+		if ((fd = open(lun_file, O_WRONLY)) < 0) {
+			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			return false;
+		}
+
+		if (write(fd, Part->Actual_Block_Device.c_str(), Part->Actual_Block_Device.size()) < 0) {
+			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			close(fd);
+			return false;
+		}
+		close(fd);
+	} else {
+		if (has_data_media == 0)
+			ext_path = DataManager::GetCurrentStoragePath();
+		else
+			DataManager::GetValue(TW_EXTERNAL_PATH, ext_path);
+
+		Part = Find_Partition_By_Path(ext_path);
+		if (Part == NULL) {
+			LOGE("Unable to locate volume information.\n");
+			return false;
+		}
+		if (!Part->UnMount(true))
+			return false;
+
+		sprintf(lun_file, CUSTOM_LUN_FILE, 0);
+
+		if ((fd = open(lun_file, O_WRONLY)) < 0) {
+			LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			return false;
+		}
+
+		if (write(fd, Part->Actual_Block_Device.c_str(), Part->Actual_Block_Device.size()) < 0) {
+			LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
+			close(fd);
+			return false;
+		}
+		close(fd);
+	}
+	return true;
+}
+
+int TWPartitionManager::usb_storage_disable(void) {
+	int fd, index;
+	char lun_file[255];
+
+	for (index=0; index<2; index++) {
+		sprintf(lun_file, CUSTOM_LUN_FILE, index);
+
+		if ((fd = open(lun_file, O_WRONLY)) < 0) {
+			if (index == 0)
+				LOGE("Unable to open ums lunfile '%s': (%s)", lun_file, strerror(errno));
+			return false;
+		}
+
+		char ch = 0;
+		if (write(fd, &ch, 1) < 0) {
+			if (index == 0)
+				LOGE("Unable to write to ums lunfile '%s': (%s)", lun_file, strerror(errno));
+			close(fd);
+			return false;
+		}
+
+		close(fd);
+	}
+	Mount_By_Path(DataManager::GetSettingsStoragePath(), true);
+	Mount_By_Path(DataManager::GetCurrentStoragePath(), true);
+	return true;
+}
\ No newline at end of file
diff --git a/partitions.hpp b/partitions.hpp
index ada2f33..32c4f45 100644
--- a/partitions.hpp
+++ b/partitions.hpp
@@ -140,6 +140,7 @@
 public:
 	virtual int Process_Fstab(string Fstab_Filename, bool Display_Error);     // Parses the fstab and populates the partitions
 	virtual int Write_Fstab();                                                // Creates /etc/fstab file that's used by the command line for mount commands
+	virtual void Output_Partition_Logging();                                  // Outputs partition information to the log
 	virtual int Mount_By_Path(string Path, bool Display_Error);               // Mounts partition based on path (e.g. /system)
 	virtual int Mount_By_Block(string Block, bool Display_Error);             // Mounts partition based on block device (e.g. /dev/block/mmcblk1p1)
 	virtual int Mount_By_Name(string Name, bool Display_Error);               // Mounts partition based on display name (e.g. System)
@@ -170,11 +171,14 @@
 	virtual void Update_System_Details();                                     // Updates fstab, file systems, sizes, etc.
 	virtual int Decrypt_Device(string Password);                              // Attempt to decrypt any encrypted partitions
 	virtual int Fix_Permissions();                                            // Fixes permissions in /system and /data
+	virtual int usb_storage_enable(void);                                     // Enable USB storage mode
+	virtual int usb_storage_disable(void);                                    // Disable USB storage mode
 
 private:
 	bool Make_MD5(bool generate_md5, string Backup_Folder, string Backup_Filename); // Generates an MD5 after a backup is made
 	bool Backup_Partition(TWPartition* Part, string Backup_Folder, bool generate_md5, unsigned long long* img_bytes_remaining, unsigned long long* file_bytes_remaining, unsigned long *img_time, unsigned long *file_time);
 	bool Restore_Partition(TWPartition* Part, string Restore_Name);
+	void Output_Partition(TWPartition* Part);
 
 private:
 	std::vector<TWPartition*> Partitions;                                     // Vector list of all partitions
diff --git a/recovery.cpp b/recovery.cpp
index 743920c..b333db9 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -808,14 +808,15 @@
 	printf("Starting the UI...");
 	gui_init();
 	printf("=> Installing busybox into /sbin\n");
-	__system("/sbin/bbinstall.sh"); // Let's install busybox
+	system("/sbin/bbinstall.sh"); // Let's install busybox
 	printf("=> Linking mtab\n");
-	__system("ln -s /proc/mounts /etc/mtab"); // And link mtab for mke2fs
+	system("ln -s /proc/mounts /etc/mtab"); // And link mtab for mke2fs
 	printf("=> Processing recovery.fstab\n");
 	if (!PartitionManager.Process_Fstab("/etc/recovery.fstab", 1)) {
 		LOGE("Failing out of recovery due to problem with recovery.fstab.\n");
 		//return -1;
 	}
+	PartitionManager.Output_Partition_Logging();
 	// Load up all the resources
 	gui_loadResources();
 
@@ -890,7 +891,7 @@
 #ifdef TW_INCLUDE_INJECTTWRP
 	// Back up TWRP Ramdisk if needed:
 	LOGI("Backing up TWRP ramdisk...\n");
-	__system("injecttwrp --backup /tmp/backup_recovery_ramdisk.img");
+	system("injecttwrp --backup /tmp/backup_recovery_ramdisk.img");
 	LOGI("Backup of TWRP ramdisk done.\n");
 #endif
 
@@ -923,9 +924,6 @@
     //if (status != INSTALL_SUCCESS) ui->SetBackground(RecoveryUI::ERROR);
     if (status != INSTALL_SUCCESS /*|| ui->IsTextVisible()*/) {
 		DataManager_ReadSettingsFile();
-
-		// Update some of the main data
-		update_tz_environment_variables();
         gui_start();
 		//prompt_and_wait(device);
     }
diff --git a/twrp-functions.cpp b/twrp-functions.cpp
index b393f2b..90c6016 100644
--- a/twrp-functions.cpp
+++ b/twrp-functions.cpp
@@ -12,10 +12,6 @@
 #include "twrp-functions.hpp"
 #include "partitions.hpp"
 #include "common.h"
-extern "C" {
-	#include "extra-functions.h"
-	int __system(const char *command);
-}
 
 /*  Checks md5 for a path
     Return values:
@@ -34,7 +30,7 @@
 		chdir(DirPath.c_str());
 		MD5_File = Get_Filename(MD5_File);
 		Command = "/sbin/busybox md5sum -c '" + MD5_File + "' > /tmp/md5output";
-		__system(Command.c_str());
+		system(Command.c_str());
 		FILE * cs = fopen("/tmp/md5output", "r");
 		if (cs == NULL) {
 			LOGE("Unable to open md5 output file.\n");
@@ -108,7 +104,6 @@
 }
 
 void TWFunc::install_htc_dumlock(void) {
-	struct statfs fs1, fs2;
 	int need_libs = 0;
 
 	if (!PartitionManager.Mount_By_Path("/system", true))
@@ -118,30 +113,30 @@
 		return;
 
 	ui_print("Installing HTC Dumlock to system...\n");
-	__system("cp /res/htcd/htcdumlocksys /system/bin/htcdumlock && chmod 755 /system/bin/htcdumlock");
-	if (statfs("/system/bin/flash_image", &fs1) != 0) {
+	system("cp /res/htcd/htcdumlocksys /system/bin/htcdumlock && chmod 755 /system/bin/htcdumlock");
+	if (!Path_Exists("/system/bin/flash_image")) {
 		ui_print("Installing flash_image...\n");
-		__system("cp /res/htcd/flash_imagesys /system/bin/flash_image && chmod 755 /system/bin/flash_image");
+		system("cp /res/htcd/flash_imagesys /system/bin/flash_image && chmod 755 /system/bin/flash_image");
 		need_libs = 1;
 	} else
 		ui_print("flash_image is already installed, skipping...\n");
-	if (statfs("/system/bin/dump_image", &fs2) != 0) {
+	if (!Path_Exists("/system/bin/dump_image")) {
 		ui_print("Installing dump_image...\n");
-		__system("cp /res/htcd/dump_imagesys /system/bin/dump_image && chmod 755 /system/bin/dump_image");
+		system("cp /res/htcd/dump_imagesys /system/bin/dump_image && chmod 755 /system/bin/dump_image");
 		need_libs = 1;
 	} else
 		ui_print("dump_image is already installed, skipping...\n");
 	if (need_libs) {
 		ui_print("Installing libs needed for flash_image and dump_image...\n");
-		__system("cp /res/htcd/libbmlutils.so /system/lib && chmod 755 /system/lib/libbmlutils.so");
-		__system("cp /res/htcd/libflashutils.so /system/lib && chmod 755 /system/lib/libflashutils.so");
-		__system("cp /res/htcd/libmmcutils.so /system/lib && chmod 755 /system/lib/libmmcutils.so");
-		__system("cp /res/htcd/libmtdutils.so /system/lib && chmod 755 /system/lib/libmtdutils.so");
+		system("cp /res/htcd/libbmlutils.so /system/lib && chmod 755 /system/lib/libbmlutils.so");
+		system("cp /res/htcd/libflashutils.so /system/lib && chmod 755 /system/lib/libflashutils.so");
+		system("cp /res/htcd/libmmcutils.so /system/lib && chmod 755 /system/lib/libmmcutils.so");
+		system("cp /res/htcd/libmtdutils.so /system/lib && chmod 755 /system/lib/libmtdutils.so");
 	}
 	ui_print("Installing HTC Dumlock app...\n");
 	mkdir("/data/app", 0777);
-	__system("rm /data/app/com.teamwin.htcdumlock*");
-	__system("cp /res/htcd/HTCDumlock.apk /data/app/com.teamwin.htcdumlock.apk");
+	system("rm /data/app/com.teamwin.htcdumlock*");
+	system("cp /res/htcd/HTCDumlock.apk /data/app/com.teamwin.htcdumlock.apk");
 	sync();
 	ui_print("HTC Dumlock is installed.\n");
 }
@@ -151,7 +146,7 @@
 		return;
 
 	ui_print("Restoring original boot...\n");
-	__system("htcdumlock restore");
+	system("htcdumlock restore");
 	ui_print("Original boot restored.\n");
 }
 
@@ -160,7 +155,7 @@
 		return;
 
 	ui_print("Reflashing recovery to boot...\n");
-	__system("htcdumlock recovery noreboot");
+	system("htcdumlock recovery noreboot");
 	ui_print("Recovery is flashed to boot.\n");
 }